c4e44f999d04b348dbb05ce6dd835866b64850d3
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88   EVT ElVT = VT.getVectorElementType();
89   int Factor = VT.getSizeInBits()/128;
90   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
91                                   VT.getVectorNumElements()/Factor);
92
93   // Extract from UNDEF is UNDEF.
94   if (Vec.getOpcode() == ISD::UNDEF)
95     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
96
97   if (isa<ConstantSDNode>(Idx)) {
98     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
99
100     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
101     // we can match to VEXTRACTF128.
102     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
103
104     // This is the index of the first element of the 128-bit chunk
105     // we want.
106     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
107                                  * ElemsPerChunk);
108
109     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
110     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
111                                  VecIdx);
112
113     return Result;
114   }
115
116   return SDValue();
117 }
118
119 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
120 /// sets things up to match to an AVX VINSERTF128 instruction or a
121 /// simple superregister reference.  Idx is an index in the 128 bits
122 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
123 /// lowering INSERT_VECTOR_ELT operations easier.
124 static SDValue Insert128BitVector(SDValue Result,
125                                   SDValue Vec,
126                                   SDValue Idx,
127                                   SelectionDAG &DAG,
128                                   DebugLoc dl) {
129   if (isa<ConstantSDNode>(Idx)) {
130     EVT VT = Vec.getValueType();
131     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
132
133     EVT ElVT = VT.getVectorElementType();
134     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
135     EVT ResultVT = Result.getValueType();
136
137     // Insert the relevant 128 bits.
138     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
139
140     // This is the index of the first element of the 128-bit chunk
141     // we want.
142     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
143                                  * ElemsPerChunk);
144
145     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
146     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
147                          VecIdx);
148     return Result;
149   }
150
151   return SDValue();
152 }
153
154 /// Given two vectors, concat them.
155 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
156   DebugLoc dl = Lower.getDebugLoc();
157
158   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
159
160   EVT VT = EVT::getVectorVT(*DAG.getContext(),
161                             Lower.getValueType().getVectorElementType(),
162                             Lower.getValueType().getVectorNumElements() * 2);
163
164   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
165   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
166
167   // Insert the upper subvector.
168   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
169                                    DAG.getConstant(
170                                      // This is half the length of the result
171                                      // vector.  Start inserting the upper 128
172                                      // bits here.
173                                      Lower.getValueType().getVectorNumElements(),
174                                      MVT::i32),
175                                    DAG, dl);
176
177   // Insert the lower subvector.
178   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
179   return Vec;
180 }
181
182 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
183   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
184   bool is64Bit = Subtarget->is64Bit();
185
186   if (Subtarget->isTargetEnvMacho()) {
187     if (is64Bit)
188       return new X8664_MachoTargetObjectFile();
189     return new TargetLoweringObjectFileMachO();
190   }
191
192   if (Subtarget->isTargetELF())
193     return new TargetLoweringObjectFileELF();
194   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(TM)) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasXMMInt();
203   X86ScalarSSEf32 = Subtarget->hasXMM();
204   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
205
206   RegInfo = TM.getRegisterInfo();
207   TD = getTargetData();
208
209   // Set up the TargetLowering object.
210   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
211
212   // X86 is weird, it always uses i8 for shift amounts and setcc results.
213   setBooleanContents(ZeroOrOneBooleanContent);
214
215   // For 64-bit since we have so many registers use the ILP scheduler, for
216   // 32-bit code use the register pressure specific scheduling.
217   if (Subtarget->is64Bit())
218     setSchedulingPreference(Sched::ILP);
219   else
220     setSchedulingPreference(Sched::RegPressure);
221   setStackPointerRegisterToSaveRestore(X86StackPtr);
222
223   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
224     // Setup Windows compiler runtime calls.
225     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
226     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
227     setLibcallName(RTLIB::SREM_I64, "_allrem");
228     setLibcallName(RTLIB::UREM_I64, "_aullrem");
229     setLibcallName(RTLIB::MUL_I64, "_allmul");
230     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
231     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
232     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
233     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
234     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
235     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
237     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
238     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
239   }
240
241   if (Subtarget->isTargetDarwin()) {
242     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
243     setUseUnderscoreSetJmp(false);
244     setUseUnderscoreLongJmp(false);
245   } else if (Subtarget->isTargetMingw()) {
246     // MS runtime is weird: it exports _setjmp, but longjmp!
247     setUseUnderscoreSetJmp(true);
248     setUseUnderscoreLongJmp(false);
249   } else {
250     setUseUnderscoreSetJmp(true);
251     setUseUnderscoreLongJmp(true);
252   }
253
254   // Set up the register classes.
255   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
256   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
257   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
258   if (Subtarget->is64Bit())
259     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
260
261   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
262
263   // We don't accept any truncstore of integer registers.
264   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
265   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
266   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
267   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
268   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
269   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
270
271   // SETOEQ and SETUNE require checking two conditions.
272   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
273   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
274   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
275   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
276   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
277   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
278
279   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
280   // operation.
281   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
282   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
283   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
284
285   if (Subtarget->is64Bit()) {
286     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
287     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
288   } else if (!UseSoftFloat) {
289     // We have an algorithm for SSE2->double, and we turn this into a
290     // 64-bit FILD followed by conditional FADD for other targets.
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
292     // We have an algorithm for SSE2, and we turn this into a 64-bit
293     // FILD for other targets.
294     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
295   }
296
297   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
298   // this operation.
299   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
300   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
301
302   if (!UseSoftFloat) {
303     // SSE has no i16 to fp conversion, only i32
304     if (X86ScalarSSEf32) {
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
306       // f32 and f64 cases are Legal, f80 case is not
307       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
308     } else {
309       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
311     }
312   } else {
313     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
314     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
315   }
316
317   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
318   // are Legal, f80 is custom lowered.
319   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
320   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
321
322   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
323   // this operation.
324   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
325   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
326
327   if (X86ScalarSSEf32) {
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
329     // f32 and f64 cases are Legal, f80 case is not
330     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
331   } else {
332     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
334   }
335
336   // Handle FP_TO_UINT by promoting the destination to a larger signed
337   // conversion.
338   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
339   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
340   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
341
342   if (Subtarget->is64Bit()) {
343     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
344     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
345   } else if (!UseSoftFloat) {
346     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
347       // Expand FP_TO_UINT into a select.
348       // FIXME: We would like to use a Custom expander here eventually to do
349       // the optimal thing for SSE vs. the default expansion in the legalizer.
350       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
351     else
352       // With SSE3 we can use fisttpll to convert to a signed i64; without
353       // SSE, we're stuck with a fistpll.
354       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
355   }
356
357   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
358   if (!X86ScalarSSEf64) {
359     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
360     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
361     if (Subtarget->is64Bit()) {
362       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
363       // Without SSE, i64->f64 goes through memory.
364       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
365     }
366   }
367
368   // Scalar integer divide and remainder are lowered to use operations that
369   // produce two results, to match the available instructions. This exposes
370   // the two-result form to trivial CSE, which is able to combine x/y and x%y
371   // into a single instruction.
372   //
373   // Scalar integer multiply-high is also lowered to use two-result
374   // operations, to match the available instructions. However, plain multiply
375   // (low) operations are left as Legal, as there are single-result
376   // instructions for this in x86. Using the two-result multiply instructions
377   // when both high and low results are needed must be arranged by dagcombine.
378   for (unsigned i = 0, e = 4; i != e; ++i) {
379     MVT VT = IntVTs[i];
380     setOperationAction(ISD::MULHS, VT, Expand);
381     setOperationAction(ISD::MULHU, VT, Expand);
382     setOperationAction(ISD::SDIV, VT, Expand);
383     setOperationAction(ISD::UDIV, VT, Expand);
384     setOperationAction(ISD::SREM, VT, Expand);
385     setOperationAction(ISD::UREM, VT, Expand);
386
387     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
388     setOperationAction(ISD::ADDC, VT, Custom);
389     setOperationAction(ISD::ADDE, VT, Custom);
390     setOperationAction(ISD::SUBC, VT, Custom);
391     setOperationAction(ISD::SUBE, VT, Custom);
392   }
393
394   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
395   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
396   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
397   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
398   if (Subtarget->is64Bit())
399     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
400   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
401   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
402   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
403   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
404   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
405   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
406   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
407   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
408
409   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
410   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
411   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
412   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
413   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
414   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
418   }
419
420   if (Subtarget->hasPOPCNT()) {
421     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
422   } else {
423     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
424     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
425     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
426     if (Subtarget->is64Bit())
427       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
428   }
429
430   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
431   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
432
433   // These should be promoted to a larger select which is supported.
434   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
435   // X86 wants to expand cmov itself.
436   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
437   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
439   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
440   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
443   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
448   if (Subtarget->is64Bit()) {
449     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
450     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
451   }
452   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
453
454   // Darwin ABI issue.
455   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
456   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
457   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
458   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
459   if (Subtarget->is64Bit())
460     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
461   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
462   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
463   if (Subtarget->is64Bit()) {
464     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
465     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
466     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
467     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
468     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
469   }
470   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
471   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
472   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
473   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
474   if (Subtarget->is64Bit()) {
475     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
476     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
477     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
478   }
479
480   if (Subtarget->hasXMM())
481     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
482
483   // We may not have a libcall for MEMBARRIER so we should lower this.
484   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
485
486   // On X86 and X86-64, atomic operations are lowered to locked instructions.
487   // Locked instructions, in turn, have implicit fence semantics (all memory
488   // operations are flushed before issuing the locked instruction, and they
489   // are not buffered), so we can fold away the common pattern of
490   // fence-atomic-fence.
491   setShouldFoldAtomicFences(true);
492
493   // Expand certain atomics
494   for (unsigned i = 0, e = 4; i != e; ++i) {
495     MVT VT = IntVTs[i];
496     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
497     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
498   }
499
500   if (!Subtarget->is64Bit()) {
501     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
508   }
509
510   // FIXME - use subtarget debug flags
511   if (!Subtarget->isTargetDarwin() &&
512       !Subtarget->isTargetELF() &&
513       !Subtarget->isTargetCygMing()) {
514     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
518   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
519   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
520   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
521   if (Subtarget->is64Bit()) {
522     setExceptionPointerRegister(X86::RAX);
523     setExceptionSelectorRegister(X86::RDX);
524   } else {
525     setExceptionPointerRegister(X86::EAX);
526     setExceptionSelectorRegister(X86::EDX);
527   }
528   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
529   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
530
531   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
532
533   setOperationAction(ISD::TRAP, MVT::Other, Legal);
534
535   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
536   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
537   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
538   if (Subtarget->is64Bit()) {
539     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
540     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
541   } else {
542     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
543     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
544   }
545
546   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
547   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
548   setOperationAction(ISD::DYNAMIC_STACKALLOC,
549                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
550                      (Subtarget->isTargetCOFF()
551                       && !Subtarget->isTargetEnvMacho()
552                       ? Custom : Expand));
553
554   if (!UseSoftFloat && X86ScalarSSEf64) {
555     // f32 and f64 use SSE.
556     // Set up the FP register classes.
557     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
558     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
559
560     // Use ANDPD to simulate FABS.
561     setOperationAction(ISD::FABS , MVT::f64, Custom);
562     setOperationAction(ISD::FABS , MVT::f32, Custom);
563
564     // Use XORP to simulate FNEG.
565     setOperationAction(ISD::FNEG , MVT::f64, Custom);
566     setOperationAction(ISD::FNEG , MVT::f32, Custom);
567
568     // Use ANDPD and ORPD to simulate FCOPYSIGN.
569     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
570     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571
572     // Lower this to FGETSIGNx86 plus an AND.
573     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
574     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
575
576     // We don't support sin/cos/fmod
577     setOperationAction(ISD::FSIN , MVT::f64, Expand);
578     setOperationAction(ISD::FCOS , MVT::f64, Expand);
579     setOperationAction(ISD::FSIN , MVT::f32, Expand);
580     setOperationAction(ISD::FCOS , MVT::f32, Expand);
581
582     // Expand FP immediates into loads from the stack, except for the special
583     // cases we handle.
584     addLegalFPImmediate(APFloat(+0.0)); // xorpd
585     addLegalFPImmediate(APFloat(+0.0f)); // xorps
586   } else if (!UseSoftFloat && X86ScalarSSEf32) {
587     // Use SSE for f32, x87 for f64.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
590     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
591
592     // Use ANDPS to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f32, Custom);
597
598     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
599
600     // Use ANDPS and ORPS to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // We don't support sin/cos/fmod
605     setOperationAction(ISD::FSIN , MVT::f32, Expand);
606     setOperationAction(ISD::FCOS , MVT::f32, Expand);
607
608     // Special cases we handle for FP constants.
609     addLegalFPImmediate(APFloat(+0.0f)); // xorps
610     addLegalFPImmediate(APFloat(+0.0)); // FLD0
611     addLegalFPImmediate(APFloat(+1.0)); // FLD1
612     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
613     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
614
615     if (!UnsafeFPMath) {
616       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
617       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
618     }
619   } else if (!UseSoftFloat) {
620     // f32 and f64 in x87.
621     // Set up the FP register classes.
622     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
623     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
624
625     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
626     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
627     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
629
630     if (!UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634     addLegalFPImmediate(APFloat(+0.0)); // FLD0
635     addLegalFPImmediate(APFloat(+1.0)); // FLD1
636     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
637     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
638     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
639     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
640     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
641     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
642   }
643
644   // We don't support FMA.
645   setOperationAction(ISD::FMA, MVT::f64, Expand);
646   setOperationAction(ISD::FMA, MVT::f32, Expand);
647
648   // Long double always uses X87.
649   if (!UseSoftFloat) {
650     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
651     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
652     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
653     {
654       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
655       addLegalFPImmediate(TmpFlt);  // FLD0
656       TmpFlt.changeSign();
657       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
658
659       bool ignored;
660       APFloat TmpFlt2(+1.0);
661       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
662                       &ignored);
663       addLegalFPImmediate(TmpFlt2);  // FLD1
664       TmpFlt2.changeSign();
665       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
666     }
667
668     if (!UnsafeFPMath) {
669       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
670       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
671     }
672
673     setOperationAction(ISD::FMA, MVT::f80, Expand);
674   }
675
676   // Always use a library call for pow.
677   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
679   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
680
681   setOperationAction(ISD::FLOG, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
683   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP, MVT::f80, Expand);
685   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
686
687   // First set operation action for all vector types to either promote
688   // (for widening) or expand (for scalarization). Then we will selectively
689   // turn on ones that can be effectively codegen'd.
690   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
691        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
692     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
707     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
710     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
742     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
746     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
747          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
748       setTruncStoreAction((MVT::SimpleValueType)VT,
749                           (MVT::SimpleValueType)InnerVT, Expand);
750     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
752     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!UseSoftFloat && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
765   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
767   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
768   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
769   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
770   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
771   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
772   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
773   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
774   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
775   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
776   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
777   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
778   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
779   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
783   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
784   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
785   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
786   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
788   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
792   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
793
794   if (!UseSoftFloat && Subtarget->hasXMM()) {
795     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
796
797     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
801     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
802     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
803     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
804     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
805     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
806     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
807     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
808     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
809   }
810
811   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
812     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
813
814     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
815     // registers cannot be used even for integer operations.
816     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
819     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
820
821     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
822     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
823     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
824     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
826     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
827     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
828     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
829     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
830     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
831     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
835     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
836     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
837
838     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
841     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
842
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
844     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
848
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
853     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
854
855     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
856     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
857       EVT VT = (MVT::SimpleValueType)i;
858       // Do not attempt to custom lower non-power-of-2 vectors
859       if (!isPowerOf2_32(VT.getVectorNumElements()))
860         continue;
861       // Do not attempt to custom lower non-128-bit vectors
862       if (!VT.is128BitVector())
863         continue;
864       setOperationAction(ISD::BUILD_VECTOR,
865                          VT.getSimpleVT().SimpleTy, Custom);
866       setOperationAction(ISD::VECTOR_SHUFFLE,
867                          VT.getSimpleVT().SimpleTy, Custom);
868       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
869                          VT.getSimpleVT().SimpleTy, Custom);
870     }
871
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
873     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
875     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
877     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
878
879     if (Subtarget->is64Bit()) {
880       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
881       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
882     }
883
884     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
885     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
886       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
887       EVT VT = SVT;
888
889       // Do not attempt to promote non-128-bit vectors
890       if (!VT.is128BitVector())
891         continue;
892
893       setOperationAction(ISD::AND,    SVT, Promote);
894       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
895       setOperationAction(ISD::OR,     SVT, Promote);
896       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
897       setOperationAction(ISD::XOR,    SVT, Promote);
898       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
899       setOperationAction(ISD::LOAD,   SVT, Promote);
900       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
901       setOperationAction(ISD::SELECT, SVT, Promote);
902       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
903     }
904
905     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
906
907     // Custom lower v2i64 and v2f64 selects.
908     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
909     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
910     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
911     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
912
913     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
914     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
915   }
916
917   if (Subtarget->hasSSE41()) {
918     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
923     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
924     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
925     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
926     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
927     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
928
929     // FIXME: Do we need to handle scalar-to-vector here?
930     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
931
932     // Can turn SHL into an integer multiply.
933     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
934     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
935
936     // i8 and i16 vectors are custom , because the source register and source
937     // source memory operand types are not the same width.  f32 vectors are
938     // custom since the immediate controlling the insert encodes additional
939     // information.
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
944
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
949
950     if (Subtarget->is64Bit()) {
951       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
952       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
953     }
954   }
955
956   if (Subtarget->hasSSE2()) {
957     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
958     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
959     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
960
961     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
962     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
963     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
964
965     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
966     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
967   }
968
969   if (Subtarget->hasSSE42())
970     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
971
972   if (!UseSoftFloat && Subtarget->hasAVX()) {
973     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
977     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
978
979     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower several nodes for 256-bit types.
998     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
999                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1000       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1001       EVT VT = SVT;
1002
1003       // Extract subvector is special because the value type
1004       // (result) is 128-bit but the source is 256-bit wide.
1005       if (VT.is128BitVector())
1006         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1007
1008       // Do not attempt to custom lower other non-256-bit vectors
1009       if (!VT.is256BitVector())
1010         continue;
1011
1012       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1013       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1014       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1015       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1016       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1017       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1018     }
1019
1020     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1021     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1022       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1023       EVT VT = SVT;
1024
1025       // Do not attempt to promote non-256-bit vectors
1026       if (!VT.is256BitVector())
1027         continue;
1028
1029       setOperationAction(ISD::AND,    SVT, Promote);
1030       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1031       setOperationAction(ISD::OR,     SVT, Promote);
1032       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1033       setOperationAction(ISD::XOR,    SVT, Promote);
1034       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1035       setOperationAction(ISD::LOAD,   SVT, Promote);
1036       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1037       setOperationAction(ISD::SELECT, SVT, Promote);
1038       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1039     }
1040   }
1041
1042   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1043   // of this type with custom code.
1044   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1045          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1046     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1047   }
1048
1049   // We want to custom lower some of our intrinsics.
1050   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1051
1052
1053   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1054   // handle type legalization for these operations here.
1055   //
1056   // FIXME: We really should do custom legalization for addition and
1057   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1058   // than generic legalization for 64-bit multiplication-with-overflow, though.
1059   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1060     // Add/Sub/Mul with overflow operations are custom lowered.
1061     MVT VT = IntVTs[i];
1062     setOperationAction(ISD::SADDO, VT, Custom);
1063     setOperationAction(ISD::UADDO, VT, Custom);
1064     setOperationAction(ISD::SSUBO, VT, Custom);
1065     setOperationAction(ISD::USUBO, VT, Custom);
1066     setOperationAction(ISD::SMULO, VT, Custom);
1067     setOperationAction(ISD::UMULO, VT, Custom);
1068   }
1069
1070   // There are no 8-bit 3-address imul/mul instructions
1071   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1072   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1073
1074   if (!Subtarget->is64Bit()) {
1075     // These libcalls are not available in 32-bit.
1076     setLibcallName(RTLIB::SHL_I128, 0);
1077     setLibcallName(RTLIB::SRL_I128, 0);
1078     setLibcallName(RTLIB::SRA_I128, 0);
1079   }
1080
1081   // We have target-specific dag combine patterns for the following nodes:
1082   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1083   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1084   setTargetDAGCombine(ISD::BUILD_VECTOR);
1085   setTargetDAGCombine(ISD::SELECT);
1086   setTargetDAGCombine(ISD::SHL);
1087   setTargetDAGCombine(ISD::SRA);
1088   setTargetDAGCombine(ISD::SRL);
1089   setTargetDAGCombine(ISD::OR);
1090   setTargetDAGCombine(ISD::AND);
1091   setTargetDAGCombine(ISD::ADD);
1092   setTargetDAGCombine(ISD::SUB);
1093   setTargetDAGCombine(ISD::STORE);
1094   setTargetDAGCombine(ISD::ZERO_EXTEND);
1095   setTargetDAGCombine(ISD::SINT_TO_FP);
1096   if (Subtarget->is64Bit())
1097     setTargetDAGCombine(ISD::MUL);
1098
1099   computeRegisterProperties();
1100
1101   // On Darwin, -Os means optimize for size without hurting performance,
1102   // do not reduce the limit.
1103   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1104   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1105   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1106   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1107   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1108   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1109   setPrefLoopAlignment(16);
1110   benefitFromCodePlacementOpt = true;
1111
1112   setPrefFunctionAlignment(4);
1113 }
1114
1115
1116 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1117   return MVT::i8;
1118 }
1119
1120
1121 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1122 /// the desired ByVal argument alignment.
1123 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1124   if (MaxAlign == 16)
1125     return;
1126   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1127     if (VTy->getBitWidth() == 128)
1128       MaxAlign = 16;
1129   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1130     unsigned EltAlign = 0;
1131     getMaxByValAlign(ATy->getElementType(), EltAlign);
1132     if (EltAlign > MaxAlign)
1133       MaxAlign = EltAlign;
1134   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1135     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136       unsigned EltAlign = 0;
1137       getMaxByValAlign(STy->getElementType(i), EltAlign);
1138       if (EltAlign > MaxAlign)
1139         MaxAlign = EltAlign;
1140       if (MaxAlign == 16)
1141         break;
1142     }
1143   }
1144   return;
1145 }
1146
1147 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1148 /// function arguments in the caller parameter area. For X86, aggregates
1149 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1150 /// are at 4-byte boundaries.
1151 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1152   if (Subtarget->is64Bit()) {
1153     // Max of 8 and alignment of type.
1154     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1155     if (TyAlign > 8)
1156       return TyAlign;
1157     return 8;
1158   }
1159
1160   unsigned Align = 4;
1161   if (Subtarget->hasXMM())
1162     getMaxByValAlign(Ty, Align);
1163   return Align;
1164 }
1165
1166 /// getOptimalMemOpType - Returns the target specific optimal type for load
1167 /// and store operations as a result of memset, memcpy, and memmove
1168 /// lowering. If DstAlign is zero that means it's safe to destination
1169 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1170 /// means there isn't a need to check it against alignment requirement,
1171 /// probably because the source does not need to be loaded. If
1172 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1173 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1174 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1175 /// constant so it does not need to be loaded.
1176 /// It returns EVT::Other if the type should be determined using generic
1177 /// target-independent logic.
1178 EVT
1179 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1180                                        unsigned DstAlign, unsigned SrcAlign,
1181                                        bool NonScalarIntSafe,
1182                                        bool MemcpyStrSrc,
1183                                        MachineFunction &MF) const {
1184   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1185   // linux.  This is because the stack realignment code can't handle certain
1186   // cases like PR2962.  This should be removed when PR2962 is fixed.
1187   const Function *F = MF.getFunction();
1188   if (NonScalarIntSafe &&
1189       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1190     if (Size >= 16 &&
1191         (Subtarget->isUnalignedMemAccessFast() ||
1192          ((DstAlign == 0 || DstAlign >= 16) &&
1193           (SrcAlign == 0 || SrcAlign >= 16))) &&
1194         Subtarget->getStackAlignment() >= 16) {
1195       if (Subtarget->hasSSE2())
1196         return MVT::v4i32;
1197       if (Subtarget->hasSSE1())
1198         return MVT::v4f32;
1199     } else if (!MemcpyStrSrc && Size >= 8 &&
1200                !Subtarget->is64Bit() &&
1201                Subtarget->getStackAlignment() >= 8 &&
1202                Subtarget->hasXMMInt()) {
1203       // Do not use f64 to lower memcpy if source is string constant. It's
1204       // better to use i32 to avoid the loads.
1205       return MVT::f64;
1206     }
1207   }
1208   if (Subtarget->is64Bit() && Size >= 8)
1209     return MVT::i64;
1210   return MVT::i32;
1211 }
1212
1213 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1214 /// current function.  The returned value is a member of the
1215 /// MachineJumpTableInfo::JTEntryKind enum.
1216 unsigned X86TargetLowering::getJumpTableEncoding() const {
1217   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1218   // symbol.
1219   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1220       Subtarget->isPICStyleGOT())
1221     return MachineJumpTableInfo::EK_Custom32;
1222
1223   // Otherwise, use the normal jump table encoding heuristics.
1224   return TargetLowering::getJumpTableEncoding();
1225 }
1226
1227 const MCExpr *
1228 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1229                                              const MachineBasicBlock *MBB,
1230                                              unsigned uid,MCContext &Ctx) const{
1231   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1232          Subtarget->isPICStyleGOT());
1233   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1234   // entries.
1235   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1236                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1237 }
1238
1239 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1240 /// jumptable.
1241 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1242                                                     SelectionDAG &DAG) const {
1243   if (!Subtarget->is64Bit())
1244     // This doesn't have DebugLoc associated with it, but is not really the
1245     // same as a Register.
1246     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1247   return Table;
1248 }
1249
1250 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1251 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1252 /// MCExpr.
1253 const MCExpr *X86TargetLowering::
1254 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1255                              MCContext &Ctx) const {
1256   // X86-64 uses RIP relative addressing based on the jump table label.
1257   if (Subtarget->isPICStyleRIPRel())
1258     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1259
1260   // Otherwise, the reference is relative to the PIC base.
1261   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1262 }
1263
1264 // FIXME: Why this routine is here? Move to RegInfo!
1265 std::pair<const TargetRegisterClass*, uint8_t>
1266 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1267   const TargetRegisterClass *RRC = 0;
1268   uint8_t Cost = 1;
1269   switch (VT.getSimpleVT().SimpleTy) {
1270   default:
1271     return TargetLowering::findRepresentativeClass(VT);
1272   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1273     RRC = (Subtarget->is64Bit()
1274            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1275     break;
1276   case MVT::x86mmx:
1277     RRC = X86::VR64RegisterClass;
1278     break;
1279   case MVT::f32: case MVT::f64:
1280   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1281   case MVT::v4f32: case MVT::v2f64:
1282   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1283   case MVT::v4f64:
1284     RRC = X86::VR128RegisterClass;
1285     break;
1286   }
1287   return std::make_pair(RRC, Cost);
1288 }
1289
1290 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1291                                                unsigned &Offset) const {
1292   if (!Subtarget->isTargetLinux())
1293     return false;
1294
1295   if (Subtarget->is64Bit()) {
1296     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1297     Offset = 0x28;
1298     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1299       AddressSpace = 256;
1300     else
1301       AddressSpace = 257;
1302   } else {
1303     // %gs:0x14 on i386
1304     Offset = 0x14;
1305     AddressSpace = 256;
1306   }
1307   return true;
1308 }
1309
1310
1311 //===----------------------------------------------------------------------===//
1312 //               Return Value Calling Convention Implementation
1313 //===----------------------------------------------------------------------===//
1314
1315 #include "X86GenCallingConv.inc"
1316
1317 bool
1318 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1319                                   MachineFunction &MF, bool isVarArg,
1320                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1321                         LLVMContext &Context) const {
1322   SmallVector<CCValAssign, 16> RVLocs;
1323   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1324                  RVLocs, Context);
1325   return CCInfo.CheckReturn(Outs, RetCC_X86);
1326 }
1327
1328 SDValue
1329 X86TargetLowering::LowerReturn(SDValue Chain,
1330                                CallingConv::ID CallConv, bool isVarArg,
1331                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1332                                const SmallVectorImpl<SDValue> &OutVals,
1333                                DebugLoc dl, SelectionDAG &DAG) const {
1334   MachineFunction &MF = DAG.getMachineFunction();
1335   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1336
1337   SmallVector<CCValAssign, 16> RVLocs;
1338   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1339                  RVLocs, *DAG.getContext());
1340   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1341
1342   // Add the regs to the liveout set for the function.
1343   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1344   for (unsigned i = 0; i != RVLocs.size(); ++i)
1345     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1346       MRI.addLiveOut(RVLocs[i].getLocReg());
1347
1348   SDValue Flag;
1349
1350   SmallVector<SDValue, 6> RetOps;
1351   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1352   // Operand #1 = Bytes To Pop
1353   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1354                    MVT::i16));
1355
1356   // Copy the result values into the output registers.
1357   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1358     CCValAssign &VA = RVLocs[i];
1359     assert(VA.isRegLoc() && "Can only return in registers!");
1360     SDValue ValToCopy = OutVals[i];
1361     EVT ValVT = ValToCopy.getValueType();
1362
1363     // If this is x86-64, and we disabled SSE, we can't return FP values,
1364     // or SSE or MMX vectors.
1365     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1366          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1367           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1368       report_fatal_error("SSE register return with SSE disabled");
1369     }
1370     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1371     // llvm-gcc has never done it right and no one has noticed, so this
1372     // should be OK for now.
1373     if (ValVT == MVT::f64 &&
1374         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1375       report_fatal_error("SSE2 register return with SSE2 disabled");
1376
1377     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1378     // the RET instruction and handled by the FP Stackifier.
1379     if (VA.getLocReg() == X86::ST0 ||
1380         VA.getLocReg() == X86::ST1) {
1381       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1382       // change the value to the FP stack register class.
1383       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1384         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1385       RetOps.push_back(ValToCopy);
1386       // Don't emit a copytoreg.
1387       continue;
1388     }
1389
1390     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1391     // which is returned in RAX / RDX.
1392     if (Subtarget->is64Bit()) {
1393       if (ValVT == MVT::x86mmx) {
1394         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1395           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1396           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1397                                   ValToCopy);
1398           // If we don't have SSE2 available, convert to v4f32 so the generated
1399           // register is legal.
1400           if (!Subtarget->hasSSE2())
1401             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1402         }
1403       }
1404     }
1405
1406     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1407     Flag = Chain.getValue(1);
1408   }
1409
1410   // The x86-64 ABI for returning structs by value requires that we copy
1411   // the sret argument into %rax for the return. We saved the argument into
1412   // a virtual register in the entry block, so now we copy the value out
1413   // and into %rax.
1414   if (Subtarget->is64Bit() &&
1415       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1416     MachineFunction &MF = DAG.getMachineFunction();
1417     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1418     unsigned Reg = FuncInfo->getSRetReturnReg();
1419     assert(Reg &&
1420            "SRetReturnReg should have been set in LowerFormalArguments().");
1421     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1422
1423     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1424     Flag = Chain.getValue(1);
1425
1426     // RAX now acts like a return value.
1427     MRI.addLiveOut(X86::RAX);
1428   }
1429
1430   RetOps[0] = Chain;  // Update chain.
1431
1432   // Add the flag if we have it.
1433   if (Flag.getNode())
1434     RetOps.push_back(Flag);
1435
1436   return DAG.getNode(X86ISD::RET_FLAG, dl,
1437                      MVT::Other, &RetOps[0], RetOps.size());
1438 }
1439
1440 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1441   if (N->getNumValues() != 1)
1442     return false;
1443   if (!N->hasNUsesOfValue(1, 0))
1444     return false;
1445
1446   SDNode *Copy = *N->use_begin();
1447   if (Copy->getOpcode() != ISD::CopyToReg &&
1448       Copy->getOpcode() != ISD::FP_EXTEND)
1449     return false;
1450
1451   bool HasRet = false;
1452   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1453        UI != UE; ++UI) {
1454     if (UI->getOpcode() != X86ISD::RET_FLAG)
1455       return false;
1456     HasRet = true;
1457   }
1458
1459   return HasRet;
1460 }
1461
1462 EVT
1463 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1464                                             ISD::NodeType ExtendKind) const {
1465   MVT ReturnMVT;
1466   // TODO: Is this also valid on 32-bit?
1467   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1468     ReturnMVT = MVT::i8;
1469   else
1470     ReturnMVT = MVT::i32;
1471
1472   EVT MinVT = getRegisterType(Context, ReturnMVT);
1473   return VT.bitsLT(MinVT) ? MinVT : VT;
1474 }
1475
1476 /// LowerCallResult - Lower the result values of a call into the
1477 /// appropriate copies out of appropriate physical registers.
1478 ///
1479 SDValue
1480 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1481                                    CallingConv::ID CallConv, bool isVarArg,
1482                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1483                                    DebugLoc dl, SelectionDAG &DAG,
1484                                    SmallVectorImpl<SDValue> &InVals) const {
1485
1486   // Assign locations to each value returned by this call.
1487   SmallVector<CCValAssign, 16> RVLocs;
1488   bool Is64Bit = Subtarget->is64Bit();
1489   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1490                  getTargetMachine(), RVLocs, *DAG.getContext());
1491   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1492
1493   // Copy all of the result registers out of their specified physreg.
1494   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1495     CCValAssign &VA = RVLocs[i];
1496     EVT CopyVT = VA.getValVT();
1497
1498     // If this is x86-64, and we disabled SSE, we can't return FP values
1499     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1500         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1501       report_fatal_error("SSE register return with SSE disabled");
1502     }
1503
1504     SDValue Val;
1505
1506     // If this is a call to a function that returns an fp value on the floating
1507     // point stack, we must guarantee the the value is popped from the stack, so
1508     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1509     // if the return value is not used. We use the FpPOP_RETVAL instruction
1510     // instead.
1511     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1512       // If we prefer to use the value in xmm registers, copy it out as f80 and
1513       // use a truncate to move it from fp stack reg to xmm reg.
1514       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1515       SDValue Ops[] = { Chain, InFlag };
1516       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1517                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1518       Val = Chain.getValue(0);
1519
1520       // Round the f80 to the right size, which also moves it to the appropriate
1521       // xmm register.
1522       if (CopyVT != VA.getValVT())
1523         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1524                           // This truncation won't change the value.
1525                           DAG.getIntPtrConstant(1));
1526     } else {
1527       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1528                                  CopyVT, InFlag).getValue(1);
1529       Val = Chain.getValue(0);
1530     }
1531     InFlag = Chain.getValue(2);
1532     InVals.push_back(Val);
1533   }
1534
1535   return Chain;
1536 }
1537
1538
1539 //===----------------------------------------------------------------------===//
1540 //                C & StdCall & Fast Calling Convention implementation
1541 //===----------------------------------------------------------------------===//
1542 //  StdCall calling convention seems to be standard for many Windows' API
1543 //  routines and around. It differs from C calling convention just a little:
1544 //  callee should clean up the stack, not caller. Symbols should be also
1545 //  decorated in some fancy way :) It doesn't support any vector arguments.
1546 //  For info on fast calling convention see Fast Calling Convention (tail call)
1547 //  implementation LowerX86_32FastCCCallTo.
1548
1549 /// CallIsStructReturn - Determines whether a call uses struct return
1550 /// semantics.
1551 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1552   if (Outs.empty())
1553     return false;
1554
1555   return Outs[0].Flags.isSRet();
1556 }
1557
1558 /// ArgsAreStructReturn - Determines whether a function uses struct
1559 /// return semantics.
1560 static bool
1561 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1562   if (Ins.empty())
1563     return false;
1564
1565   return Ins[0].Flags.isSRet();
1566 }
1567
1568 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1569 /// by "Src" to address "Dst" with size and alignment information specified by
1570 /// the specific parameter attribute. The copy will be passed as a byval
1571 /// function parameter.
1572 static SDValue
1573 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1574                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1575                           DebugLoc dl) {
1576   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1577
1578   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1579                        /*isVolatile*/false, /*AlwaysInline=*/true,
1580                        MachinePointerInfo(), MachinePointerInfo());
1581 }
1582
1583 /// IsTailCallConvention - Return true if the calling convention is one that
1584 /// supports tail call optimization.
1585 static bool IsTailCallConvention(CallingConv::ID CC) {
1586   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1587 }
1588
1589 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1590   if (!CI->isTailCall())
1591     return false;
1592
1593   CallSite CS(CI);
1594   CallingConv::ID CalleeCC = CS.getCallingConv();
1595   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1596     return false;
1597
1598   return true;
1599 }
1600
1601 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1602 /// a tailcall target by changing its ABI.
1603 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1604   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1605 }
1606
1607 SDValue
1608 X86TargetLowering::LowerMemArgument(SDValue Chain,
1609                                     CallingConv::ID CallConv,
1610                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1611                                     DebugLoc dl, SelectionDAG &DAG,
1612                                     const CCValAssign &VA,
1613                                     MachineFrameInfo *MFI,
1614                                     unsigned i) const {
1615   // Create the nodes corresponding to a load from this parameter slot.
1616   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1617   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1618   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1619   EVT ValVT;
1620
1621   // If value is passed by pointer we have address passed instead of the value
1622   // itself.
1623   if (VA.getLocInfo() == CCValAssign::Indirect)
1624     ValVT = VA.getLocVT();
1625   else
1626     ValVT = VA.getValVT();
1627
1628   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1629   // changed with more analysis.
1630   // In case of tail call optimization mark all arguments mutable. Since they
1631   // could be overwritten by lowering of arguments in case of a tail call.
1632   if (Flags.isByVal()) {
1633     unsigned Bytes = Flags.getByValSize();
1634     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1635     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1636     return DAG.getFrameIndex(FI, getPointerTy());
1637   } else {
1638     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1639                                     VA.getLocMemOffset(), isImmutable);
1640     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1641     return DAG.getLoad(ValVT, dl, Chain, FIN,
1642                        MachinePointerInfo::getFixedStack(FI),
1643                        false, false, 0);
1644   }
1645 }
1646
1647 SDValue
1648 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1649                                         CallingConv::ID CallConv,
1650                                         bool isVarArg,
1651                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1652                                         DebugLoc dl,
1653                                         SelectionDAG &DAG,
1654                                         SmallVectorImpl<SDValue> &InVals)
1655                                           const {
1656   MachineFunction &MF = DAG.getMachineFunction();
1657   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1658
1659   const Function* Fn = MF.getFunction();
1660   if (Fn->hasExternalLinkage() &&
1661       Subtarget->isTargetCygMing() &&
1662       Fn->getName() == "main")
1663     FuncInfo->setForceFramePointer(true);
1664
1665   MachineFrameInfo *MFI = MF.getFrameInfo();
1666   bool Is64Bit = Subtarget->is64Bit();
1667   bool IsWin64 = Subtarget->isTargetWin64();
1668
1669   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1670          "Var args not supported with calling convention fastcc or ghc");
1671
1672   // Assign locations to all of the incoming arguments.
1673   SmallVector<CCValAssign, 16> ArgLocs;
1674   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1675                  ArgLocs, *DAG.getContext());
1676
1677   // Allocate shadow area for Win64
1678   if (IsWin64) {
1679     CCInfo.AllocateStack(32, 8);
1680   }
1681
1682   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1683
1684   unsigned LastVal = ~0U;
1685   SDValue ArgValue;
1686   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1687     CCValAssign &VA = ArgLocs[i];
1688     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1689     // places.
1690     assert(VA.getValNo() != LastVal &&
1691            "Don't support value assigned to multiple locs yet");
1692     LastVal = VA.getValNo();
1693
1694     if (VA.isRegLoc()) {
1695       EVT RegVT = VA.getLocVT();
1696       TargetRegisterClass *RC = NULL;
1697       if (RegVT == MVT::i32)
1698         RC = X86::GR32RegisterClass;
1699       else if (Is64Bit && RegVT == MVT::i64)
1700         RC = X86::GR64RegisterClass;
1701       else if (RegVT == MVT::f32)
1702         RC = X86::FR32RegisterClass;
1703       else if (RegVT == MVT::f64)
1704         RC = X86::FR64RegisterClass;
1705       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1706         RC = X86::VR256RegisterClass;
1707       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1708         RC = X86::VR128RegisterClass;
1709       else if (RegVT == MVT::x86mmx)
1710         RC = X86::VR64RegisterClass;
1711       else
1712         llvm_unreachable("Unknown argument type!");
1713
1714       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1715       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1716
1717       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1718       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1719       // right size.
1720       if (VA.getLocInfo() == CCValAssign::SExt)
1721         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1722                                DAG.getValueType(VA.getValVT()));
1723       else if (VA.getLocInfo() == CCValAssign::ZExt)
1724         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1725                                DAG.getValueType(VA.getValVT()));
1726       else if (VA.getLocInfo() == CCValAssign::BCvt)
1727         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1728
1729       if (VA.isExtInLoc()) {
1730         // Handle MMX values passed in XMM regs.
1731         if (RegVT.isVector()) {
1732           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1733                                  ArgValue);
1734         } else
1735           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1736       }
1737     } else {
1738       assert(VA.isMemLoc());
1739       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1740     }
1741
1742     // If value is passed via pointer - do a load.
1743     if (VA.getLocInfo() == CCValAssign::Indirect)
1744       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1745                              MachinePointerInfo(), false, false, 0);
1746
1747     InVals.push_back(ArgValue);
1748   }
1749
1750   // The x86-64 ABI for returning structs by value requires that we copy
1751   // the sret argument into %rax for the return. Save the argument into
1752   // a virtual register so that we can access it from the return points.
1753   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1754     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1755     unsigned Reg = FuncInfo->getSRetReturnReg();
1756     if (!Reg) {
1757       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1758       FuncInfo->setSRetReturnReg(Reg);
1759     }
1760     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1761     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1762   }
1763
1764   unsigned StackSize = CCInfo.getNextStackOffset();
1765   // Align stack specially for tail calls.
1766   if (FuncIsMadeTailCallSafe(CallConv))
1767     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1768
1769   // If the function takes variable number of arguments, make a frame index for
1770   // the start of the first vararg value... for expansion of llvm.va_start.
1771   if (isVarArg) {
1772     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1773                     CallConv != CallingConv::X86_ThisCall)) {
1774       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1775     }
1776     if (Is64Bit) {
1777       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1778
1779       // FIXME: We should really autogenerate these arrays
1780       static const unsigned GPR64ArgRegsWin64[] = {
1781         X86::RCX, X86::RDX, X86::R8,  X86::R9
1782       };
1783       static const unsigned GPR64ArgRegs64Bit[] = {
1784         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1785       };
1786       static const unsigned XMMArgRegs64Bit[] = {
1787         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1788         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1789       };
1790       const unsigned *GPR64ArgRegs;
1791       unsigned NumXMMRegs = 0;
1792
1793       if (IsWin64) {
1794         // The XMM registers which might contain var arg parameters are shadowed
1795         // in their paired GPR.  So we only need to save the GPR to their home
1796         // slots.
1797         TotalNumIntRegs = 4;
1798         GPR64ArgRegs = GPR64ArgRegsWin64;
1799       } else {
1800         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1801         GPR64ArgRegs = GPR64ArgRegs64Bit;
1802
1803         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1804       }
1805       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1806                                                        TotalNumIntRegs);
1807
1808       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1809       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1810              "SSE register cannot be used when SSE is disabled!");
1811       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1812              "SSE register cannot be used when SSE is disabled!");
1813       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1814         // Kernel mode asks for SSE to be disabled, so don't push them
1815         // on the stack.
1816         TotalNumXMMRegs = 0;
1817
1818       if (IsWin64) {
1819         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1820         // Get to the caller-allocated home save location.  Add 8 to account
1821         // for the return address.
1822         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1823         FuncInfo->setRegSaveFrameIndex(
1824           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1825         // Fixup to set vararg frame on shadow area (4 x i64).
1826         if (NumIntRegs < 4)
1827           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1828       } else {
1829         // For X86-64, if there are vararg parameters that are passed via
1830         // registers, then we must store them to their spots on the stack so they
1831         // may be loaded by deferencing the result of va_next.
1832         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1833         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1834         FuncInfo->setRegSaveFrameIndex(
1835           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1836                                false));
1837       }
1838
1839       // Store the integer parameter registers.
1840       SmallVector<SDValue, 8> MemOps;
1841       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1842                                         getPointerTy());
1843       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1844       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1845         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1846                                   DAG.getIntPtrConstant(Offset));
1847         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1848                                      X86::GR64RegisterClass);
1849         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1850         SDValue Store =
1851           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1852                        MachinePointerInfo::getFixedStack(
1853                          FuncInfo->getRegSaveFrameIndex(), Offset),
1854                        false, false, 0);
1855         MemOps.push_back(Store);
1856         Offset += 8;
1857       }
1858
1859       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1860         // Now store the XMM (fp + vector) parameter registers.
1861         SmallVector<SDValue, 11> SaveXMMOps;
1862         SaveXMMOps.push_back(Chain);
1863
1864         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1865         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1866         SaveXMMOps.push_back(ALVal);
1867
1868         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1869                                FuncInfo->getRegSaveFrameIndex()));
1870         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1871                                FuncInfo->getVarArgsFPOffset()));
1872
1873         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1874           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1875                                        X86::VR128RegisterClass);
1876           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1877           SaveXMMOps.push_back(Val);
1878         }
1879         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1880                                      MVT::Other,
1881                                      &SaveXMMOps[0], SaveXMMOps.size()));
1882       }
1883
1884       if (!MemOps.empty())
1885         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1886                             &MemOps[0], MemOps.size());
1887     }
1888   }
1889
1890   // Some CCs need callee pop.
1891   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1892     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1893   } else {
1894     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1895     // If this is an sret function, the return should pop the hidden pointer.
1896     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1897       FuncInfo->setBytesToPopOnReturn(4);
1898   }
1899
1900   if (!Is64Bit) {
1901     // RegSaveFrameIndex is X86-64 only.
1902     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1903     if (CallConv == CallingConv::X86_FastCall ||
1904         CallConv == CallingConv::X86_ThisCall)
1905       // fastcc functions can't have varargs.
1906       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1907   }
1908
1909   return Chain;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1914                                     SDValue StackPtr, SDValue Arg,
1915                                     DebugLoc dl, SelectionDAG &DAG,
1916                                     const CCValAssign &VA,
1917                                     ISD::ArgFlagsTy Flags) const {
1918   unsigned LocMemOffset = VA.getLocMemOffset();
1919   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1920   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1921   if (Flags.isByVal())
1922     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1923
1924   return DAG.getStore(Chain, dl, Arg, PtrOff,
1925                       MachinePointerInfo::getStack(LocMemOffset),
1926                       false, false, 0);
1927 }
1928
1929 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1930 /// optimization is performed and it is required.
1931 SDValue
1932 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1933                                            SDValue &OutRetAddr, SDValue Chain,
1934                                            bool IsTailCall, bool Is64Bit,
1935                                            int FPDiff, DebugLoc dl) const {
1936   // Adjust the Return address stack slot.
1937   EVT VT = getPointerTy();
1938   OutRetAddr = getReturnAddressFrameIndex(DAG);
1939
1940   // Load the "old" Return address.
1941   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1942                            false, false, 0);
1943   return SDValue(OutRetAddr.getNode(), 1);
1944 }
1945
1946 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1947 /// optimization is performed and it is required (FPDiff!=0).
1948 static SDValue
1949 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1950                          SDValue Chain, SDValue RetAddrFrIdx,
1951                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1952   // Store the return address to the appropriate stack slot.
1953   if (!FPDiff) return Chain;
1954   // Calculate the new stack slot for the return address.
1955   int SlotSize = Is64Bit ? 8 : 4;
1956   int NewReturnAddrFI =
1957     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1958   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1959   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1960   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1961                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1962                        false, false, 0);
1963   return Chain;
1964 }
1965
1966 SDValue
1967 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1968                              CallingConv::ID CallConv, bool isVarArg,
1969                              bool &isTailCall,
1970                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1971                              const SmallVectorImpl<SDValue> &OutVals,
1972                              const SmallVectorImpl<ISD::InputArg> &Ins,
1973                              DebugLoc dl, SelectionDAG &DAG,
1974                              SmallVectorImpl<SDValue> &InVals) const {
1975   MachineFunction &MF = DAG.getMachineFunction();
1976   bool Is64Bit        = Subtarget->is64Bit();
1977   bool IsWin64        = Subtarget->isTargetWin64();
1978   bool IsStructRet    = CallIsStructReturn(Outs);
1979   bool IsSibcall      = false;
1980
1981   if (isTailCall) {
1982     // Check if it's really possible to do a tail call.
1983     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1984                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1985                                                    Outs, OutVals, Ins, DAG);
1986
1987     // Sibcalls are automatically detected tailcalls which do not require
1988     // ABI changes.
1989     if (!GuaranteedTailCallOpt && isTailCall)
1990       IsSibcall = true;
1991
1992     if (isTailCall)
1993       ++NumTailCalls;
1994   }
1995
1996   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1997          "Var args not supported with calling convention fastcc or ghc");
1998
1999   // Analyze operands of the call, assigning locations to each operand.
2000   SmallVector<CCValAssign, 16> ArgLocs;
2001   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2002                  ArgLocs, *DAG.getContext());
2003
2004   // Allocate shadow area for Win64
2005   if (IsWin64) {
2006     CCInfo.AllocateStack(32, 8);
2007   }
2008
2009   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2010
2011   // Get a count of how many bytes are to be pushed on the stack.
2012   unsigned NumBytes = CCInfo.getNextStackOffset();
2013   if (IsSibcall)
2014     // This is a sibcall. The memory operands are available in caller's
2015     // own caller's stack.
2016     NumBytes = 0;
2017   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2018     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2019
2020   int FPDiff = 0;
2021   if (isTailCall && !IsSibcall) {
2022     // Lower arguments at fp - stackoffset + fpdiff.
2023     unsigned NumBytesCallerPushed =
2024       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2025     FPDiff = NumBytesCallerPushed - NumBytes;
2026
2027     // Set the delta of movement of the returnaddr stackslot.
2028     // But only set if delta is greater than previous delta.
2029     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2030       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2031   }
2032
2033   if (!IsSibcall)
2034     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2035
2036   SDValue RetAddrFrIdx;
2037   // Load return address for tail calls.
2038   if (isTailCall && FPDiff)
2039     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2040                                     Is64Bit, FPDiff, dl);
2041
2042   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2043   SmallVector<SDValue, 8> MemOpChains;
2044   SDValue StackPtr;
2045
2046   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2047   // of tail call optimization arguments are handle later.
2048   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2049     CCValAssign &VA = ArgLocs[i];
2050     EVT RegVT = VA.getLocVT();
2051     SDValue Arg = OutVals[i];
2052     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2053     bool isByVal = Flags.isByVal();
2054
2055     // Promote the value if needed.
2056     switch (VA.getLocInfo()) {
2057     default: llvm_unreachable("Unknown loc info!");
2058     case CCValAssign::Full: break;
2059     case CCValAssign::SExt:
2060       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2061       break;
2062     case CCValAssign::ZExt:
2063       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2064       break;
2065     case CCValAssign::AExt:
2066       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2067         // Special case: passing MMX values in XMM registers.
2068         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2069         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2070         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2071       } else
2072         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2073       break;
2074     case CCValAssign::BCvt:
2075       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2076       break;
2077     case CCValAssign::Indirect: {
2078       // Store the argument.
2079       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2080       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2081       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2082                            MachinePointerInfo::getFixedStack(FI),
2083                            false, false, 0);
2084       Arg = SpillSlot;
2085       break;
2086     }
2087     }
2088
2089     if (VA.isRegLoc()) {
2090       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2091       if (isVarArg && IsWin64) {
2092         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2093         // shadow reg if callee is a varargs function.
2094         unsigned ShadowReg = 0;
2095         switch (VA.getLocReg()) {
2096         case X86::XMM0: ShadowReg = X86::RCX; break;
2097         case X86::XMM1: ShadowReg = X86::RDX; break;
2098         case X86::XMM2: ShadowReg = X86::R8; break;
2099         case X86::XMM3: ShadowReg = X86::R9; break;
2100         }
2101         if (ShadowReg)
2102           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2103       }
2104     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2105       assert(VA.isMemLoc());
2106       if (StackPtr.getNode() == 0)
2107         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2108       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2109                                              dl, DAG, VA, Flags));
2110     }
2111   }
2112
2113   if (!MemOpChains.empty())
2114     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115                         &MemOpChains[0], MemOpChains.size());
2116
2117   // Build a sequence of copy-to-reg nodes chained together with token chain
2118   // and flag operands which copy the outgoing args into registers.
2119   SDValue InFlag;
2120   // Tail call byval lowering might overwrite argument registers so in case of
2121   // tail call optimization the copies to registers are lowered later.
2122   if (!isTailCall)
2123     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2124       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2125                                RegsToPass[i].second, InFlag);
2126       InFlag = Chain.getValue(1);
2127     }
2128
2129   if (Subtarget->isPICStyleGOT()) {
2130     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2131     // GOT pointer.
2132     if (!isTailCall) {
2133       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2134                                DAG.getNode(X86ISD::GlobalBaseReg,
2135                                            DebugLoc(), getPointerTy()),
2136                                InFlag);
2137       InFlag = Chain.getValue(1);
2138     } else {
2139       // If we are tail calling and generating PIC/GOT style code load the
2140       // address of the callee into ECX. The value in ecx is used as target of
2141       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2142       // for tail calls on PIC/GOT architectures. Normally we would just put the
2143       // address of GOT into ebx and then call target@PLT. But for tail calls
2144       // ebx would be restored (since ebx is callee saved) before jumping to the
2145       // target@PLT.
2146
2147       // Note: The actual moving to ECX is done further down.
2148       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2149       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2150           !G->getGlobal()->hasProtectedVisibility())
2151         Callee = LowerGlobalAddress(Callee, DAG);
2152       else if (isa<ExternalSymbolSDNode>(Callee))
2153         Callee = LowerExternalSymbol(Callee, DAG);
2154     }
2155   }
2156
2157   if (Is64Bit && isVarArg && !IsWin64) {
2158     // From AMD64 ABI document:
2159     // For calls that may call functions that use varargs or stdargs
2160     // (prototype-less calls or calls to functions containing ellipsis (...) in
2161     // the declaration) %al is used as hidden argument to specify the number
2162     // of SSE registers used. The contents of %al do not need to match exactly
2163     // the number of registers, but must be an ubound on the number of SSE
2164     // registers used and is in the range 0 - 8 inclusive.
2165
2166     // Count the number of XMM registers allocated.
2167     static const unsigned XMMArgRegs[] = {
2168       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2169       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2170     };
2171     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2172     assert((Subtarget->hasXMM() || !NumXMMRegs)
2173            && "SSE registers cannot be used when SSE is disabled");
2174
2175     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2176                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2177     InFlag = Chain.getValue(1);
2178   }
2179
2180
2181   // For tail calls lower the arguments to the 'real' stack slot.
2182   if (isTailCall) {
2183     // Force all the incoming stack arguments to be loaded from the stack
2184     // before any new outgoing arguments are stored to the stack, because the
2185     // outgoing stack slots may alias the incoming argument stack slots, and
2186     // the alias isn't otherwise explicit. This is slightly more conservative
2187     // than necessary, because it means that each store effectively depends
2188     // on every argument instead of just those arguments it would clobber.
2189     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2190
2191     SmallVector<SDValue, 8> MemOpChains2;
2192     SDValue FIN;
2193     int FI = 0;
2194     // Do not flag preceding copytoreg stuff together with the following stuff.
2195     InFlag = SDValue();
2196     if (GuaranteedTailCallOpt) {
2197       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2198         CCValAssign &VA = ArgLocs[i];
2199         if (VA.isRegLoc())
2200           continue;
2201         assert(VA.isMemLoc());
2202         SDValue Arg = OutVals[i];
2203         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2204         // Create frame index.
2205         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2206         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2207         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2208         FIN = DAG.getFrameIndex(FI, getPointerTy());
2209
2210         if (Flags.isByVal()) {
2211           // Copy relative to framepointer.
2212           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2213           if (StackPtr.getNode() == 0)
2214             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2215                                           getPointerTy());
2216           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2217
2218           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2219                                                            ArgChain,
2220                                                            Flags, DAG, dl));
2221         } else {
2222           // Store relative to framepointer.
2223           MemOpChains2.push_back(
2224             DAG.getStore(ArgChain, dl, Arg, FIN,
2225                          MachinePointerInfo::getFixedStack(FI),
2226                          false, false, 0));
2227         }
2228       }
2229     }
2230
2231     if (!MemOpChains2.empty())
2232       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2233                           &MemOpChains2[0], MemOpChains2.size());
2234
2235     // Copy arguments to their registers.
2236     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2237       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2238                                RegsToPass[i].second, InFlag);
2239       InFlag = Chain.getValue(1);
2240     }
2241     InFlag =SDValue();
2242
2243     // Store the return address to the appropriate stack slot.
2244     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2245                                      FPDiff, dl);
2246   }
2247
2248   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2249     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2250     // In the 64-bit large code model, we have to make all calls
2251     // through a register, since the call instruction's 32-bit
2252     // pc-relative offset may not be large enough to hold the whole
2253     // address.
2254   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2255     // If the callee is a GlobalAddress node (quite common, every direct call
2256     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2257     // it.
2258
2259     // We should use extra load for direct calls to dllimported functions in
2260     // non-JIT mode.
2261     const GlobalValue *GV = G->getGlobal();
2262     if (!GV->hasDLLImportLinkage()) {
2263       unsigned char OpFlags = 0;
2264       bool ExtraLoad = false;
2265       unsigned WrapperKind = ISD::DELETED_NODE;
2266
2267       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2268       // external symbols most go through the PLT in PIC mode.  If the symbol
2269       // has hidden or protected visibility, or if it is static or local, then
2270       // we don't need to use the PLT - we can directly call it.
2271       if (Subtarget->isTargetELF() &&
2272           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2273           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2274         OpFlags = X86II::MO_PLT;
2275       } else if (Subtarget->isPICStyleStubAny() &&
2276                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2277                  (!Subtarget->getTargetTriple().isMacOSX() ||
2278                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2279         // PC-relative references to external symbols should go through $stub,
2280         // unless we're building with the leopard linker or later, which
2281         // automatically synthesizes these stubs.
2282         OpFlags = X86II::MO_DARWIN_STUB;
2283       } else if (Subtarget->isPICStyleRIPRel() &&
2284                  isa<Function>(GV) &&
2285                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2286         // If the function is marked as non-lazy, generate an indirect call
2287         // which loads from the GOT directly. This avoids runtime overhead
2288         // at the cost of eager binding (and one extra byte of encoding).
2289         OpFlags = X86II::MO_GOTPCREL;
2290         WrapperKind = X86ISD::WrapperRIP;
2291         ExtraLoad = true;
2292       }
2293
2294       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2295                                           G->getOffset(), OpFlags);
2296
2297       // Add a wrapper if needed.
2298       if (WrapperKind != ISD::DELETED_NODE)
2299         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2300       // Add extra indirection if needed.
2301       if (ExtraLoad)
2302         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2303                              MachinePointerInfo::getGOT(),
2304                              false, false, 0);
2305     }
2306   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2307     unsigned char OpFlags = 0;
2308
2309     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2310     // external symbols should go through the PLT.
2311     if (Subtarget->isTargetELF() &&
2312         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2313       OpFlags = X86II::MO_PLT;
2314     } else if (Subtarget->isPICStyleStubAny() &&
2315                (!Subtarget->getTargetTriple().isMacOSX() ||
2316                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2317       // PC-relative references to external symbols should go through $stub,
2318       // unless we're building with the leopard linker or later, which
2319       // automatically synthesizes these stubs.
2320       OpFlags = X86II::MO_DARWIN_STUB;
2321     }
2322
2323     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2324                                          OpFlags);
2325   }
2326
2327   // Returns a chain & a flag for retval copy to use.
2328   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2329   SmallVector<SDValue, 8> Ops;
2330
2331   if (!IsSibcall && isTailCall) {
2332     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2333                            DAG.getIntPtrConstant(0, true), InFlag);
2334     InFlag = Chain.getValue(1);
2335   }
2336
2337   Ops.push_back(Chain);
2338   Ops.push_back(Callee);
2339
2340   if (isTailCall)
2341     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2342
2343   // Add argument registers to the end of the list so that they are known live
2344   // into the call.
2345   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2346     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2347                                   RegsToPass[i].second.getValueType()));
2348
2349   // Add an implicit use GOT pointer in EBX.
2350   if (!isTailCall && Subtarget->isPICStyleGOT())
2351     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2352
2353   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2354   if (Is64Bit && isVarArg && !IsWin64)
2355     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2356
2357   if (InFlag.getNode())
2358     Ops.push_back(InFlag);
2359
2360   if (isTailCall) {
2361     // We used to do:
2362     //// If this is the first return lowered for this function, add the regs
2363     //// to the liveout set for the function.
2364     // This isn't right, although it's probably harmless on x86; liveouts
2365     // should be computed from returns not tail calls.  Consider a void
2366     // function making a tail call to a function returning int.
2367     return DAG.getNode(X86ISD::TC_RETURN, dl,
2368                        NodeTys, &Ops[0], Ops.size());
2369   }
2370
2371   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2372   InFlag = Chain.getValue(1);
2373
2374   // Create the CALLSEQ_END node.
2375   unsigned NumBytesForCalleeToPush;
2376   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2377     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2378   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2379     // If this is a call to a struct-return function, the callee
2380     // pops the hidden struct pointer, so we have to push it back.
2381     // This is common for Darwin/X86, Linux & Mingw32 targets.
2382     NumBytesForCalleeToPush = 4;
2383   else
2384     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2385
2386   // Returns a flag for retval copy to use.
2387   if (!IsSibcall) {
2388     Chain = DAG.getCALLSEQ_END(Chain,
2389                                DAG.getIntPtrConstant(NumBytes, true),
2390                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2391                                                      true),
2392                                InFlag);
2393     InFlag = Chain.getValue(1);
2394   }
2395
2396   // Handle result values, copying them out of physregs into vregs that we
2397   // return.
2398   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2399                          Ins, dl, DAG, InVals);
2400 }
2401
2402
2403 //===----------------------------------------------------------------------===//
2404 //                Fast Calling Convention (tail call) implementation
2405 //===----------------------------------------------------------------------===//
2406
2407 //  Like std call, callee cleans arguments, convention except that ECX is
2408 //  reserved for storing the tail called function address. Only 2 registers are
2409 //  free for argument passing (inreg). Tail call optimization is performed
2410 //  provided:
2411 //                * tailcallopt is enabled
2412 //                * caller/callee are fastcc
2413 //  On X86_64 architecture with GOT-style position independent code only local
2414 //  (within module) calls are supported at the moment.
2415 //  To keep the stack aligned according to platform abi the function
2416 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2417 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2418 //  If a tail called function callee has more arguments than the caller the
2419 //  caller needs to make sure that there is room to move the RETADDR to. This is
2420 //  achieved by reserving an area the size of the argument delta right after the
2421 //  original REtADDR, but before the saved framepointer or the spilled registers
2422 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2423 //  stack layout:
2424 //    arg1
2425 //    arg2
2426 //    RETADDR
2427 //    [ new RETADDR
2428 //      move area ]
2429 //    (possible EBP)
2430 //    ESI
2431 //    EDI
2432 //    local1 ..
2433
2434 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2435 /// for a 16 byte align requirement.
2436 unsigned
2437 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2438                                                SelectionDAG& DAG) const {
2439   MachineFunction &MF = DAG.getMachineFunction();
2440   const TargetMachine &TM = MF.getTarget();
2441   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2442   unsigned StackAlignment = TFI.getStackAlignment();
2443   uint64_t AlignMask = StackAlignment - 1;
2444   int64_t Offset = StackSize;
2445   uint64_t SlotSize = TD->getPointerSize();
2446   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2447     // Number smaller than 12 so just add the difference.
2448     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2449   } else {
2450     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2451     Offset = ((~AlignMask) & Offset) + StackAlignment +
2452       (StackAlignment-SlotSize);
2453   }
2454   return Offset;
2455 }
2456
2457 /// MatchingStackOffset - Return true if the given stack call argument is
2458 /// already available in the same position (relatively) of the caller's
2459 /// incoming argument stack.
2460 static
2461 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2462                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2463                          const X86InstrInfo *TII) {
2464   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2465   int FI = INT_MAX;
2466   if (Arg.getOpcode() == ISD::CopyFromReg) {
2467     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2468     if (!TargetRegisterInfo::isVirtualRegister(VR))
2469       return false;
2470     MachineInstr *Def = MRI->getVRegDef(VR);
2471     if (!Def)
2472       return false;
2473     if (!Flags.isByVal()) {
2474       if (!TII->isLoadFromStackSlot(Def, FI))
2475         return false;
2476     } else {
2477       unsigned Opcode = Def->getOpcode();
2478       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2479           Def->getOperand(1).isFI()) {
2480         FI = Def->getOperand(1).getIndex();
2481         Bytes = Flags.getByValSize();
2482       } else
2483         return false;
2484     }
2485   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2486     if (Flags.isByVal())
2487       // ByVal argument is passed in as a pointer but it's now being
2488       // dereferenced. e.g.
2489       // define @foo(%struct.X* %A) {
2490       //   tail call @bar(%struct.X* byval %A)
2491       // }
2492       return false;
2493     SDValue Ptr = Ld->getBasePtr();
2494     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2495     if (!FINode)
2496       return false;
2497     FI = FINode->getIndex();
2498   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2499     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2500     FI = FINode->getIndex();
2501     Bytes = Flags.getByValSize();
2502   } else
2503     return false;
2504
2505   assert(FI != INT_MAX);
2506   if (!MFI->isFixedObjectIndex(FI))
2507     return false;
2508   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2509 }
2510
2511 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2512 /// for tail call optimization. Targets which want to do tail call
2513 /// optimization should implement this function.
2514 bool
2515 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2516                                                      CallingConv::ID CalleeCC,
2517                                                      bool isVarArg,
2518                                                      bool isCalleeStructRet,
2519                                                      bool isCallerStructRet,
2520                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2521                                     const SmallVectorImpl<SDValue> &OutVals,
2522                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2523                                                      SelectionDAG& DAG) const {
2524   if (!IsTailCallConvention(CalleeCC) &&
2525       CalleeCC != CallingConv::C)
2526     return false;
2527
2528   // If -tailcallopt is specified, make fastcc functions tail-callable.
2529   const MachineFunction &MF = DAG.getMachineFunction();
2530   const Function *CallerF = DAG.getMachineFunction().getFunction();
2531   CallingConv::ID CallerCC = CallerF->getCallingConv();
2532   bool CCMatch = CallerCC == CalleeCC;
2533
2534   if (GuaranteedTailCallOpt) {
2535     if (IsTailCallConvention(CalleeCC) && CCMatch)
2536       return true;
2537     return false;
2538   }
2539
2540   // Look for obvious safe cases to perform tail call optimization that do not
2541   // require ABI changes. This is what gcc calls sibcall.
2542
2543   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2544   // emit a special epilogue.
2545   if (RegInfo->needsStackRealignment(MF))
2546     return false;
2547
2548   // Also avoid sibcall optimization if either caller or callee uses struct
2549   // return semantics.
2550   if (isCalleeStructRet || isCallerStructRet)
2551     return false;
2552
2553   // An stdcall caller is expected to clean up its arguments; the callee
2554   // isn't going to do that.
2555   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2556     return false;
2557
2558   // Do not sibcall optimize vararg calls unless all arguments are passed via
2559   // registers.
2560   if (isVarArg && !Outs.empty()) {
2561
2562     // Optimizing for varargs on Win64 is unlikely to be safe without
2563     // additional testing.
2564     if (Subtarget->isTargetWin64())
2565       return false;
2566
2567     SmallVector<CCValAssign, 16> ArgLocs;
2568     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2569                    getTargetMachine(), ArgLocs, *DAG.getContext());
2570
2571     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2572     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2573       if (!ArgLocs[i].isRegLoc())
2574         return false;
2575   }
2576
2577   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2578   // Therefore if it's not used by the call it is not safe to optimize this into
2579   // a sibcall.
2580   bool Unused = false;
2581   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2582     if (!Ins[i].Used) {
2583       Unused = true;
2584       break;
2585     }
2586   }
2587   if (Unused) {
2588     SmallVector<CCValAssign, 16> RVLocs;
2589     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2590                    getTargetMachine(), RVLocs, *DAG.getContext());
2591     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2592     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2593       CCValAssign &VA = RVLocs[i];
2594       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2595         return false;
2596     }
2597   }
2598
2599   // If the calling conventions do not match, then we'd better make sure the
2600   // results are returned in the same way as what the caller expects.
2601   if (!CCMatch) {
2602     SmallVector<CCValAssign, 16> RVLocs1;
2603     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2604                     getTargetMachine(), RVLocs1, *DAG.getContext());
2605     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2606
2607     SmallVector<CCValAssign, 16> RVLocs2;
2608     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2609                     getTargetMachine(), RVLocs2, *DAG.getContext());
2610     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2611
2612     if (RVLocs1.size() != RVLocs2.size())
2613       return false;
2614     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2615       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2616         return false;
2617       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2618         return false;
2619       if (RVLocs1[i].isRegLoc()) {
2620         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2621           return false;
2622       } else {
2623         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2624           return false;
2625       }
2626     }
2627   }
2628
2629   // If the callee takes no arguments then go on to check the results of the
2630   // call.
2631   if (!Outs.empty()) {
2632     // Check if stack adjustment is needed. For now, do not do this if any
2633     // argument is passed on the stack.
2634     SmallVector<CCValAssign, 16> ArgLocs;
2635     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2636                    getTargetMachine(), ArgLocs, *DAG.getContext());
2637
2638     // Allocate shadow area for Win64
2639     if (Subtarget->isTargetWin64()) {
2640       CCInfo.AllocateStack(32, 8);
2641     }
2642
2643     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2644     if (CCInfo.getNextStackOffset()) {
2645       MachineFunction &MF = DAG.getMachineFunction();
2646       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2647         return false;
2648
2649       // Check if the arguments are already laid out in the right way as
2650       // the caller's fixed stack objects.
2651       MachineFrameInfo *MFI = MF.getFrameInfo();
2652       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2653       const X86InstrInfo *TII =
2654         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2655       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2656         CCValAssign &VA = ArgLocs[i];
2657         SDValue Arg = OutVals[i];
2658         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2659         if (VA.getLocInfo() == CCValAssign::Indirect)
2660           return false;
2661         if (!VA.isRegLoc()) {
2662           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2663                                    MFI, MRI, TII))
2664             return false;
2665         }
2666       }
2667     }
2668
2669     // If the tailcall address may be in a register, then make sure it's
2670     // possible to register allocate for it. In 32-bit, the call address can
2671     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2672     // callee-saved registers are restored. These happen to be the same
2673     // registers used to pass 'inreg' arguments so watch out for those.
2674     if (!Subtarget->is64Bit() &&
2675         !isa<GlobalAddressSDNode>(Callee) &&
2676         !isa<ExternalSymbolSDNode>(Callee)) {
2677       unsigned NumInRegs = 0;
2678       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2679         CCValAssign &VA = ArgLocs[i];
2680         if (!VA.isRegLoc())
2681           continue;
2682         unsigned Reg = VA.getLocReg();
2683         switch (Reg) {
2684         default: break;
2685         case X86::EAX: case X86::EDX: case X86::ECX:
2686           if (++NumInRegs == 3)
2687             return false;
2688           break;
2689         }
2690       }
2691     }
2692   }
2693
2694   return true;
2695 }
2696
2697 FastISel *
2698 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2699   return X86::createFastISel(funcInfo);
2700 }
2701
2702
2703 //===----------------------------------------------------------------------===//
2704 //                           Other Lowering Hooks
2705 //===----------------------------------------------------------------------===//
2706
2707 static bool MayFoldLoad(SDValue Op) {
2708   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2709 }
2710
2711 static bool MayFoldIntoStore(SDValue Op) {
2712   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2713 }
2714
2715 static bool isTargetShuffle(unsigned Opcode) {
2716   switch(Opcode) {
2717   default: return false;
2718   case X86ISD::PSHUFD:
2719   case X86ISD::PSHUFHW:
2720   case X86ISD::PSHUFLW:
2721   case X86ISD::SHUFPD:
2722   case X86ISD::PALIGN:
2723   case X86ISD::SHUFPS:
2724   case X86ISD::MOVLHPS:
2725   case X86ISD::MOVLHPD:
2726   case X86ISD::MOVHLPS:
2727   case X86ISD::MOVLPS:
2728   case X86ISD::MOVLPD:
2729   case X86ISD::MOVSHDUP:
2730   case X86ISD::MOVSLDUP:
2731   case X86ISD::MOVDDUP:
2732   case X86ISD::MOVSS:
2733   case X86ISD::MOVSD:
2734   case X86ISD::UNPCKLPS:
2735   case X86ISD::UNPCKLPD:
2736   case X86ISD::VUNPCKLPS:
2737   case X86ISD::VUNPCKLPD:
2738   case X86ISD::VUNPCKLPSY:
2739   case X86ISD::VUNPCKLPDY:
2740   case X86ISD::PUNPCKLWD:
2741   case X86ISD::PUNPCKLBW:
2742   case X86ISD::PUNPCKLDQ:
2743   case X86ISD::PUNPCKLQDQ:
2744   case X86ISD::UNPCKHPS:
2745   case X86ISD::UNPCKHPD:
2746   case X86ISD::PUNPCKHWD:
2747   case X86ISD::PUNPCKHBW:
2748   case X86ISD::PUNPCKHDQ:
2749   case X86ISD::PUNPCKHQDQ:
2750     return true;
2751   }
2752   return false;
2753 }
2754
2755 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2756                                                SDValue V1, SelectionDAG &DAG) {
2757   switch(Opc) {
2758   default: llvm_unreachable("Unknown x86 shuffle node");
2759   case X86ISD::MOVSHDUP:
2760   case X86ISD::MOVSLDUP:
2761   case X86ISD::MOVDDUP:
2762     return DAG.getNode(Opc, dl, VT, V1);
2763   }
2764
2765   return SDValue();
2766 }
2767
2768 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2769                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2770   switch(Opc) {
2771   default: llvm_unreachable("Unknown x86 shuffle node");
2772   case X86ISD::PSHUFD:
2773   case X86ISD::PSHUFHW:
2774   case X86ISD::PSHUFLW:
2775     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2776   }
2777
2778   return SDValue();
2779 }
2780
2781 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2782                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2783   switch(Opc) {
2784   default: llvm_unreachable("Unknown x86 shuffle node");
2785   case X86ISD::PALIGN:
2786   case X86ISD::SHUFPD:
2787   case X86ISD::SHUFPS:
2788     return DAG.getNode(Opc, dl, VT, V1, V2,
2789                        DAG.getConstant(TargetMask, MVT::i8));
2790   }
2791   return SDValue();
2792 }
2793
2794 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2795                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2796   switch(Opc) {
2797   default: llvm_unreachable("Unknown x86 shuffle node");
2798   case X86ISD::MOVLHPS:
2799   case X86ISD::MOVLHPD:
2800   case X86ISD::MOVHLPS:
2801   case X86ISD::MOVLPS:
2802   case X86ISD::MOVLPD:
2803   case X86ISD::MOVSS:
2804   case X86ISD::MOVSD:
2805   case X86ISD::UNPCKLPS:
2806   case X86ISD::UNPCKLPD:
2807   case X86ISD::VUNPCKLPS:
2808   case X86ISD::VUNPCKLPD:
2809   case X86ISD::VUNPCKLPSY:
2810   case X86ISD::VUNPCKLPDY:
2811   case X86ISD::PUNPCKLWD:
2812   case X86ISD::PUNPCKLBW:
2813   case X86ISD::PUNPCKLDQ:
2814   case X86ISD::PUNPCKLQDQ:
2815   case X86ISD::UNPCKHPS:
2816   case X86ISD::UNPCKHPD:
2817   case X86ISD::PUNPCKHWD:
2818   case X86ISD::PUNPCKHBW:
2819   case X86ISD::PUNPCKHDQ:
2820   case X86ISD::PUNPCKHQDQ:
2821     return DAG.getNode(Opc, dl, VT, V1, V2);
2822   }
2823   return SDValue();
2824 }
2825
2826 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2827   MachineFunction &MF = DAG.getMachineFunction();
2828   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2829   int ReturnAddrIndex = FuncInfo->getRAIndex();
2830
2831   if (ReturnAddrIndex == 0) {
2832     // Set up a frame object for the return address.
2833     uint64_t SlotSize = TD->getPointerSize();
2834     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2835                                                            false);
2836     FuncInfo->setRAIndex(ReturnAddrIndex);
2837   }
2838
2839   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2840 }
2841
2842
2843 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2844                                        bool hasSymbolicDisplacement) {
2845   // Offset should fit into 32 bit immediate field.
2846   if (!isInt<32>(Offset))
2847     return false;
2848
2849   // If we don't have a symbolic displacement - we don't have any extra
2850   // restrictions.
2851   if (!hasSymbolicDisplacement)
2852     return true;
2853
2854   // FIXME: Some tweaks might be needed for medium code model.
2855   if (M != CodeModel::Small && M != CodeModel::Kernel)
2856     return false;
2857
2858   // For small code model we assume that latest object is 16MB before end of 31
2859   // bits boundary. We may also accept pretty large negative constants knowing
2860   // that all objects are in the positive half of address space.
2861   if (M == CodeModel::Small && Offset < 16*1024*1024)
2862     return true;
2863
2864   // For kernel code model we know that all object resist in the negative half
2865   // of 32bits address space. We may not accept negative offsets, since they may
2866   // be just off and we may accept pretty large positive ones.
2867   if (M == CodeModel::Kernel && Offset > 0)
2868     return true;
2869
2870   return false;
2871 }
2872
2873 /// isCalleePop - Determines whether the callee is required to pop its
2874 /// own arguments. Callee pop is necessary to support tail calls.
2875 bool X86::isCalleePop(CallingConv::ID CallingConv,
2876                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2877   if (IsVarArg)
2878     return false;
2879
2880   switch (CallingConv) {
2881   default:
2882     return false;
2883   case CallingConv::X86_StdCall:
2884     return !is64Bit;
2885   case CallingConv::X86_FastCall:
2886     return !is64Bit;
2887   case CallingConv::X86_ThisCall:
2888     return !is64Bit;
2889   case CallingConv::Fast:
2890     return TailCallOpt;
2891   case CallingConv::GHC:
2892     return TailCallOpt;
2893   }
2894 }
2895
2896 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2897 /// specific condition code, returning the condition code and the LHS/RHS of the
2898 /// comparison to make.
2899 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2900                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2901   if (!isFP) {
2902     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2903       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2904         // X > -1   -> X == 0, jump !sign.
2905         RHS = DAG.getConstant(0, RHS.getValueType());
2906         return X86::COND_NS;
2907       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2908         // X < 0   -> X == 0, jump on sign.
2909         return X86::COND_S;
2910       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2911         // X < 1   -> X <= 0
2912         RHS = DAG.getConstant(0, RHS.getValueType());
2913         return X86::COND_LE;
2914       }
2915     }
2916
2917     switch (SetCCOpcode) {
2918     default: llvm_unreachable("Invalid integer condition!");
2919     case ISD::SETEQ:  return X86::COND_E;
2920     case ISD::SETGT:  return X86::COND_G;
2921     case ISD::SETGE:  return X86::COND_GE;
2922     case ISD::SETLT:  return X86::COND_L;
2923     case ISD::SETLE:  return X86::COND_LE;
2924     case ISD::SETNE:  return X86::COND_NE;
2925     case ISD::SETULT: return X86::COND_B;
2926     case ISD::SETUGT: return X86::COND_A;
2927     case ISD::SETULE: return X86::COND_BE;
2928     case ISD::SETUGE: return X86::COND_AE;
2929     }
2930   }
2931
2932   // First determine if it is required or is profitable to flip the operands.
2933
2934   // If LHS is a foldable load, but RHS is not, flip the condition.
2935   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2936       !ISD::isNON_EXTLoad(RHS.getNode())) {
2937     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2938     std::swap(LHS, RHS);
2939   }
2940
2941   switch (SetCCOpcode) {
2942   default: break;
2943   case ISD::SETOLT:
2944   case ISD::SETOLE:
2945   case ISD::SETUGT:
2946   case ISD::SETUGE:
2947     std::swap(LHS, RHS);
2948     break;
2949   }
2950
2951   // On a floating point condition, the flags are set as follows:
2952   // ZF  PF  CF   op
2953   //  0 | 0 | 0 | X > Y
2954   //  0 | 0 | 1 | X < Y
2955   //  1 | 0 | 0 | X == Y
2956   //  1 | 1 | 1 | unordered
2957   switch (SetCCOpcode) {
2958   default: llvm_unreachable("Condcode should be pre-legalized away");
2959   case ISD::SETUEQ:
2960   case ISD::SETEQ:   return X86::COND_E;
2961   case ISD::SETOLT:              // flipped
2962   case ISD::SETOGT:
2963   case ISD::SETGT:   return X86::COND_A;
2964   case ISD::SETOLE:              // flipped
2965   case ISD::SETOGE:
2966   case ISD::SETGE:   return X86::COND_AE;
2967   case ISD::SETUGT:              // flipped
2968   case ISD::SETULT:
2969   case ISD::SETLT:   return X86::COND_B;
2970   case ISD::SETUGE:              // flipped
2971   case ISD::SETULE:
2972   case ISD::SETLE:   return X86::COND_BE;
2973   case ISD::SETONE:
2974   case ISD::SETNE:   return X86::COND_NE;
2975   case ISD::SETUO:   return X86::COND_P;
2976   case ISD::SETO:    return X86::COND_NP;
2977   case ISD::SETOEQ:
2978   case ISD::SETUNE:  return X86::COND_INVALID;
2979   }
2980 }
2981
2982 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2983 /// code. Current x86 isa includes the following FP cmov instructions:
2984 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2985 static bool hasFPCMov(unsigned X86CC) {
2986   switch (X86CC) {
2987   default:
2988     return false;
2989   case X86::COND_B:
2990   case X86::COND_BE:
2991   case X86::COND_E:
2992   case X86::COND_P:
2993   case X86::COND_A:
2994   case X86::COND_AE:
2995   case X86::COND_NE:
2996   case X86::COND_NP:
2997     return true;
2998   }
2999 }
3000
3001 /// isFPImmLegal - Returns true if the target can instruction select the
3002 /// specified FP immediate natively. If false, the legalizer will
3003 /// materialize the FP immediate as a load from a constant pool.
3004 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3005   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3006     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3007       return true;
3008   }
3009   return false;
3010 }
3011
3012 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3013 /// the specified range (L, H].
3014 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3015   return (Val < 0) || (Val >= Low && Val < Hi);
3016 }
3017
3018 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3019 /// specified value.
3020 static bool isUndefOrEqual(int Val, int CmpVal) {
3021   if (Val < 0 || Val == CmpVal)
3022     return true;
3023   return false;
3024 }
3025
3026 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3027 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3028 /// the second operand.
3029 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3030   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3031     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3032   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3033     return (Mask[0] < 2 && Mask[1] < 2);
3034   return false;
3035 }
3036
3037 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3038   SmallVector<int, 8> M;
3039   N->getMask(M);
3040   return ::isPSHUFDMask(M, N->getValueType(0));
3041 }
3042
3043 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3044 /// is suitable for input to PSHUFHW.
3045 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3046   if (VT != MVT::v8i16)
3047     return false;
3048
3049   // Lower quadword copied in order or undef.
3050   for (int i = 0; i != 4; ++i)
3051     if (Mask[i] >= 0 && Mask[i] != i)
3052       return false;
3053
3054   // Upper quadword shuffled.
3055   for (int i = 4; i != 8; ++i)
3056     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3057       return false;
3058
3059   return true;
3060 }
3061
3062 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3063   SmallVector<int, 8> M;
3064   N->getMask(M);
3065   return ::isPSHUFHWMask(M, N->getValueType(0));
3066 }
3067
3068 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3069 /// is suitable for input to PSHUFLW.
3070 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3071   if (VT != MVT::v8i16)
3072     return false;
3073
3074   // Upper quadword copied in order.
3075   for (int i = 4; i != 8; ++i)
3076     if (Mask[i] >= 0 && Mask[i] != i)
3077       return false;
3078
3079   // Lower quadword shuffled.
3080   for (int i = 0; i != 4; ++i)
3081     if (Mask[i] >= 4)
3082       return false;
3083
3084   return true;
3085 }
3086
3087 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3088   SmallVector<int, 8> M;
3089   N->getMask(M);
3090   return ::isPSHUFLWMask(M, N->getValueType(0));
3091 }
3092
3093 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3094 /// is suitable for input to PALIGNR.
3095 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3096                           bool hasSSSE3) {
3097   int i, e = VT.getVectorNumElements();
3098
3099   // Do not handle v2i64 / v2f64 shuffles with palignr.
3100   if (e < 4 || !hasSSSE3)
3101     return false;
3102
3103   for (i = 0; i != e; ++i)
3104     if (Mask[i] >= 0)
3105       break;
3106
3107   // All undef, not a palignr.
3108   if (i == e)
3109     return false;
3110
3111   // Determine if it's ok to perform a palignr with only the LHS, since we
3112   // don't have access to the actual shuffle elements to see if RHS is undef.
3113   bool Unary = Mask[i] < (int)e;
3114   bool NeedsUnary = false;
3115
3116   int s = Mask[i] - i;
3117
3118   // Check the rest of the elements to see if they are consecutive.
3119   for (++i; i != e; ++i) {
3120     int m = Mask[i];
3121     if (m < 0)
3122       continue;
3123
3124     Unary = Unary && (m < (int)e);
3125     NeedsUnary = NeedsUnary || (m < s);
3126
3127     if (NeedsUnary && !Unary)
3128       return false;
3129     if (Unary && m != ((s+i) & (e-1)))
3130       return false;
3131     if (!Unary && m != (s+i))
3132       return false;
3133   }
3134   return true;
3135 }
3136
3137 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3138   SmallVector<int, 8> M;
3139   N->getMask(M);
3140   return ::isPALIGNRMask(M, N->getValueType(0), true);
3141 }
3142
3143 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3144 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3145 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3146   int NumElems = VT.getVectorNumElements();
3147   if (NumElems != 2 && NumElems != 4)
3148     return false;
3149
3150   int Half = NumElems / 2;
3151   for (int i = 0; i < Half; ++i)
3152     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3153       return false;
3154   for (int i = Half; i < NumElems; ++i)
3155     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3156       return false;
3157
3158   return true;
3159 }
3160
3161 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3162   SmallVector<int, 8> M;
3163   N->getMask(M);
3164   return ::isSHUFPMask(M, N->getValueType(0));
3165 }
3166
3167 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3168 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3169 /// half elements to come from vector 1 (which would equal the dest.) and
3170 /// the upper half to come from vector 2.
3171 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3172   int NumElems = VT.getVectorNumElements();
3173
3174   if (NumElems != 2 && NumElems != 4)
3175     return false;
3176
3177   int Half = NumElems / 2;
3178   for (int i = 0; i < Half; ++i)
3179     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3180       return false;
3181   for (int i = Half; i < NumElems; ++i)
3182     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3183       return false;
3184   return true;
3185 }
3186
3187 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3188   SmallVector<int, 8> M;
3189   N->getMask(M);
3190   return isCommutedSHUFPMask(M, N->getValueType(0));
3191 }
3192
3193 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3194 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3195 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3196   if (N->getValueType(0).getVectorNumElements() != 4)
3197     return false;
3198
3199   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3200   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3201          isUndefOrEqual(N->getMaskElt(1), 7) &&
3202          isUndefOrEqual(N->getMaskElt(2), 2) &&
3203          isUndefOrEqual(N->getMaskElt(3), 3);
3204 }
3205
3206 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3207 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3208 /// <2, 3, 2, 3>
3209 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3210   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3211
3212   if (NumElems != 4)
3213     return false;
3214
3215   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3216   isUndefOrEqual(N->getMaskElt(1), 3) &&
3217   isUndefOrEqual(N->getMaskElt(2), 2) &&
3218   isUndefOrEqual(N->getMaskElt(3), 3);
3219 }
3220
3221 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3222 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3223 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3224   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3225
3226   if (NumElems != 2 && NumElems != 4)
3227     return false;
3228
3229   for (unsigned i = 0; i < NumElems/2; ++i)
3230     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3231       return false;
3232
3233   for (unsigned i = NumElems/2; i < NumElems; ++i)
3234     if (!isUndefOrEqual(N->getMaskElt(i), i))
3235       return false;
3236
3237   return true;
3238 }
3239
3240 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3241 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3242 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3243   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3244
3245   if ((NumElems != 2 && NumElems != 4)
3246       || N->getValueType(0).getSizeInBits() > 128)
3247     return false;
3248
3249   for (unsigned i = 0; i < NumElems/2; ++i)
3250     if (!isUndefOrEqual(N->getMaskElt(i), i))
3251       return false;
3252
3253   for (unsigned i = 0; i < NumElems/2; ++i)
3254     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3255       return false;
3256
3257   return true;
3258 }
3259
3260 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3261 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3262 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3263                          bool V2IsSplat = false) {
3264   int NumElts = VT.getVectorNumElements();
3265   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3266     return false;
3267
3268   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3269   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3270   // sections.
3271   unsigned NumSections = VT.getSizeInBits() / 128;
3272   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3273   unsigned NumSectionElts = NumElts / NumSections;
3274
3275   unsigned Start = 0;
3276   unsigned End = NumSectionElts;
3277   for (unsigned s = 0; s < NumSections; ++s) {
3278     for (unsigned i = Start, j = s * NumSectionElts;
3279          i != End;
3280          i += 2, ++j) {
3281       int BitI  = Mask[i];
3282       int BitI1 = Mask[i+1];
3283       if (!isUndefOrEqual(BitI, j))
3284         return false;
3285       if (V2IsSplat) {
3286         if (!isUndefOrEqual(BitI1, NumElts))
3287           return false;
3288       } else {
3289         if (!isUndefOrEqual(BitI1, j + NumElts))
3290           return false;
3291       }
3292     }
3293     // Process the next 128 bits.
3294     Start += NumSectionElts;
3295     End += NumSectionElts;
3296   }
3297
3298   return true;
3299 }
3300
3301 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3302   SmallVector<int, 8> M;
3303   N->getMask(M);
3304   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3305 }
3306
3307 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3308 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3309 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3310                          bool V2IsSplat = false) {
3311   int NumElts = VT.getVectorNumElements();
3312   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3313     return false;
3314
3315   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3316     int BitI  = Mask[i];
3317     int BitI1 = Mask[i+1];
3318     if (!isUndefOrEqual(BitI, j + NumElts/2))
3319       return false;
3320     if (V2IsSplat) {
3321       if (isUndefOrEqual(BitI1, NumElts))
3322         return false;
3323     } else {
3324       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3325         return false;
3326     }
3327   }
3328   return true;
3329 }
3330
3331 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3332   SmallVector<int, 8> M;
3333   N->getMask(M);
3334   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3335 }
3336
3337 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3338 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3339 /// <0, 0, 1, 1>
3340 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3341   int NumElems = VT.getVectorNumElements();
3342   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3343     return false;
3344
3345   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3346   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3347   // sections.
3348   unsigned NumSections = VT.getSizeInBits() / 128;
3349   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3350   unsigned NumSectionElts = NumElems / NumSections;
3351
3352   for (unsigned s = 0; s < NumSections; ++s) {
3353     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3354          i != NumSectionElts * (s + 1);
3355          i += 2, ++j) {
3356       int BitI  = Mask[i];
3357       int BitI1 = Mask[i+1];
3358
3359       if (!isUndefOrEqual(BitI, j))
3360         return false;
3361       if (!isUndefOrEqual(BitI1, j))
3362         return false;
3363     }
3364   }
3365
3366   return true;
3367 }
3368
3369 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3370   SmallVector<int, 8> M;
3371   N->getMask(M);
3372   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3373 }
3374
3375 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3376 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3377 /// <2, 2, 3, 3>
3378 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3379   int NumElems = VT.getVectorNumElements();
3380   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3381     return false;
3382
3383   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3384     int BitI  = Mask[i];
3385     int BitI1 = Mask[i+1];
3386     if (!isUndefOrEqual(BitI, j))
3387       return false;
3388     if (!isUndefOrEqual(BitI1, j))
3389       return false;
3390   }
3391   return true;
3392 }
3393
3394 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3395   SmallVector<int, 8> M;
3396   N->getMask(M);
3397   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3398 }
3399
3400 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3401 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3402 /// MOVSD, and MOVD, i.e. setting the lowest element.
3403 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3404   if (VT.getVectorElementType().getSizeInBits() < 32)
3405     return false;
3406
3407   int NumElts = VT.getVectorNumElements();
3408
3409   if (!isUndefOrEqual(Mask[0], NumElts))
3410     return false;
3411
3412   for (int i = 1; i < NumElts; ++i)
3413     if (!isUndefOrEqual(Mask[i], i))
3414       return false;
3415
3416   return true;
3417 }
3418
3419 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3420   SmallVector<int, 8> M;
3421   N->getMask(M);
3422   return ::isMOVLMask(M, N->getValueType(0));
3423 }
3424
3425 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3426 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3427 /// element of vector 2 and the other elements to come from vector 1 in order.
3428 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3429                                bool V2IsSplat = false, bool V2IsUndef = false) {
3430   int NumOps = VT.getVectorNumElements();
3431   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3432     return false;
3433
3434   if (!isUndefOrEqual(Mask[0], 0))
3435     return false;
3436
3437   for (int i = 1; i < NumOps; ++i)
3438     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3439           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3440           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3441       return false;
3442
3443   return true;
3444 }
3445
3446 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3447                            bool V2IsUndef = false) {
3448   SmallVector<int, 8> M;
3449   N->getMask(M);
3450   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3451 }
3452
3453 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3455 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3456   if (N->getValueType(0).getVectorNumElements() != 4)
3457     return false;
3458
3459   // Expect 1, 1, 3, 3
3460   for (unsigned i = 0; i < 2; ++i) {
3461     int Elt = N->getMaskElt(i);
3462     if (Elt >= 0 && Elt != 1)
3463       return false;
3464   }
3465
3466   bool HasHi = false;
3467   for (unsigned i = 2; i < 4; ++i) {
3468     int Elt = N->getMaskElt(i);
3469     if (Elt >= 0 && Elt != 3)
3470       return false;
3471     if (Elt == 3)
3472       HasHi = true;
3473   }
3474   // Don't use movshdup if it can be done with a shufps.
3475   // FIXME: verify that matching u, u, 3, 3 is what we want.
3476   return HasHi;
3477 }
3478
3479 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3480 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3481 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3482   if (N->getValueType(0).getVectorNumElements() != 4)
3483     return false;
3484
3485   // Expect 0, 0, 2, 2
3486   for (unsigned i = 0; i < 2; ++i)
3487     if (N->getMaskElt(i) > 0)
3488       return false;
3489
3490   bool HasHi = false;
3491   for (unsigned i = 2; i < 4; ++i) {
3492     int Elt = N->getMaskElt(i);
3493     if (Elt >= 0 && Elt != 2)
3494       return false;
3495     if (Elt == 2)
3496       HasHi = true;
3497   }
3498   // Don't use movsldup if it can be done with a shufps.
3499   return HasHi;
3500 }
3501
3502 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3503 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3504 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3505   int e = N->getValueType(0).getVectorNumElements() / 2;
3506
3507   for (int i = 0; i < e; ++i)
3508     if (!isUndefOrEqual(N->getMaskElt(i), i))
3509       return false;
3510   for (int i = 0; i < e; ++i)
3511     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3512       return false;
3513   return true;
3514 }
3515
3516 /// isVEXTRACTF128Index - Return true if the specified
3517 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3518 /// suitable for input to VEXTRACTF128.
3519 bool X86::isVEXTRACTF128Index(SDNode *N) {
3520   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3521     return false;
3522
3523   // The index should be aligned on a 128-bit boundary.
3524   uint64_t Index =
3525     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3526
3527   unsigned VL = N->getValueType(0).getVectorNumElements();
3528   unsigned VBits = N->getValueType(0).getSizeInBits();
3529   unsigned ElSize = VBits / VL;
3530   bool Result = (Index * ElSize) % 128 == 0;
3531
3532   return Result;
3533 }
3534
3535 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3536 /// operand specifies a subvector insert that is suitable for input to
3537 /// VINSERTF128.
3538 bool X86::isVINSERTF128Index(SDNode *N) {
3539   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3540     return false;
3541
3542   // The index should be aligned on a 128-bit boundary.
3543   uint64_t Index =
3544     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3545
3546   unsigned VL = N->getValueType(0).getVectorNumElements();
3547   unsigned VBits = N->getValueType(0).getSizeInBits();
3548   unsigned ElSize = VBits / VL;
3549   bool Result = (Index * ElSize) % 128 == 0;
3550
3551   return Result;
3552 }
3553
3554 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3555 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3556 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3557   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3558   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3559
3560   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3561   unsigned Mask = 0;
3562   for (int i = 0; i < NumOperands; ++i) {
3563     int Val = SVOp->getMaskElt(NumOperands-i-1);
3564     if (Val < 0) Val = 0;
3565     if (Val >= NumOperands) Val -= NumOperands;
3566     Mask |= Val;
3567     if (i != NumOperands - 1)
3568       Mask <<= Shift;
3569   }
3570   return Mask;
3571 }
3572
3573 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3574 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3575 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3576   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3577   unsigned Mask = 0;
3578   // 8 nodes, but we only care about the last 4.
3579   for (unsigned i = 7; i >= 4; --i) {
3580     int Val = SVOp->getMaskElt(i);
3581     if (Val >= 0)
3582       Mask |= (Val - 4);
3583     if (i != 4)
3584       Mask <<= 2;
3585   }
3586   return Mask;
3587 }
3588
3589 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3590 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3591 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3592   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3593   unsigned Mask = 0;
3594   // 8 nodes, but we only care about the first 4.
3595   for (int i = 3; i >= 0; --i) {
3596     int Val = SVOp->getMaskElt(i);
3597     if (Val >= 0)
3598       Mask |= Val;
3599     if (i != 0)
3600       Mask <<= 2;
3601   }
3602   return Mask;
3603 }
3604
3605 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3606 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3607 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3608   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3609   EVT VVT = N->getValueType(0);
3610   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3611   int Val = 0;
3612
3613   unsigned i, e;
3614   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3615     Val = SVOp->getMaskElt(i);
3616     if (Val >= 0)
3617       break;
3618   }
3619   return (Val - i) * EltSize;
3620 }
3621
3622 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3623 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3624 /// instructions.
3625 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3626   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3627     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3628
3629   uint64_t Index =
3630     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3631
3632   EVT VecVT = N->getOperand(0).getValueType();
3633   EVT ElVT = VecVT.getVectorElementType();
3634
3635   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3636   return Index / NumElemsPerChunk;
3637 }
3638
3639 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3640 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3641 /// instructions.
3642 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3643   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3644     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3645
3646   uint64_t Index =
3647     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3648
3649   EVT VecVT = N->getValueType(0);
3650   EVT ElVT = VecVT.getVectorElementType();
3651
3652   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3653   return Index / NumElemsPerChunk;
3654 }
3655
3656 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3657 /// constant +0.0.
3658 bool X86::isZeroNode(SDValue Elt) {
3659   return ((isa<ConstantSDNode>(Elt) &&
3660            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3661           (isa<ConstantFPSDNode>(Elt) &&
3662            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3663 }
3664
3665 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3666 /// their permute mask.
3667 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3668                                     SelectionDAG &DAG) {
3669   EVT VT = SVOp->getValueType(0);
3670   unsigned NumElems = VT.getVectorNumElements();
3671   SmallVector<int, 8> MaskVec;
3672
3673   for (unsigned i = 0; i != NumElems; ++i) {
3674     int idx = SVOp->getMaskElt(i);
3675     if (idx < 0)
3676       MaskVec.push_back(idx);
3677     else if (idx < (int)NumElems)
3678       MaskVec.push_back(idx + NumElems);
3679     else
3680       MaskVec.push_back(idx - NumElems);
3681   }
3682   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3683                               SVOp->getOperand(0), &MaskVec[0]);
3684 }
3685
3686 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3687 /// the two vector operands have swapped position.
3688 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3689   unsigned NumElems = VT.getVectorNumElements();
3690   for (unsigned i = 0; i != NumElems; ++i) {
3691     int idx = Mask[i];
3692     if (idx < 0)
3693       continue;
3694     else if (idx < (int)NumElems)
3695       Mask[i] = idx + NumElems;
3696     else
3697       Mask[i] = idx - NumElems;
3698   }
3699 }
3700
3701 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3702 /// match movhlps. The lower half elements should come from upper half of
3703 /// V1 (and in order), and the upper half elements should come from the upper
3704 /// half of V2 (and in order).
3705 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3706   if (Op->getValueType(0).getVectorNumElements() != 4)
3707     return false;
3708   for (unsigned i = 0, e = 2; i != e; ++i)
3709     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3710       return false;
3711   for (unsigned i = 2; i != 4; ++i)
3712     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3713       return false;
3714   return true;
3715 }
3716
3717 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3718 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3719 /// required.
3720 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3721   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3722     return false;
3723   N = N->getOperand(0).getNode();
3724   if (!ISD::isNON_EXTLoad(N))
3725     return false;
3726   if (LD)
3727     *LD = cast<LoadSDNode>(N);
3728   return true;
3729 }
3730
3731 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3732 /// match movlp{s|d}. The lower half elements should come from lower half of
3733 /// V1 (and in order), and the upper half elements should come from the upper
3734 /// half of V2 (and in order). And since V1 will become the source of the
3735 /// MOVLP, it must be either a vector load or a scalar load to vector.
3736 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3737                                ShuffleVectorSDNode *Op) {
3738   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3739     return false;
3740   // Is V2 is a vector load, don't do this transformation. We will try to use
3741   // load folding shufps op.
3742   if (ISD::isNON_EXTLoad(V2))
3743     return false;
3744
3745   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3746
3747   if (NumElems != 2 && NumElems != 4)
3748     return false;
3749   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3750     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3751       return false;
3752   for (unsigned i = NumElems/2; i != NumElems; ++i)
3753     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3754       return false;
3755   return true;
3756 }
3757
3758 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3759 /// all the same.
3760 static bool isSplatVector(SDNode *N) {
3761   if (N->getOpcode() != ISD::BUILD_VECTOR)
3762     return false;
3763
3764   SDValue SplatValue = N->getOperand(0);
3765   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3766     if (N->getOperand(i) != SplatValue)
3767       return false;
3768   return true;
3769 }
3770
3771 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3772 /// to an zero vector.
3773 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3774 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3775   SDValue V1 = N->getOperand(0);
3776   SDValue V2 = N->getOperand(1);
3777   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3778   for (unsigned i = 0; i != NumElems; ++i) {
3779     int Idx = N->getMaskElt(i);
3780     if (Idx >= (int)NumElems) {
3781       unsigned Opc = V2.getOpcode();
3782       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3783         continue;
3784       if (Opc != ISD::BUILD_VECTOR ||
3785           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3786         return false;
3787     } else if (Idx >= 0) {
3788       unsigned Opc = V1.getOpcode();
3789       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3790         continue;
3791       if (Opc != ISD::BUILD_VECTOR ||
3792           !X86::isZeroNode(V1.getOperand(Idx)))
3793         return false;
3794     }
3795   }
3796   return true;
3797 }
3798
3799 /// getZeroVector - Returns a vector of specified type with all zero elements.
3800 ///
3801 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3802                              DebugLoc dl) {
3803   assert(VT.isVector() && "Expected a vector type");
3804
3805   // Always build SSE zero vectors as <4 x i32> bitcasted
3806   // to their dest type. This ensures they get CSE'd.
3807   SDValue Vec;
3808   if (VT.getSizeInBits() == 128) {  // SSE
3809     if (HasSSE2) {  // SSE2
3810       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3811       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3812     } else { // SSE1
3813       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3814       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3815     }
3816   } else if (VT.getSizeInBits() == 256) { // AVX
3817     // 256-bit logic and arithmetic instructions in AVX are
3818     // all floating-point, no support for integer ops. Default
3819     // to emitting fp zeroed vectors then.
3820     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3821     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3822     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3823   }
3824   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3825 }
3826
3827 /// getOnesVector - Returns a vector of specified type with all bits set.
3828 /// Always build ones vectors as <4 x i32> or <8 x i32> bitcasted to
3829 /// their original type, ensuring they get CSE'd.
3830 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3831   assert(VT.isVector() && "Expected a vector type");
3832   assert((VT.is128BitVector() || VT.is256BitVector())
3833          && "Expected a 128-bit or 256-bit vector type");
3834
3835   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3836
3837   SDValue Vec;
3838   if (VT.is256BitVector()) {
3839     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3840     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
3841   } else
3842     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3843   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3844 }
3845
3846 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3847 /// that point to V2 points to its first element.
3848 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3849   EVT VT = SVOp->getValueType(0);
3850   unsigned NumElems = VT.getVectorNumElements();
3851
3852   bool Changed = false;
3853   SmallVector<int, 8> MaskVec;
3854   SVOp->getMask(MaskVec);
3855
3856   for (unsigned i = 0; i != NumElems; ++i) {
3857     if (MaskVec[i] > (int)NumElems) {
3858       MaskVec[i] = NumElems;
3859       Changed = true;
3860     }
3861   }
3862   if (Changed)
3863     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3864                                 SVOp->getOperand(1), &MaskVec[0]);
3865   return SDValue(SVOp, 0);
3866 }
3867
3868 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3869 /// operation of specified width.
3870 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3871                        SDValue V2) {
3872   unsigned NumElems = VT.getVectorNumElements();
3873   SmallVector<int, 8> Mask;
3874   Mask.push_back(NumElems);
3875   for (unsigned i = 1; i != NumElems; ++i)
3876     Mask.push_back(i);
3877   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3878 }
3879
3880 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3881 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3882                           SDValue V2) {
3883   unsigned NumElems = VT.getVectorNumElements();
3884   SmallVector<int, 8> Mask;
3885   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3886     Mask.push_back(i);
3887     Mask.push_back(i + NumElems);
3888   }
3889   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3890 }
3891
3892 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
3893 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3894                           SDValue V2) {
3895   unsigned NumElems = VT.getVectorNumElements();
3896   unsigned Half = NumElems/2;
3897   SmallVector<int, 8> Mask;
3898   for (unsigned i = 0; i != Half; ++i) {
3899     Mask.push_back(i + Half);
3900     Mask.push_back(i + NumElems + Half);
3901   }
3902   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3903 }
3904
3905 // PromoteSplatv8v16 - All i16 and i8 vector types can't be used directly by
3906 // a generic shuffle instruction because the target has no such instructions.
3907 // Generate shuffles which repeat i16 and i8 several times until they can be
3908 // represented by v4f32 and then be manipulated by target suported shuffles.
3909 static SDValue PromoteSplatv8v16(SDValue V, SelectionDAG &DAG, int &EltNo) {
3910   EVT VT = V.getValueType();
3911   int NumElems = VT.getVectorNumElements();
3912   DebugLoc dl = V.getDebugLoc();
3913
3914   while (NumElems > 4) {
3915     if (EltNo < NumElems/2) {
3916       V = getUnpackl(DAG, dl, VT, V, V);
3917     } else {
3918       V = getUnpackh(DAG, dl, VT, V, V);
3919       EltNo -= NumElems/2;
3920     }
3921     NumElems >>= 1;
3922   }
3923   return V;
3924 }
3925
3926 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
3927 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
3928   EVT VT = V.getValueType();
3929   DebugLoc dl = V.getDebugLoc();
3930   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
3931          && "Vector size not supported");
3932
3933   bool Is128 = VT.getSizeInBits() == 128;
3934   EVT NVT = Is128 ? MVT::v4f32 : MVT::v8f32;
3935   V = DAG.getNode(ISD::BITCAST, dl, NVT, V);
3936
3937   if (Is128) {
3938     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3939     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3940   } else {
3941     // The second half of indicies refer to the higher part, which is a
3942     // duplication of the lower one. This makes this shuffle a perfect match
3943     // for the VPERM instruction.
3944     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
3945                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
3946     V = DAG.getVectorShuffle(NVT, dl, V, DAG.getUNDEF(NVT), &SplatMask[0]);
3947   }
3948
3949   return DAG.getNode(ISD::BITCAST, dl, VT, V);
3950 }
3951
3952 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32 and
3953 /// v8i32, v16i16 or v32i8 to v8f32.
3954 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3955   EVT SrcVT = SV->getValueType(0);
3956   SDValue V1 = SV->getOperand(0);
3957   DebugLoc dl = SV->getDebugLoc();
3958
3959   int EltNo = SV->getSplatIndex();
3960   int NumElems = SrcVT.getVectorNumElements();
3961   unsigned Size = SrcVT.getSizeInBits();
3962
3963   // Extract the 128-bit part containing the splat element and update
3964   // the splat element index when it refers to the higher register.
3965   if (Size == 256) {
3966     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
3967     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
3968     if (Idx > 0)
3969       EltNo -= NumElems/2;
3970   }
3971
3972   // Make this 128-bit vector duplicate i8 and i16 elements
3973   if (NumElems > 4)
3974     V1 = PromoteSplatv8v16(V1, DAG, EltNo);
3975
3976   // Recreate the 256-bit vector and place the same 128-bit vector
3977   // into the low and high part. This is necessary because we want
3978   // to use VPERM to shuffle the v8f32 vector, and VPERM only shuffles
3979   // inside each separate v4f32 lane.
3980   if (Size == 256) {
3981     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
3982                          DAG.getConstant(0, MVT::i32), DAG, dl);
3983     V1 = Insert128BitVector(InsV, V1,
3984                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
3985   }
3986
3987   return getLegalSplat(DAG, V1, EltNo);
3988 }
3989
3990 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3991 /// vector of zero or undef vector.  This produces a shuffle where the low
3992 /// element of V2 is swizzled into the zero/undef vector, landing at element
3993 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3994 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3995                                              bool isZero, bool HasSSE2,
3996                                              SelectionDAG &DAG) {
3997   EVT VT = V2.getValueType();
3998   SDValue V1 = isZero
3999     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4000   unsigned NumElems = VT.getVectorNumElements();
4001   SmallVector<int, 16> MaskVec;
4002   for (unsigned i = 0; i != NumElems; ++i)
4003     // If this is the insertion idx, put the low elt of V2 here.
4004     MaskVec.push_back(i == Idx ? NumElems : i);
4005   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4006 }
4007
4008 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4009 /// element of the result of the vector shuffle.
4010 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4011                                    unsigned Depth) {
4012   if (Depth == 6)
4013     return SDValue();  // Limit search depth.
4014
4015   SDValue V = SDValue(N, 0);
4016   EVT VT = V.getValueType();
4017   unsigned Opcode = V.getOpcode();
4018
4019   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4020   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4021     Index = SV->getMaskElt(Index);
4022
4023     if (Index < 0)
4024       return DAG.getUNDEF(VT.getVectorElementType());
4025
4026     int NumElems = VT.getVectorNumElements();
4027     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4028     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4029   }
4030
4031   // Recurse into target specific vector shuffles to find scalars.
4032   if (isTargetShuffle(Opcode)) {
4033     int NumElems = VT.getVectorNumElements();
4034     SmallVector<unsigned, 16> ShuffleMask;
4035     SDValue ImmN;
4036
4037     switch(Opcode) {
4038     case X86ISD::SHUFPS:
4039     case X86ISD::SHUFPD:
4040       ImmN = N->getOperand(N->getNumOperands()-1);
4041       DecodeSHUFPSMask(NumElems,
4042                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4043                        ShuffleMask);
4044       break;
4045     case X86ISD::PUNPCKHBW:
4046     case X86ISD::PUNPCKHWD:
4047     case X86ISD::PUNPCKHDQ:
4048     case X86ISD::PUNPCKHQDQ:
4049       DecodePUNPCKHMask(NumElems, ShuffleMask);
4050       break;
4051     case X86ISD::UNPCKHPS:
4052     case X86ISD::UNPCKHPD:
4053       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4054       break;
4055     case X86ISD::PUNPCKLBW:
4056     case X86ISD::PUNPCKLWD:
4057     case X86ISD::PUNPCKLDQ:
4058     case X86ISD::PUNPCKLQDQ:
4059       DecodePUNPCKLMask(VT, ShuffleMask);
4060       break;
4061     case X86ISD::UNPCKLPS:
4062     case X86ISD::UNPCKLPD:
4063     case X86ISD::VUNPCKLPS:
4064     case X86ISD::VUNPCKLPD:
4065     case X86ISD::VUNPCKLPSY:
4066     case X86ISD::VUNPCKLPDY:
4067       DecodeUNPCKLPMask(VT, ShuffleMask);
4068       break;
4069     case X86ISD::MOVHLPS:
4070       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4071       break;
4072     case X86ISD::MOVLHPS:
4073       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4074       break;
4075     case X86ISD::PSHUFD:
4076       ImmN = N->getOperand(N->getNumOperands()-1);
4077       DecodePSHUFMask(NumElems,
4078                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4079                       ShuffleMask);
4080       break;
4081     case X86ISD::PSHUFHW:
4082       ImmN = N->getOperand(N->getNumOperands()-1);
4083       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4084                         ShuffleMask);
4085       break;
4086     case X86ISD::PSHUFLW:
4087       ImmN = N->getOperand(N->getNumOperands()-1);
4088       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4089                         ShuffleMask);
4090       break;
4091     case X86ISD::MOVSS:
4092     case X86ISD::MOVSD: {
4093       // The index 0 always comes from the first element of the second source,
4094       // this is why MOVSS and MOVSD are used in the first place. The other
4095       // elements come from the other positions of the first source vector.
4096       unsigned OpNum = (Index == 0) ? 1 : 0;
4097       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4098                                  Depth+1);
4099     }
4100     default:
4101       assert("not implemented for target shuffle node");
4102       return SDValue();
4103     }
4104
4105     Index = ShuffleMask[Index];
4106     if (Index < 0)
4107       return DAG.getUNDEF(VT.getVectorElementType());
4108
4109     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4110     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4111                                Depth+1);
4112   }
4113
4114   // Actual nodes that may contain scalar elements
4115   if (Opcode == ISD::BITCAST) {
4116     V = V.getOperand(0);
4117     EVT SrcVT = V.getValueType();
4118     unsigned NumElems = VT.getVectorNumElements();
4119
4120     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4121       return SDValue();
4122   }
4123
4124   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4125     return (Index == 0) ? V.getOperand(0)
4126                           : DAG.getUNDEF(VT.getVectorElementType());
4127
4128   if (V.getOpcode() == ISD::BUILD_VECTOR)
4129     return V.getOperand(Index);
4130
4131   return SDValue();
4132 }
4133
4134 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4135 /// shuffle operation which come from a consecutively from a zero. The
4136 /// search can start in two different directions, from left or right.
4137 static
4138 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4139                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4140   int i = 0;
4141
4142   while (i < NumElems) {
4143     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4144     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4145     if (!(Elt.getNode() &&
4146          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4147       break;
4148     ++i;
4149   }
4150
4151   return i;
4152 }
4153
4154 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4155 /// MaskE correspond consecutively to elements from one of the vector operands,
4156 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4157 static
4158 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4159                               int OpIdx, int NumElems, unsigned &OpNum) {
4160   bool SeenV1 = false;
4161   bool SeenV2 = false;
4162
4163   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4164     int Idx = SVOp->getMaskElt(i);
4165     // Ignore undef indicies
4166     if (Idx < 0)
4167       continue;
4168
4169     if (Idx < NumElems)
4170       SeenV1 = true;
4171     else
4172       SeenV2 = true;
4173
4174     // Only accept consecutive elements from the same vector
4175     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4176       return false;
4177   }
4178
4179   OpNum = SeenV1 ? 0 : 1;
4180   return true;
4181 }
4182
4183 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4184 /// logical left shift of a vector.
4185 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4186                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4187   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4188   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4189               false /* check zeros from right */, DAG);
4190   unsigned OpSrc;
4191
4192   if (!NumZeros)
4193     return false;
4194
4195   // Considering the elements in the mask that are not consecutive zeros,
4196   // check if they consecutively come from only one of the source vectors.
4197   //
4198   //               V1 = {X, A, B, C}     0
4199   //                         \  \  \    /
4200   //   vector_shuffle V1, V2 <1, 2, 3, X>
4201   //
4202   if (!isShuffleMaskConsecutive(SVOp,
4203             0,                   // Mask Start Index
4204             NumElems-NumZeros-1, // Mask End Index
4205             NumZeros,            // Where to start looking in the src vector
4206             NumElems,            // Number of elements in vector
4207             OpSrc))              // Which source operand ?
4208     return false;
4209
4210   isLeft = false;
4211   ShAmt = NumZeros;
4212   ShVal = SVOp->getOperand(OpSrc);
4213   return true;
4214 }
4215
4216 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4217 /// logical left shift of a vector.
4218 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4219                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4220   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4221   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4222               true /* check zeros from left */, DAG);
4223   unsigned OpSrc;
4224
4225   if (!NumZeros)
4226     return false;
4227
4228   // Considering the elements in the mask that are not consecutive zeros,
4229   // check if they consecutively come from only one of the source vectors.
4230   //
4231   //                           0    { A, B, X, X } = V2
4232   //                          / \    /  /
4233   //   vector_shuffle V1, V2 <X, X, 4, 5>
4234   //
4235   if (!isShuffleMaskConsecutive(SVOp,
4236             NumZeros,     // Mask Start Index
4237             NumElems-1,   // Mask End Index
4238             0,            // Where to start looking in the src vector
4239             NumElems,     // Number of elements in vector
4240             OpSrc))       // Which source operand ?
4241     return false;
4242
4243   isLeft = true;
4244   ShAmt = NumZeros;
4245   ShVal = SVOp->getOperand(OpSrc);
4246   return true;
4247 }
4248
4249 /// isVectorShift - Returns true if the shuffle can be implemented as a
4250 /// logical left or right shift of a vector.
4251 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4252                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4253   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4254       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4255     return true;
4256
4257   return false;
4258 }
4259
4260 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4261 ///
4262 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4263                                        unsigned NumNonZero, unsigned NumZero,
4264                                        SelectionDAG &DAG,
4265                                        const TargetLowering &TLI) {
4266   if (NumNonZero > 8)
4267     return SDValue();
4268
4269   DebugLoc dl = Op.getDebugLoc();
4270   SDValue V(0, 0);
4271   bool First = true;
4272   for (unsigned i = 0; i < 16; ++i) {
4273     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4274     if (ThisIsNonZero && First) {
4275       if (NumZero)
4276         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4277       else
4278         V = DAG.getUNDEF(MVT::v8i16);
4279       First = false;
4280     }
4281
4282     if ((i & 1) != 0) {
4283       SDValue ThisElt(0, 0), LastElt(0, 0);
4284       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4285       if (LastIsNonZero) {
4286         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4287                               MVT::i16, Op.getOperand(i-1));
4288       }
4289       if (ThisIsNonZero) {
4290         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4291         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4292                               ThisElt, DAG.getConstant(8, MVT::i8));
4293         if (LastIsNonZero)
4294           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4295       } else
4296         ThisElt = LastElt;
4297
4298       if (ThisElt.getNode())
4299         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4300                         DAG.getIntPtrConstant(i/2));
4301     }
4302   }
4303
4304   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4305 }
4306
4307 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4308 ///
4309 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4310                                      unsigned NumNonZero, unsigned NumZero,
4311                                      SelectionDAG &DAG,
4312                                      const TargetLowering &TLI) {
4313   if (NumNonZero > 4)
4314     return SDValue();
4315
4316   DebugLoc dl = Op.getDebugLoc();
4317   SDValue V(0, 0);
4318   bool First = true;
4319   for (unsigned i = 0; i < 8; ++i) {
4320     bool isNonZero = (NonZeros & (1 << i)) != 0;
4321     if (isNonZero) {
4322       if (First) {
4323         if (NumZero)
4324           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4325         else
4326           V = DAG.getUNDEF(MVT::v8i16);
4327         First = false;
4328       }
4329       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4330                       MVT::v8i16, V, Op.getOperand(i),
4331                       DAG.getIntPtrConstant(i));
4332     }
4333   }
4334
4335   return V;
4336 }
4337
4338 /// getVShift - Return a vector logical shift node.
4339 ///
4340 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4341                          unsigned NumBits, SelectionDAG &DAG,
4342                          const TargetLowering &TLI, DebugLoc dl) {
4343   EVT ShVT = MVT::v2i64;
4344   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4345   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4346   return DAG.getNode(ISD::BITCAST, dl, VT,
4347                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4348                              DAG.getConstant(NumBits,
4349                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4350 }
4351
4352 SDValue
4353 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4354                                           SelectionDAG &DAG) const {
4355
4356   // Check if the scalar load can be widened into a vector load. And if
4357   // the address is "base + cst" see if the cst can be "absorbed" into
4358   // the shuffle mask.
4359   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4360     SDValue Ptr = LD->getBasePtr();
4361     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4362       return SDValue();
4363     EVT PVT = LD->getValueType(0);
4364     if (PVT != MVT::i32 && PVT != MVT::f32)
4365       return SDValue();
4366
4367     int FI = -1;
4368     int64_t Offset = 0;
4369     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4370       FI = FINode->getIndex();
4371       Offset = 0;
4372     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4373                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4374       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4375       Offset = Ptr.getConstantOperandVal(1);
4376       Ptr = Ptr.getOperand(0);
4377     } else {
4378       return SDValue();
4379     }
4380
4381     SDValue Chain = LD->getChain();
4382     // Make sure the stack object alignment is at least 16.
4383     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4384     if (DAG.InferPtrAlignment(Ptr) < 16) {
4385       if (MFI->isFixedObjectIndex(FI)) {
4386         // Can't change the alignment. FIXME: It's possible to compute
4387         // the exact stack offset and reference FI + adjust offset instead.
4388         // If someone *really* cares about this. That's the way to implement it.
4389         return SDValue();
4390       } else {
4391         MFI->setObjectAlignment(FI, 16);
4392       }
4393     }
4394
4395     // (Offset % 16) must be multiple of 4. Then address is then
4396     // Ptr + (Offset & ~15).
4397     if (Offset < 0)
4398       return SDValue();
4399     if ((Offset % 16) & 3)
4400       return SDValue();
4401     int64_t StartOffset = Offset & ~15;
4402     if (StartOffset)
4403       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4404                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4405
4406     int EltNo = (Offset - StartOffset) >> 2;
4407     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4408     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4409     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4410                              LD->getPointerInfo().getWithOffset(StartOffset),
4411                              false, false, 0);
4412     // Canonicalize it to a v4i32 shuffle.
4413     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4414     return DAG.getNode(ISD::BITCAST, dl, VT,
4415                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4416                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4417   }
4418
4419   return SDValue();
4420 }
4421
4422 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4423 /// vector of type 'VT', see if the elements can be replaced by a single large
4424 /// load which has the same value as a build_vector whose operands are 'elts'.
4425 ///
4426 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4427 ///
4428 /// FIXME: we'd also like to handle the case where the last elements are zero
4429 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4430 /// There's even a handy isZeroNode for that purpose.
4431 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4432                                         DebugLoc &DL, SelectionDAG &DAG) {
4433   EVT EltVT = VT.getVectorElementType();
4434   unsigned NumElems = Elts.size();
4435
4436   LoadSDNode *LDBase = NULL;
4437   unsigned LastLoadedElt = -1U;
4438
4439   // For each element in the initializer, see if we've found a load or an undef.
4440   // If we don't find an initial load element, or later load elements are
4441   // non-consecutive, bail out.
4442   for (unsigned i = 0; i < NumElems; ++i) {
4443     SDValue Elt = Elts[i];
4444
4445     if (!Elt.getNode() ||
4446         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4447       return SDValue();
4448     if (!LDBase) {
4449       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4450         return SDValue();
4451       LDBase = cast<LoadSDNode>(Elt.getNode());
4452       LastLoadedElt = i;
4453       continue;
4454     }
4455     if (Elt.getOpcode() == ISD::UNDEF)
4456       continue;
4457
4458     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4459     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4460       return SDValue();
4461     LastLoadedElt = i;
4462   }
4463
4464   // If we have found an entire vector of loads and undefs, then return a large
4465   // load of the entire vector width starting at the base pointer.  If we found
4466   // consecutive loads for the low half, generate a vzext_load node.
4467   if (LastLoadedElt == NumElems - 1) {
4468     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4469       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4470                          LDBase->getPointerInfo(),
4471                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4472     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4473                        LDBase->getPointerInfo(),
4474                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4475                        LDBase->getAlignment());
4476   } else if (NumElems == 4 && LastLoadedElt == 1) {
4477     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4478     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4479     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4480                                               Ops, 2, MVT::i32,
4481                                               LDBase->getMemOperand());
4482     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4483   }
4484   return SDValue();
4485 }
4486
4487 SDValue
4488 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4489   DebugLoc dl = Op.getDebugLoc();
4490
4491   EVT VT = Op.getValueType();
4492   EVT ExtVT = VT.getVectorElementType();
4493
4494   unsigned NumElems = Op.getNumOperands();
4495
4496   // For AVX-length vectors, build the individual 128-bit pieces and
4497   // use shuffles to put them in place.
4498   if (VT.getSizeInBits() > 256 &&
4499       Subtarget->hasAVX() &&
4500       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4501     SmallVector<SDValue, 8> V;
4502     V.resize(NumElems);
4503     for (unsigned i = 0; i < NumElems; ++i) {
4504       V[i] = Op.getOperand(i);
4505     }
4506
4507     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4508
4509     // Build the lower subvector.
4510     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4511     // Build the upper subvector.
4512     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4513                                 NumElems/2);
4514
4515     return ConcatVectors(Lower, Upper, DAG);
4516   }
4517
4518   // All zero's:
4519   //  - pxor (SSE2), xorps (SSE1), vpxor (128 AVX), xorp[s|d] (256 AVX)
4520   // All one's:
4521   //  - pcmpeqd (SSE2 and 128 AVX), fallback to constant pools (256 AVX)
4522   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4523       ISD::isBuildVectorAllOnes(Op.getNode())) {
4524     // Canonicalize this to <4 x i32> or <8 x 32> (SSE) to
4525     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4526     // eliminated on x86-32 hosts.
4527     if (Op.getValueType() == MVT::v4i32 ||
4528         Op.getValueType() == MVT::v8i32)
4529       return Op;
4530
4531     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4532       return getOnesVector(Op.getValueType(), DAG, dl);
4533     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4534   }
4535
4536   unsigned EVTBits = ExtVT.getSizeInBits();
4537
4538   unsigned NumZero  = 0;
4539   unsigned NumNonZero = 0;
4540   unsigned NonZeros = 0;
4541   bool IsAllConstants = true;
4542   SmallSet<SDValue, 8> Values;
4543   for (unsigned i = 0; i < NumElems; ++i) {
4544     SDValue Elt = Op.getOperand(i);
4545     if (Elt.getOpcode() == ISD::UNDEF)
4546       continue;
4547     Values.insert(Elt);
4548     if (Elt.getOpcode() != ISD::Constant &&
4549         Elt.getOpcode() != ISD::ConstantFP)
4550       IsAllConstants = false;
4551     if (X86::isZeroNode(Elt))
4552       NumZero++;
4553     else {
4554       NonZeros |= (1 << i);
4555       NumNonZero++;
4556     }
4557   }
4558
4559   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4560   if (NumNonZero == 0)
4561     return DAG.getUNDEF(VT);
4562
4563   // Special case for single non-zero, non-undef, element.
4564   if (NumNonZero == 1) {
4565     unsigned Idx = CountTrailingZeros_32(NonZeros);
4566     SDValue Item = Op.getOperand(Idx);
4567
4568     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4569     // the value are obviously zero, truncate the value to i32 and do the
4570     // insertion that way.  Only do this if the value is non-constant or if the
4571     // value is a constant being inserted into element 0.  It is cheaper to do
4572     // a constant pool load than it is to do a movd + shuffle.
4573     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4574         (!IsAllConstants || Idx == 0)) {
4575       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4576         // Handle SSE only.
4577         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4578         EVT VecVT = MVT::v4i32;
4579         unsigned VecElts = 4;
4580
4581         // Truncate the value (which may itself be a constant) to i32, and
4582         // convert it to a vector with movd (S2V+shuffle to zero extend).
4583         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4584         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4585         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4586                                            Subtarget->hasSSE2(), DAG);
4587
4588         // Now we have our 32-bit value zero extended in the low element of
4589         // a vector.  If Idx != 0, swizzle it into place.
4590         if (Idx != 0) {
4591           SmallVector<int, 4> Mask;
4592           Mask.push_back(Idx);
4593           for (unsigned i = 1; i != VecElts; ++i)
4594             Mask.push_back(i);
4595           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4596                                       DAG.getUNDEF(Item.getValueType()),
4597                                       &Mask[0]);
4598         }
4599         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4600       }
4601     }
4602
4603     // If we have a constant or non-constant insertion into the low element of
4604     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4605     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4606     // depending on what the source datatype is.
4607     if (Idx == 0) {
4608       if (NumZero == 0) {
4609         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4610       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4611           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4612         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4613         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4614         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4615                                            DAG);
4616       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4617         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4618         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4619         EVT MiddleVT = MVT::v4i32;
4620         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4621         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4622                                            Subtarget->hasSSE2(), DAG);
4623         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4624       }
4625     }
4626
4627     // Is it a vector logical left shift?
4628     if (NumElems == 2 && Idx == 1 &&
4629         X86::isZeroNode(Op.getOperand(0)) &&
4630         !X86::isZeroNode(Op.getOperand(1))) {
4631       unsigned NumBits = VT.getSizeInBits();
4632       return getVShift(true, VT,
4633                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4634                                    VT, Op.getOperand(1)),
4635                        NumBits/2, DAG, *this, dl);
4636     }
4637
4638     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4639       return SDValue();
4640
4641     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4642     // is a non-constant being inserted into an element other than the low one,
4643     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4644     // movd/movss) to move this into the low element, then shuffle it into
4645     // place.
4646     if (EVTBits == 32) {
4647       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4648
4649       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4650       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4651                                          Subtarget->hasSSE2(), DAG);
4652       SmallVector<int, 8> MaskVec;
4653       for (unsigned i = 0; i < NumElems; i++)
4654         MaskVec.push_back(i == Idx ? 0 : 1);
4655       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4656     }
4657   }
4658
4659   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4660   if (Values.size() == 1) {
4661     if (EVTBits == 32) {
4662       // Instead of a shuffle like this:
4663       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4664       // Check if it's possible to issue this instead.
4665       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4666       unsigned Idx = CountTrailingZeros_32(NonZeros);
4667       SDValue Item = Op.getOperand(Idx);
4668       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4669         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4670     }
4671     return SDValue();
4672   }
4673
4674   // A vector full of immediates; various special cases are already
4675   // handled, so this is best done with a single constant-pool load.
4676   if (IsAllConstants)
4677     return SDValue();
4678
4679   // Let legalizer expand 2-wide build_vectors.
4680   if (EVTBits == 64) {
4681     if (NumNonZero == 1) {
4682       // One half is zero or undef.
4683       unsigned Idx = CountTrailingZeros_32(NonZeros);
4684       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4685                                  Op.getOperand(Idx));
4686       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4687                                          Subtarget->hasSSE2(), DAG);
4688     }
4689     return SDValue();
4690   }
4691
4692   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4693   if (EVTBits == 8 && NumElems == 16) {
4694     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4695                                         *this);
4696     if (V.getNode()) return V;
4697   }
4698
4699   if (EVTBits == 16 && NumElems == 8) {
4700     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4701                                       *this);
4702     if (V.getNode()) return V;
4703   }
4704
4705   // If element VT is == 32 bits, turn it into a number of shuffles.
4706   SmallVector<SDValue, 8> V;
4707   V.resize(NumElems);
4708   if (NumElems == 4 && NumZero > 0) {
4709     for (unsigned i = 0; i < 4; ++i) {
4710       bool isZero = !(NonZeros & (1 << i));
4711       if (isZero)
4712         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4713       else
4714         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4715     }
4716
4717     for (unsigned i = 0; i < 2; ++i) {
4718       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4719         default: break;
4720         case 0:
4721           V[i] = V[i*2];  // Must be a zero vector.
4722           break;
4723         case 1:
4724           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4725           break;
4726         case 2:
4727           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4728           break;
4729         case 3:
4730           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4731           break;
4732       }
4733     }
4734
4735     SmallVector<int, 8> MaskVec;
4736     bool Reverse = (NonZeros & 0x3) == 2;
4737     for (unsigned i = 0; i < 2; ++i)
4738       MaskVec.push_back(Reverse ? 1-i : i);
4739     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4740     for (unsigned i = 0; i < 2; ++i)
4741       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4742     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4743   }
4744
4745   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4746     // Check for a build vector of consecutive loads.
4747     for (unsigned i = 0; i < NumElems; ++i)
4748       V[i] = Op.getOperand(i);
4749
4750     // Check for elements which are consecutive loads.
4751     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4752     if (LD.getNode())
4753       return LD;
4754
4755     // For SSE 4.1, use insertps to put the high elements into the low element.
4756     if (getSubtarget()->hasSSE41()) {
4757       SDValue Result;
4758       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4759         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4760       else
4761         Result = DAG.getUNDEF(VT);
4762
4763       for (unsigned i = 1; i < NumElems; ++i) {
4764         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4765         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4766                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4767       }
4768       return Result;
4769     }
4770
4771     // Otherwise, expand into a number of unpckl*, start by extending each of
4772     // our (non-undef) elements to the full vector width with the element in the
4773     // bottom slot of the vector (which generates no code for SSE).
4774     for (unsigned i = 0; i < NumElems; ++i) {
4775       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4776         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4777       else
4778         V[i] = DAG.getUNDEF(VT);
4779     }
4780
4781     // Next, we iteratively mix elements, e.g. for v4f32:
4782     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4783     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4784     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4785     unsigned EltStride = NumElems >> 1;
4786     while (EltStride != 0) {
4787       for (unsigned i = 0; i < EltStride; ++i) {
4788         // If V[i+EltStride] is undef and this is the first round of mixing,
4789         // then it is safe to just drop this shuffle: V[i] is already in the
4790         // right place, the one element (since it's the first round) being
4791         // inserted as undef can be dropped.  This isn't safe for successive
4792         // rounds because they will permute elements within both vectors.
4793         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4794             EltStride == NumElems/2)
4795           continue;
4796
4797         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4798       }
4799       EltStride >>= 1;
4800     }
4801     return V[0];
4802   }
4803   return SDValue();
4804 }
4805
4806 SDValue
4807 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4808   // We support concatenate two MMX registers and place them in a MMX
4809   // register.  This is better than doing a stack convert.
4810   DebugLoc dl = Op.getDebugLoc();
4811   EVT ResVT = Op.getValueType();
4812   assert(Op.getNumOperands() == 2);
4813   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4814          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4815   int Mask[2];
4816   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4817   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4818   InVec = Op.getOperand(1);
4819   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4820     unsigned NumElts = ResVT.getVectorNumElements();
4821     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4822     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4823                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4824   } else {
4825     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4826     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4827     Mask[0] = 0; Mask[1] = 2;
4828     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4829   }
4830   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4831 }
4832
4833 // v8i16 shuffles - Prefer shuffles in the following order:
4834 // 1. [all]   pshuflw, pshufhw, optional move
4835 // 2. [ssse3] 1 x pshufb
4836 // 3. [ssse3] 2 x pshufb + 1 x por
4837 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4838 SDValue
4839 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4840                                             SelectionDAG &DAG) const {
4841   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4842   SDValue V1 = SVOp->getOperand(0);
4843   SDValue V2 = SVOp->getOperand(1);
4844   DebugLoc dl = SVOp->getDebugLoc();
4845   SmallVector<int, 8> MaskVals;
4846
4847   // Determine if more than 1 of the words in each of the low and high quadwords
4848   // of the result come from the same quadword of one of the two inputs.  Undef
4849   // mask values count as coming from any quadword, for better codegen.
4850   SmallVector<unsigned, 4> LoQuad(4);
4851   SmallVector<unsigned, 4> HiQuad(4);
4852   BitVector InputQuads(4);
4853   for (unsigned i = 0; i < 8; ++i) {
4854     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4855     int EltIdx = SVOp->getMaskElt(i);
4856     MaskVals.push_back(EltIdx);
4857     if (EltIdx < 0) {
4858       ++Quad[0];
4859       ++Quad[1];
4860       ++Quad[2];
4861       ++Quad[3];
4862       continue;
4863     }
4864     ++Quad[EltIdx / 4];
4865     InputQuads.set(EltIdx / 4);
4866   }
4867
4868   int BestLoQuad = -1;
4869   unsigned MaxQuad = 1;
4870   for (unsigned i = 0; i < 4; ++i) {
4871     if (LoQuad[i] > MaxQuad) {
4872       BestLoQuad = i;
4873       MaxQuad = LoQuad[i];
4874     }
4875   }
4876
4877   int BestHiQuad = -1;
4878   MaxQuad = 1;
4879   for (unsigned i = 0; i < 4; ++i) {
4880     if (HiQuad[i] > MaxQuad) {
4881       BestHiQuad = i;
4882       MaxQuad = HiQuad[i];
4883     }
4884   }
4885
4886   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4887   // of the two input vectors, shuffle them into one input vector so only a
4888   // single pshufb instruction is necessary. If There are more than 2 input
4889   // quads, disable the next transformation since it does not help SSSE3.
4890   bool V1Used = InputQuads[0] || InputQuads[1];
4891   bool V2Used = InputQuads[2] || InputQuads[3];
4892   if (Subtarget->hasSSSE3()) {
4893     if (InputQuads.count() == 2 && V1Used && V2Used) {
4894       BestLoQuad = InputQuads.find_first();
4895       BestHiQuad = InputQuads.find_next(BestLoQuad);
4896     }
4897     if (InputQuads.count() > 2) {
4898       BestLoQuad = -1;
4899       BestHiQuad = -1;
4900     }
4901   }
4902
4903   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4904   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4905   // words from all 4 input quadwords.
4906   SDValue NewV;
4907   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4908     SmallVector<int, 8> MaskV;
4909     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4910     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4911     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4912                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4913                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4914     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4915
4916     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4917     // source words for the shuffle, to aid later transformations.
4918     bool AllWordsInNewV = true;
4919     bool InOrder[2] = { true, true };
4920     for (unsigned i = 0; i != 8; ++i) {
4921       int idx = MaskVals[i];
4922       if (idx != (int)i)
4923         InOrder[i/4] = false;
4924       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4925         continue;
4926       AllWordsInNewV = false;
4927       break;
4928     }
4929
4930     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4931     if (AllWordsInNewV) {
4932       for (int i = 0; i != 8; ++i) {
4933         int idx = MaskVals[i];
4934         if (idx < 0)
4935           continue;
4936         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4937         if ((idx != i) && idx < 4)
4938           pshufhw = false;
4939         if ((idx != i) && idx > 3)
4940           pshuflw = false;
4941       }
4942       V1 = NewV;
4943       V2Used = false;
4944       BestLoQuad = 0;
4945       BestHiQuad = 1;
4946     }
4947
4948     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4949     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4950     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4951       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4952       unsigned TargetMask = 0;
4953       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4954                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4955       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4956                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4957       V1 = NewV.getOperand(0);
4958       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4959     }
4960   }
4961
4962   // If we have SSSE3, and all words of the result are from 1 input vector,
4963   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4964   // is present, fall back to case 4.
4965   if (Subtarget->hasSSSE3()) {
4966     SmallVector<SDValue,16> pshufbMask;
4967
4968     // If we have elements from both input vectors, set the high bit of the
4969     // shuffle mask element to zero out elements that come from V2 in the V1
4970     // mask, and elements that come from V1 in the V2 mask, so that the two
4971     // results can be OR'd together.
4972     bool TwoInputs = V1Used && V2Used;
4973     for (unsigned i = 0; i != 8; ++i) {
4974       int EltIdx = MaskVals[i] * 2;
4975       if (TwoInputs && (EltIdx >= 16)) {
4976         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4977         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4978         continue;
4979       }
4980       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4981       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4982     }
4983     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4984     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4985                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4986                                  MVT::v16i8, &pshufbMask[0], 16));
4987     if (!TwoInputs)
4988       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4989
4990     // Calculate the shuffle mask for the second input, shuffle it, and
4991     // OR it with the first shuffled input.
4992     pshufbMask.clear();
4993     for (unsigned i = 0; i != 8; ++i) {
4994       int EltIdx = MaskVals[i] * 2;
4995       if (EltIdx < 16) {
4996         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4997         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4998         continue;
4999       }
5000       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5001       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5002     }
5003     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5004     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5005                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5006                                  MVT::v16i8, &pshufbMask[0], 16));
5007     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5008     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5009   }
5010
5011   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5012   // and update MaskVals with new element order.
5013   BitVector InOrder(8);
5014   if (BestLoQuad >= 0) {
5015     SmallVector<int, 8> MaskV;
5016     for (int i = 0; i != 4; ++i) {
5017       int idx = MaskVals[i];
5018       if (idx < 0) {
5019         MaskV.push_back(-1);
5020         InOrder.set(i);
5021       } else if ((idx / 4) == BestLoQuad) {
5022         MaskV.push_back(idx & 3);
5023         InOrder.set(i);
5024       } else {
5025         MaskV.push_back(-1);
5026       }
5027     }
5028     for (unsigned i = 4; i != 8; ++i)
5029       MaskV.push_back(i);
5030     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5031                                 &MaskV[0]);
5032
5033     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5034       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5035                                NewV.getOperand(0),
5036                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5037                                DAG);
5038   }
5039
5040   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5041   // and update MaskVals with the new element order.
5042   if (BestHiQuad >= 0) {
5043     SmallVector<int, 8> MaskV;
5044     for (unsigned i = 0; i != 4; ++i)
5045       MaskV.push_back(i);
5046     for (unsigned i = 4; i != 8; ++i) {
5047       int idx = MaskVals[i];
5048       if (idx < 0) {
5049         MaskV.push_back(-1);
5050         InOrder.set(i);
5051       } else if ((idx / 4) == BestHiQuad) {
5052         MaskV.push_back((idx & 3) + 4);
5053         InOrder.set(i);
5054       } else {
5055         MaskV.push_back(-1);
5056       }
5057     }
5058     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5059                                 &MaskV[0]);
5060
5061     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5062       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5063                               NewV.getOperand(0),
5064                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5065                               DAG);
5066   }
5067
5068   // In case BestHi & BestLo were both -1, which means each quadword has a word
5069   // from each of the four input quadwords, calculate the InOrder bitvector now
5070   // before falling through to the insert/extract cleanup.
5071   if (BestLoQuad == -1 && BestHiQuad == -1) {
5072     NewV = V1;
5073     for (int i = 0; i != 8; ++i)
5074       if (MaskVals[i] < 0 || MaskVals[i] == i)
5075         InOrder.set(i);
5076   }
5077
5078   // The other elements are put in the right place using pextrw and pinsrw.
5079   for (unsigned i = 0; i != 8; ++i) {
5080     if (InOrder[i])
5081       continue;
5082     int EltIdx = MaskVals[i];
5083     if (EltIdx < 0)
5084       continue;
5085     SDValue ExtOp = (EltIdx < 8)
5086     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5087                   DAG.getIntPtrConstant(EltIdx))
5088     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5089                   DAG.getIntPtrConstant(EltIdx - 8));
5090     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5091                        DAG.getIntPtrConstant(i));
5092   }
5093   return NewV;
5094 }
5095
5096 // v16i8 shuffles - Prefer shuffles in the following order:
5097 // 1. [ssse3] 1 x pshufb
5098 // 2. [ssse3] 2 x pshufb + 1 x por
5099 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5100 static
5101 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5102                                  SelectionDAG &DAG,
5103                                  const X86TargetLowering &TLI) {
5104   SDValue V1 = SVOp->getOperand(0);
5105   SDValue V2 = SVOp->getOperand(1);
5106   DebugLoc dl = SVOp->getDebugLoc();
5107   SmallVector<int, 16> MaskVals;
5108   SVOp->getMask(MaskVals);
5109
5110   // If we have SSSE3, case 1 is generated when all result bytes come from
5111   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5112   // present, fall back to case 3.
5113   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5114   bool V1Only = true;
5115   bool V2Only = true;
5116   for (unsigned i = 0; i < 16; ++i) {
5117     int EltIdx = MaskVals[i];
5118     if (EltIdx < 0)
5119       continue;
5120     if (EltIdx < 16)
5121       V2Only = false;
5122     else
5123       V1Only = false;
5124   }
5125
5126   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5127   if (TLI.getSubtarget()->hasSSSE3()) {
5128     SmallVector<SDValue,16> pshufbMask;
5129
5130     // If all result elements are from one input vector, then only translate
5131     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5132     //
5133     // Otherwise, we have elements from both input vectors, and must zero out
5134     // elements that come from V2 in the first mask, and V1 in the second mask
5135     // so that we can OR them together.
5136     bool TwoInputs = !(V1Only || V2Only);
5137     for (unsigned i = 0; i != 16; ++i) {
5138       int EltIdx = MaskVals[i];
5139       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5140         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5141         continue;
5142       }
5143       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5144     }
5145     // If all the elements are from V2, assign it to V1 and return after
5146     // building the first pshufb.
5147     if (V2Only)
5148       V1 = V2;
5149     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5150                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5151                                  MVT::v16i8, &pshufbMask[0], 16));
5152     if (!TwoInputs)
5153       return V1;
5154
5155     // Calculate the shuffle mask for the second input, shuffle it, and
5156     // OR it with the first shuffled input.
5157     pshufbMask.clear();
5158     for (unsigned i = 0; i != 16; ++i) {
5159       int EltIdx = MaskVals[i];
5160       if (EltIdx < 16) {
5161         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5162         continue;
5163       }
5164       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5165     }
5166     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5167                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5168                                  MVT::v16i8, &pshufbMask[0], 16));
5169     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5170   }
5171
5172   // No SSSE3 - Calculate in place words and then fix all out of place words
5173   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5174   // the 16 different words that comprise the two doublequadword input vectors.
5175   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5176   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5177   SDValue NewV = V2Only ? V2 : V1;
5178   for (int i = 0; i != 8; ++i) {
5179     int Elt0 = MaskVals[i*2];
5180     int Elt1 = MaskVals[i*2+1];
5181
5182     // This word of the result is all undef, skip it.
5183     if (Elt0 < 0 && Elt1 < 0)
5184       continue;
5185
5186     // This word of the result is already in the correct place, skip it.
5187     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5188       continue;
5189     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5190       continue;
5191
5192     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5193     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5194     SDValue InsElt;
5195
5196     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5197     // using a single extract together, load it and store it.
5198     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5199       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5200                            DAG.getIntPtrConstant(Elt1 / 2));
5201       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5202                         DAG.getIntPtrConstant(i));
5203       continue;
5204     }
5205
5206     // If Elt1 is defined, extract it from the appropriate source.  If the
5207     // source byte is not also odd, shift the extracted word left 8 bits
5208     // otherwise clear the bottom 8 bits if we need to do an or.
5209     if (Elt1 >= 0) {
5210       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5211                            DAG.getIntPtrConstant(Elt1 / 2));
5212       if ((Elt1 & 1) == 0)
5213         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5214                              DAG.getConstant(8,
5215                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5216       else if (Elt0 >= 0)
5217         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5218                              DAG.getConstant(0xFF00, MVT::i16));
5219     }
5220     // If Elt0 is defined, extract it from the appropriate source.  If the
5221     // source byte is not also even, shift the extracted word right 8 bits. If
5222     // Elt1 was also defined, OR the extracted values together before
5223     // inserting them in the result.
5224     if (Elt0 >= 0) {
5225       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5226                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5227       if ((Elt0 & 1) != 0)
5228         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5229                               DAG.getConstant(8,
5230                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5231       else if (Elt1 >= 0)
5232         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5233                              DAG.getConstant(0x00FF, MVT::i16));
5234       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5235                          : InsElt0;
5236     }
5237     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5238                        DAG.getIntPtrConstant(i));
5239   }
5240   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5241 }
5242
5243 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5244 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5245 /// done when every pair / quad of shuffle mask elements point to elements in
5246 /// the right sequence. e.g.
5247 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5248 static
5249 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5250                                  SelectionDAG &DAG, DebugLoc dl) {
5251   EVT VT = SVOp->getValueType(0);
5252   SDValue V1 = SVOp->getOperand(0);
5253   SDValue V2 = SVOp->getOperand(1);
5254   unsigned NumElems = VT.getVectorNumElements();
5255   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5256   EVT NewVT;
5257   switch (VT.getSimpleVT().SimpleTy) {
5258   default: assert(false && "Unexpected!");
5259   case MVT::v4f32: NewVT = MVT::v2f64; break;
5260   case MVT::v4i32: NewVT = MVT::v2i64; break;
5261   case MVT::v8i16: NewVT = MVT::v4i32; break;
5262   case MVT::v16i8: NewVT = MVT::v4i32; break;
5263   }
5264
5265   int Scale = NumElems / NewWidth;
5266   SmallVector<int, 8> MaskVec;
5267   for (unsigned i = 0; i < NumElems; i += Scale) {
5268     int StartIdx = -1;
5269     for (int j = 0; j < Scale; ++j) {
5270       int EltIdx = SVOp->getMaskElt(i+j);
5271       if (EltIdx < 0)
5272         continue;
5273       if (StartIdx == -1)
5274         StartIdx = EltIdx - (EltIdx % Scale);
5275       if (EltIdx != StartIdx + j)
5276         return SDValue();
5277     }
5278     if (StartIdx == -1)
5279       MaskVec.push_back(-1);
5280     else
5281       MaskVec.push_back(StartIdx / Scale);
5282   }
5283
5284   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5285   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5286   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5287 }
5288
5289 /// getVZextMovL - Return a zero-extending vector move low node.
5290 ///
5291 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5292                             SDValue SrcOp, SelectionDAG &DAG,
5293                             const X86Subtarget *Subtarget, DebugLoc dl) {
5294   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5295     LoadSDNode *LD = NULL;
5296     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5297       LD = dyn_cast<LoadSDNode>(SrcOp);
5298     if (!LD) {
5299       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5300       // instead.
5301       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5302       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5303           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5304           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5305           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5306         // PR2108
5307         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5308         return DAG.getNode(ISD::BITCAST, dl, VT,
5309                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5310                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5311                                                    OpVT,
5312                                                    SrcOp.getOperand(0)
5313                                                           .getOperand(0))));
5314       }
5315     }
5316   }
5317
5318   return DAG.getNode(ISD::BITCAST, dl, VT,
5319                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5320                                  DAG.getNode(ISD::BITCAST, dl,
5321                                              OpVT, SrcOp)));
5322 }
5323
5324 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5325 /// shuffles.
5326 static SDValue
5327 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5328   SDValue V1 = SVOp->getOperand(0);
5329   SDValue V2 = SVOp->getOperand(1);
5330   DebugLoc dl = SVOp->getDebugLoc();
5331   EVT VT = SVOp->getValueType(0);
5332
5333   SmallVector<std::pair<int, int>, 8> Locs;
5334   Locs.resize(4);
5335   SmallVector<int, 8> Mask1(4U, -1);
5336   SmallVector<int, 8> PermMask;
5337   SVOp->getMask(PermMask);
5338
5339   unsigned NumHi = 0;
5340   unsigned NumLo = 0;
5341   for (unsigned i = 0; i != 4; ++i) {
5342     int Idx = PermMask[i];
5343     if (Idx < 0) {
5344       Locs[i] = std::make_pair(-1, -1);
5345     } else {
5346       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5347       if (Idx < 4) {
5348         Locs[i] = std::make_pair(0, NumLo);
5349         Mask1[NumLo] = Idx;
5350         NumLo++;
5351       } else {
5352         Locs[i] = std::make_pair(1, NumHi);
5353         if (2+NumHi < 4)
5354           Mask1[2+NumHi] = Idx;
5355         NumHi++;
5356       }
5357     }
5358   }
5359
5360   if (NumLo <= 2 && NumHi <= 2) {
5361     // If no more than two elements come from either vector. This can be
5362     // implemented with two shuffles. First shuffle gather the elements.
5363     // The second shuffle, which takes the first shuffle as both of its
5364     // vector operands, put the elements into the right order.
5365     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5366
5367     SmallVector<int, 8> Mask2(4U, -1);
5368
5369     for (unsigned i = 0; i != 4; ++i) {
5370       if (Locs[i].first == -1)
5371         continue;
5372       else {
5373         unsigned Idx = (i < 2) ? 0 : 4;
5374         Idx += Locs[i].first * 2 + Locs[i].second;
5375         Mask2[i] = Idx;
5376       }
5377     }
5378
5379     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5380   } else if (NumLo == 3 || NumHi == 3) {
5381     // Otherwise, we must have three elements from one vector, call it X, and
5382     // one element from the other, call it Y.  First, use a shufps to build an
5383     // intermediate vector with the one element from Y and the element from X
5384     // that will be in the same half in the final destination (the indexes don't
5385     // matter). Then, use a shufps to build the final vector, taking the half
5386     // containing the element from Y from the intermediate, and the other half
5387     // from X.
5388     if (NumHi == 3) {
5389       // Normalize it so the 3 elements come from V1.
5390       CommuteVectorShuffleMask(PermMask, VT);
5391       std::swap(V1, V2);
5392     }
5393
5394     // Find the element from V2.
5395     unsigned HiIndex;
5396     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5397       int Val = PermMask[HiIndex];
5398       if (Val < 0)
5399         continue;
5400       if (Val >= 4)
5401         break;
5402     }
5403
5404     Mask1[0] = PermMask[HiIndex];
5405     Mask1[1] = -1;
5406     Mask1[2] = PermMask[HiIndex^1];
5407     Mask1[3] = -1;
5408     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5409
5410     if (HiIndex >= 2) {
5411       Mask1[0] = PermMask[0];
5412       Mask1[1] = PermMask[1];
5413       Mask1[2] = HiIndex & 1 ? 6 : 4;
5414       Mask1[3] = HiIndex & 1 ? 4 : 6;
5415       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5416     } else {
5417       Mask1[0] = HiIndex & 1 ? 2 : 0;
5418       Mask1[1] = HiIndex & 1 ? 0 : 2;
5419       Mask1[2] = PermMask[2];
5420       Mask1[3] = PermMask[3];
5421       if (Mask1[2] >= 0)
5422         Mask1[2] += 4;
5423       if (Mask1[3] >= 0)
5424         Mask1[3] += 4;
5425       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5426     }
5427   }
5428
5429   // Break it into (shuffle shuffle_hi, shuffle_lo).
5430   Locs.clear();
5431   Locs.resize(4);
5432   SmallVector<int,8> LoMask(4U, -1);
5433   SmallVector<int,8> HiMask(4U, -1);
5434
5435   SmallVector<int,8> *MaskPtr = &LoMask;
5436   unsigned MaskIdx = 0;
5437   unsigned LoIdx = 0;
5438   unsigned HiIdx = 2;
5439   for (unsigned i = 0; i != 4; ++i) {
5440     if (i == 2) {
5441       MaskPtr = &HiMask;
5442       MaskIdx = 1;
5443       LoIdx = 0;
5444       HiIdx = 2;
5445     }
5446     int Idx = PermMask[i];
5447     if (Idx < 0) {
5448       Locs[i] = std::make_pair(-1, -1);
5449     } else if (Idx < 4) {
5450       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5451       (*MaskPtr)[LoIdx] = Idx;
5452       LoIdx++;
5453     } else {
5454       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5455       (*MaskPtr)[HiIdx] = Idx;
5456       HiIdx++;
5457     }
5458   }
5459
5460   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5461   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5462   SmallVector<int, 8> MaskOps;
5463   for (unsigned i = 0; i != 4; ++i) {
5464     if (Locs[i].first == -1) {
5465       MaskOps.push_back(-1);
5466     } else {
5467       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5468       MaskOps.push_back(Idx);
5469     }
5470   }
5471   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5472 }
5473
5474 static bool MayFoldVectorLoad(SDValue V) {
5475   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5476     V = V.getOperand(0);
5477   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5478     V = V.getOperand(0);
5479   if (MayFoldLoad(V))
5480     return true;
5481   return false;
5482 }
5483
5484 // FIXME: the version above should always be used. Since there's
5485 // a bug where several vector shuffles can't be folded because the
5486 // DAG is not updated during lowering and a node claims to have two
5487 // uses while it only has one, use this version, and let isel match
5488 // another instruction if the load really happens to have more than
5489 // one use. Remove this version after this bug get fixed.
5490 // rdar://8434668, PR8156
5491 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5492   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5493     V = V.getOperand(0);
5494   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5495     V = V.getOperand(0);
5496   if (ISD::isNormalLoad(V.getNode()))
5497     return true;
5498   return false;
5499 }
5500
5501 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5502 /// a vector extract, and if both can be later optimized into a single load.
5503 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5504 /// here because otherwise a target specific shuffle node is going to be
5505 /// emitted for this shuffle, and the optimization not done.
5506 /// FIXME: This is probably not the best approach, but fix the problem
5507 /// until the right path is decided.
5508 static
5509 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5510                                          const TargetLowering &TLI) {
5511   EVT VT = V.getValueType();
5512   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5513
5514   // Be sure that the vector shuffle is present in a pattern like this:
5515   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5516   if (!V.hasOneUse())
5517     return false;
5518
5519   SDNode *N = *V.getNode()->use_begin();
5520   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5521     return false;
5522
5523   SDValue EltNo = N->getOperand(1);
5524   if (!isa<ConstantSDNode>(EltNo))
5525     return false;
5526
5527   // If the bit convert changed the number of elements, it is unsafe
5528   // to examine the mask.
5529   bool HasShuffleIntoBitcast = false;
5530   if (V.getOpcode() == ISD::BITCAST) {
5531     EVT SrcVT = V.getOperand(0).getValueType();
5532     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5533       return false;
5534     V = V.getOperand(0);
5535     HasShuffleIntoBitcast = true;
5536   }
5537
5538   // Select the input vector, guarding against out of range extract vector.
5539   unsigned NumElems = VT.getVectorNumElements();
5540   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5541   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5542   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5543
5544   // Skip one more bit_convert if necessary
5545   if (V.getOpcode() == ISD::BITCAST)
5546     V = V.getOperand(0);
5547
5548   if (ISD::isNormalLoad(V.getNode())) {
5549     // Is the original load suitable?
5550     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5551
5552     // FIXME: avoid the multi-use bug that is preventing lots of
5553     // of foldings to be detected, this is still wrong of course, but
5554     // give the temporary desired behavior, and if it happens that
5555     // the load has real more uses, during isel it will not fold, and
5556     // will generate poor code.
5557     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5558       return false;
5559
5560     if (!HasShuffleIntoBitcast)
5561       return true;
5562
5563     // If there's a bitcast before the shuffle, check if the load type and
5564     // alignment is valid.
5565     unsigned Align = LN0->getAlignment();
5566     unsigned NewAlign =
5567       TLI.getTargetData()->getABITypeAlignment(
5568                                     VT.getTypeForEVT(*DAG.getContext()));
5569
5570     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5571       return false;
5572   }
5573
5574   return true;
5575 }
5576
5577 static
5578 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5579   EVT VT = Op.getValueType();
5580
5581   // Canonizalize to v2f64.
5582   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5583   return DAG.getNode(ISD::BITCAST, dl, VT,
5584                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5585                                           V1, DAG));
5586 }
5587
5588 static
5589 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5590                         bool HasSSE2) {
5591   SDValue V1 = Op.getOperand(0);
5592   SDValue V2 = Op.getOperand(1);
5593   EVT VT = Op.getValueType();
5594
5595   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5596
5597   if (HasSSE2 && VT == MVT::v2f64)
5598     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5599
5600   // v4f32 or v4i32
5601   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5602 }
5603
5604 static
5605 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5606   SDValue V1 = Op.getOperand(0);
5607   SDValue V2 = Op.getOperand(1);
5608   EVT VT = Op.getValueType();
5609
5610   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5611          "unsupported shuffle type");
5612
5613   if (V2.getOpcode() == ISD::UNDEF)
5614     V2 = V1;
5615
5616   // v4i32 or v4f32
5617   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5618 }
5619
5620 static
5621 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5622   SDValue V1 = Op.getOperand(0);
5623   SDValue V2 = Op.getOperand(1);
5624   EVT VT = Op.getValueType();
5625   unsigned NumElems = VT.getVectorNumElements();
5626
5627   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5628   // operand of these instructions is only memory, so check if there's a
5629   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5630   // same masks.
5631   bool CanFoldLoad = false;
5632
5633   // Trivial case, when V2 comes from a load.
5634   if (MayFoldVectorLoad(V2))
5635     CanFoldLoad = true;
5636
5637   // When V1 is a load, it can be folded later into a store in isel, example:
5638   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5639   //    turns into:
5640   //  (MOVLPSmr addr:$src1, VR128:$src2)
5641   // So, recognize this potential and also use MOVLPS or MOVLPD
5642   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5643     CanFoldLoad = true;
5644
5645   // Both of them can't be memory operations though.
5646   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5647     CanFoldLoad = false;
5648
5649   if (CanFoldLoad) {
5650     if (HasSSE2 && NumElems == 2)
5651       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5652
5653     if (NumElems == 4)
5654       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5655   }
5656
5657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5658   // movl and movlp will both match v2i64, but v2i64 is never matched by
5659   // movl earlier because we make it strict to avoid messing with the movlp load
5660   // folding logic (see the code above getMOVLP call). Match it here then,
5661   // this is horrible, but will stay like this until we move all shuffle
5662   // matching to x86 specific nodes. Note that for the 1st condition all
5663   // types are matched with movsd.
5664   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5665     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5666   else if (HasSSE2)
5667     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5668
5669
5670   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5671
5672   // Invert the operand order and use SHUFPS to match it.
5673   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5674                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5675 }
5676
5677 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5678   switch(VT.getSimpleVT().SimpleTy) {
5679   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5680   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5681   case MVT::v4f32:
5682     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5683   case MVT::v2f64:
5684     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5685   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5686   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5687   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5688   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5689   default:
5690     llvm_unreachable("Unknown type for unpckl");
5691   }
5692   return 0;
5693 }
5694
5695 static inline unsigned getUNPCKHOpcode(EVT VT) {
5696   switch(VT.getSimpleVT().SimpleTy) {
5697   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5698   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5699   case MVT::v4f32: return X86ISD::UNPCKHPS;
5700   case MVT::v2f64: return X86ISD::UNPCKHPD;
5701   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5702   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5703   default:
5704     llvm_unreachable("Unknown type for unpckh");
5705   }
5706   return 0;
5707 }
5708
5709 static
5710 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5711                                const TargetLowering &TLI,
5712                                const X86Subtarget *Subtarget) {
5713   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5714   EVT VT = Op.getValueType();
5715   DebugLoc dl = Op.getDebugLoc();
5716   SDValue V1 = Op.getOperand(0);
5717   SDValue V2 = Op.getOperand(1);
5718
5719   if (isZeroShuffle(SVOp))
5720     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5721
5722   // Handle splat operations
5723   if (SVOp->isSplat()) {
5724     unsigned NumElem = VT.getVectorNumElements();
5725     // Special case, this is the only place now where it's allowed to return
5726     // a vector_shuffle operation without using a target specific node, because
5727     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
5728     // this be moved to DAGCombine instead?
5729     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5730       return Op;
5731
5732     // Handle splats by matching through known masks
5733     if ((VT.is128BitVector() && NumElem <= 4) ||
5734         (VT.is256BitVector() && NumElem <= 8))
5735       return SDValue();
5736
5737     // All i16 and i8 vector types can't be used directly by a generic shuffle
5738     // instruction because the target has no such instruction. Generate shuffles
5739     // which repeat i16 and i8 several times until they fit in i32, and then can
5740     // be manipulated by target suported shuffles. After the insertion of the
5741     // necessary shuffles, the result is bitcasted back to v4f32 or v8f32.
5742     return PromoteSplat(SVOp, DAG);
5743   }
5744
5745   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5746   // do it!
5747   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5748     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5749     if (NewOp.getNode())
5750       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5751   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5752     // FIXME: Figure out a cleaner way to do this.
5753     // Try to make use of movq to zero out the top part.
5754     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5755       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5756       if (NewOp.getNode()) {
5757         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5758           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5759                               DAG, Subtarget, dl);
5760       }
5761     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5762       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5763       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5764         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5765                             DAG, Subtarget, dl);
5766     }
5767   }
5768   return SDValue();
5769 }
5770
5771 SDValue
5772 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5773   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5774   SDValue V1 = Op.getOperand(0);
5775   SDValue V2 = Op.getOperand(1);
5776   EVT VT = Op.getValueType();
5777   DebugLoc dl = Op.getDebugLoc();
5778   unsigned NumElems = VT.getVectorNumElements();
5779   bool isMMX = VT.getSizeInBits() == 64;
5780   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5781   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5782   bool V1IsSplat = false;
5783   bool V2IsSplat = false;
5784   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5785   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5786   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5787   MachineFunction &MF = DAG.getMachineFunction();
5788   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5789
5790   // Shuffle operations on MMX not supported.
5791   if (isMMX)
5792     return Op;
5793
5794   // Vector shuffle lowering takes 3 steps:
5795   //
5796   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5797   //    narrowing and commutation of operands should be handled.
5798   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5799   //    shuffle nodes.
5800   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5801   //    so the shuffle can be broken into other shuffles and the legalizer can
5802   //    try the lowering again.
5803   //
5804   // The general ideia is that no vector_shuffle operation should be left to
5805   // be matched during isel, all of them must be converted to a target specific
5806   // node here.
5807
5808   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5809   // narrowing and commutation of operands should be handled. The actual code
5810   // doesn't include all of those, work in progress...
5811   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5812   if (NewOp.getNode())
5813     return NewOp;
5814
5815   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5816   // unpckh_undef). Only use pshufd if speed is more important than size.
5817   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5818     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5819       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5820   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5821     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5822       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5823
5824   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5825       RelaxedMayFoldVectorLoad(V1))
5826     return getMOVDDup(Op, dl, V1, DAG);
5827
5828   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5829     return getMOVHighToLow(Op, dl, DAG);
5830
5831   // Use to match splats
5832   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5833       (VT == MVT::v2f64 || VT == MVT::v2i64))
5834     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5835
5836   if (X86::isPSHUFDMask(SVOp)) {
5837     // The actual implementation will match the mask in the if above and then
5838     // during isel it can match several different instructions, not only pshufd
5839     // as its name says, sad but true, emulate the behavior for now...
5840     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5841         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5842
5843     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5844
5845     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5846       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5847
5848     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5849       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5850                                   TargetMask, DAG);
5851
5852     if (VT == MVT::v4f32)
5853       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5854                                   TargetMask, DAG);
5855   }
5856
5857   // Check if this can be converted into a logical shift.
5858   bool isLeft = false;
5859   unsigned ShAmt = 0;
5860   SDValue ShVal;
5861   bool isShift = getSubtarget()->hasSSE2() &&
5862     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5863   if (isShift && ShVal.hasOneUse()) {
5864     // If the shifted value has multiple uses, it may be cheaper to use
5865     // v_set0 + movlhps or movhlps, etc.
5866     EVT EltVT = VT.getVectorElementType();
5867     ShAmt *= EltVT.getSizeInBits();
5868     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5869   }
5870
5871   if (X86::isMOVLMask(SVOp)) {
5872     if (V1IsUndef)
5873       return V2;
5874     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5875       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5876     if (!X86::isMOVLPMask(SVOp)) {
5877       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5878         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5879
5880       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5881         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5882     }
5883   }
5884
5885   // FIXME: fold these into legal mask.
5886   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5887     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5888
5889   if (X86::isMOVHLPSMask(SVOp))
5890     return getMOVHighToLow(Op, dl, DAG);
5891
5892   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5893     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5894
5895   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5896     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5897
5898   if (X86::isMOVLPMask(SVOp))
5899     return getMOVLP(Op, dl, DAG, HasSSE2);
5900
5901   if (ShouldXformToMOVHLPS(SVOp) ||
5902       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5903     return CommuteVectorShuffle(SVOp, DAG);
5904
5905   if (isShift) {
5906     // No better options. Use a vshl / vsrl.
5907     EVT EltVT = VT.getVectorElementType();
5908     ShAmt *= EltVT.getSizeInBits();
5909     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5910   }
5911
5912   bool Commuted = false;
5913   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5914   // 1,1,1,1 -> v8i16 though.
5915   V1IsSplat = isSplatVector(V1.getNode());
5916   V2IsSplat = isSplatVector(V2.getNode());
5917
5918   // Canonicalize the splat or undef, if present, to be on the RHS.
5919   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5920     Op = CommuteVectorShuffle(SVOp, DAG);
5921     SVOp = cast<ShuffleVectorSDNode>(Op);
5922     V1 = SVOp->getOperand(0);
5923     V2 = SVOp->getOperand(1);
5924     std::swap(V1IsSplat, V2IsSplat);
5925     std::swap(V1IsUndef, V2IsUndef);
5926     Commuted = true;
5927   }
5928
5929   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5930     // Shuffling low element of v1 into undef, just return v1.
5931     if (V2IsUndef)
5932       return V1;
5933     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5934     // the instruction selector will not match, so get a canonical MOVL with
5935     // swapped operands to undo the commute.
5936     return getMOVL(DAG, dl, VT, V2, V1);
5937   }
5938
5939   if (X86::isUNPCKLMask(SVOp))
5940     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5941                                 dl, VT, V1, V2, DAG);
5942
5943   if (X86::isUNPCKHMask(SVOp))
5944     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5945
5946   if (V2IsSplat) {
5947     // Normalize mask so all entries that point to V2 points to its first
5948     // element then try to match unpck{h|l} again. If match, return a
5949     // new vector_shuffle with the corrected mask.
5950     SDValue NewMask = NormalizeMask(SVOp, DAG);
5951     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5952     if (NSVOp != SVOp) {
5953       if (X86::isUNPCKLMask(NSVOp, true)) {
5954         return NewMask;
5955       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5956         return NewMask;
5957       }
5958     }
5959   }
5960
5961   if (Commuted) {
5962     // Commute is back and try unpck* again.
5963     // FIXME: this seems wrong.
5964     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5965     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5966
5967     if (X86::isUNPCKLMask(NewSVOp))
5968       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5969                                   dl, VT, V2, V1, DAG);
5970
5971     if (X86::isUNPCKHMask(NewSVOp))
5972       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5973   }
5974
5975   // Normalize the node to match x86 shuffle ops if needed
5976   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5977     return CommuteVectorShuffle(SVOp, DAG);
5978
5979   // The checks below are all present in isShuffleMaskLegal, but they are
5980   // inlined here right now to enable us to directly emit target specific
5981   // nodes, and remove one by one until they don't return Op anymore.
5982   SmallVector<int, 16> M;
5983   SVOp->getMask(M);
5984
5985   if (isPALIGNRMask(M, VT, HasSSSE3))
5986     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5987                                 X86::getShufflePALIGNRImmediate(SVOp),
5988                                 DAG);
5989
5990   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5991       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5992     if (VT == MVT::v2f64) {
5993       X86ISD::NodeType Opcode =
5994         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5995       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5996     }
5997     if (VT == MVT::v2i64)
5998       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5999   }
6000
6001   if (isPSHUFHWMask(M, VT))
6002     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6003                                 X86::getShufflePSHUFHWImmediate(SVOp),
6004                                 DAG);
6005
6006   if (isPSHUFLWMask(M, VT))
6007     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6008                                 X86::getShufflePSHUFLWImmediate(SVOp),
6009                                 DAG);
6010
6011   if (isSHUFPMask(M, VT)) {
6012     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6013     if (VT == MVT::v4f32 || VT == MVT::v4i32)
6014       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6015                                   TargetMask, DAG);
6016     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6017       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6018                                   TargetMask, DAG);
6019   }
6020
6021   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6022     if (VT != MVT::v2i64 && VT != MVT::v2f64)
6023       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
6024                                   dl, VT, V1, V1, DAG);
6025   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6026     if (VT != MVT::v2i64 && VT != MVT::v2f64)
6027       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6028
6029   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6030   if (VT == MVT::v8i16) {
6031     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6032     if (NewOp.getNode())
6033       return NewOp;
6034   }
6035
6036   if (VT == MVT::v16i8) {
6037     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6038     if (NewOp.getNode())
6039       return NewOp;
6040   }
6041
6042   // Handle all 4 wide cases with a number of shuffles.
6043   if (NumElems == 4)
6044     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
6045
6046   return SDValue();
6047 }
6048
6049 SDValue
6050 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6051                                                 SelectionDAG &DAG) const {
6052   EVT VT = Op.getValueType();
6053   DebugLoc dl = Op.getDebugLoc();
6054   if (VT.getSizeInBits() == 8) {
6055     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6056                                     Op.getOperand(0), Op.getOperand(1));
6057     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6058                                     DAG.getValueType(VT));
6059     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6060   } else if (VT.getSizeInBits() == 16) {
6061     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6062     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6063     if (Idx == 0)
6064       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6065                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6066                                      DAG.getNode(ISD::BITCAST, dl,
6067                                                  MVT::v4i32,
6068                                                  Op.getOperand(0)),
6069                                      Op.getOperand(1)));
6070     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6071                                     Op.getOperand(0), Op.getOperand(1));
6072     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6073                                     DAG.getValueType(VT));
6074     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6075   } else if (VT == MVT::f32) {
6076     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6077     // the result back to FR32 register. It's only worth matching if the
6078     // result has a single use which is a store or a bitcast to i32.  And in
6079     // the case of a store, it's not worth it if the index is a constant 0,
6080     // because a MOVSSmr can be used instead, which is smaller and faster.
6081     if (!Op.hasOneUse())
6082       return SDValue();
6083     SDNode *User = *Op.getNode()->use_begin();
6084     if ((User->getOpcode() != ISD::STORE ||
6085          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6086           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6087         (User->getOpcode() != ISD::BITCAST ||
6088          User->getValueType(0) != MVT::i32))
6089       return SDValue();
6090     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6091                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6092                                               Op.getOperand(0)),
6093                                               Op.getOperand(1));
6094     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6095   } else if (VT == MVT::i32) {
6096     // ExtractPS works with constant index.
6097     if (isa<ConstantSDNode>(Op.getOperand(1)))
6098       return Op;
6099   }
6100   return SDValue();
6101 }
6102
6103
6104 SDValue
6105 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6106                                            SelectionDAG &DAG) const {
6107   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6108     return SDValue();
6109
6110   SDValue Vec = Op.getOperand(0);
6111   EVT VecVT = Vec.getValueType();
6112
6113   // If this is a 256-bit vector result, first extract the 128-bit
6114   // vector and then extract from the 128-bit vector.
6115   if (VecVT.getSizeInBits() > 128) {
6116     DebugLoc dl = Op.getNode()->getDebugLoc();
6117     unsigned NumElems = VecVT.getVectorNumElements();
6118     SDValue Idx = Op.getOperand(1);
6119
6120     if (!isa<ConstantSDNode>(Idx))
6121       return SDValue();
6122
6123     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6124     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6125
6126     // Get the 128-bit vector.
6127     bool Upper = IdxVal >= ExtractNumElems;
6128     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6129
6130     // Extract from it.
6131     SDValue ScaledIdx = Idx;
6132     if (Upper)
6133       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6134                               DAG.getConstant(ExtractNumElems,
6135                                               Idx.getValueType()));
6136     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6137                        ScaledIdx);
6138   }
6139
6140   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6141
6142   if (Subtarget->hasSSE41()) {
6143     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6144     if (Res.getNode())
6145       return Res;
6146   }
6147
6148   EVT VT = Op.getValueType();
6149   DebugLoc dl = Op.getDebugLoc();
6150   // TODO: handle v16i8.
6151   if (VT.getSizeInBits() == 16) {
6152     SDValue Vec = Op.getOperand(0);
6153     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6154     if (Idx == 0)
6155       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6156                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6157                                      DAG.getNode(ISD::BITCAST, dl,
6158                                                  MVT::v4i32, Vec),
6159                                      Op.getOperand(1)));
6160     // Transform it so it match pextrw which produces a 32-bit result.
6161     EVT EltVT = MVT::i32;
6162     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6163                                     Op.getOperand(0), Op.getOperand(1));
6164     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6165                                     DAG.getValueType(VT));
6166     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6167   } else if (VT.getSizeInBits() == 32) {
6168     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6169     if (Idx == 0)
6170       return Op;
6171
6172     // SHUFPS the element to the lowest double word, then movss.
6173     int Mask[4] = { Idx, -1, -1, -1 };
6174     EVT VVT = Op.getOperand(0).getValueType();
6175     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6176                                        DAG.getUNDEF(VVT), Mask);
6177     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6178                        DAG.getIntPtrConstant(0));
6179   } else if (VT.getSizeInBits() == 64) {
6180     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6181     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6182     //        to match extract_elt for f64.
6183     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6184     if (Idx == 0)
6185       return Op;
6186
6187     // UNPCKHPD the element to the lowest double word, then movsd.
6188     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6189     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6190     int Mask[2] = { 1, -1 };
6191     EVT VVT = Op.getOperand(0).getValueType();
6192     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6193                                        DAG.getUNDEF(VVT), Mask);
6194     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6195                        DAG.getIntPtrConstant(0));
6196   }
6197
6198   return SDValue();
6199 }
6200
6201 SDValue
6202 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6203                                                SelectionDAG &DAG) const {
6204   EVT VT = Op.getValueType();
6205   EVT EltVT = VT.getVectorElementType();
6206   DebugLoc dl = Op.getDebugLoc();
6207
6208   SDValue N0 = Op.getOperand(0);
6209   SDValue N1 = Op.getOperand(1);
6210   SDValue N2 = Op.getOperand(2);
6211
6212   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6213       isa<ConstantSDNode>(N2)) {
6214     unsigned Opc;
6215     if (VT == MVT::v8i16)
6216       Opc = X86ISD::PINSRW;
6217     else if (VT == MVT::v16i8)
6218       Opc = X86ISD::PINSRB;
6219     else
6220       Opc = X86ISD::PINSRB;
6221
6222     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6223     // argument.
6224     if (N1.getValueType() != MVT::i32)
6225       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6226     if (N2.getValueType() != MVT::i32)
6227       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6228     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6229   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6230     // Bits [7:6] of the constant are the source select.  This will always be
6231     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6232     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6233     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6234     // Bits [5:4] of the constant are the destination select.  This is the
6235     //  value of the incoming immediate.
6236     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6237     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6238     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6239     // Create this as a scalar to vector..
6240     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6241     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6242   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6243     // PINSR* works with constant index.
6244     return Op;
6245   }
6246   return SDValue();
6247 }
6248
6249 SDValue
6250 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6251   EVT VT = Op.getValueType();
6252   EVT EltVT = VT.getVectorElementType();
6253
6254   DebugLoc dl = Op.getDebugLoc();
6255   SDValue N0 = Op.getOperand(0);
6256   SDValue N1 = Op.getOperand(1);
6257   SDValue N2 = Op.getOperand(2);
6258
6259   // If this is a 256-bit vector result, first insert into a 128-bit
6260   // vector and then insert into the 256-bit vector.
6261   if (VT.getSizeInBits() > 128) {
6262     if (!isa<ConstantSDNode>(N2))
6263       return SDValue();
6264
6265     // Get the 128-bit vector.
6266     unsigned NumElems = VT.getVectorNumElements();
6267     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6268     bool Upper = IdxVal >= NumElems / 2;
6269
6270     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6271
6272     // Insert into it.
6273     SDValue ScaledN2 = N2;
6274     if (Upper)
6275       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6276                              DAG.getConstant(NumElems /
6277                                              (VT.getSizeInBits() / 128),
6278                                              N2.getValueType()));
6279     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6280                      N1, ScaledN2);
6281
6282     // Insert the 128-bit vector
6283     // FIXME: Why UNDEF?
6284     return Insert128BitVector(N0, Op, N2, DAG, dl);
6285   }
6286
6287   if (Subtarget->hasSSE41())
6288     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6289
6290   if (EltVT == MVT::i8)
6291     return SDValue();
6292
6293   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6294     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6295     // as its second argument.
6296     if (N1.getValueType() != MVT::i32)
6297       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6298     if (N2.getValueType() != MVT::i32)
6299       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6300     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6301   }
6302   return SDValue();
6303 }
6304
6305 SDValue
6306 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6307   LLVMContext *Context = DAG.getContext();
6308   DebugLoc dl = Op.getDebugLoc();
6309   EVT OpVT = Op.getValueType();
6310
6311   // If this is a 256-bit vector result, first insert into a 128-bit
6312   // vector and then insert into the 256-bit vector.
6313   if (OpVT.getSizeInBits() > 128) {
6314     // Insert into a 128-bit vector.
6315     EVT VT128 = EVT::getVectorVT(*Context,
6316                                  OpVT.getVectorElementType(),
6317                                  OpVT.getVectorNumElements() / 2);
6318
6319     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6320
6321     // Insert the 128-bit vector.
6322     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6323                               DAG.getConstant(0, MVT::i32),
6324                               DAG, dl);
6325   }
6326
6327   if (Op.getValueType() == MVT::v1i64 &&
6328       Op.getOperand(0).getValueType() == MVT::i64)
6329     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6330
6331   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6332   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6333          "Expected an SSE type!");
6334   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6335                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6336 }
6337
6338 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6339 // a simple subregister reference or explicit instructions to grab
6340 // upper bits of a vector.
6341 SDValue
6342 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6343   if (Subtarget->hasAVX()) {
6344     DebugLoc dl = Op.getNode()->getDebugLoc();
6345     SDValue Vec = Op.getNode()->getOperand(0);
6346     SDValue Idx = Op.getNode()->getOperand(1);
6347
6348     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6349         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6350         return Extract128BitVector(Vec, Idx, DAG, dl);
6351     }
6352   }
6353   return SDValue();
6354 }
6355
6356 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6357 // simple superregister reference or explicit instructions to insert
6358 // the upper bits of a vector.
6359 SDValue
6360 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6361   if (Subtarget->hasAVX()) {
6362     DebugLoc dl = Op.getNode()->getDebugLoc();
6363     SDValue Vec = Op.getNode()->getOperand(0);
6364     SDValue SubVec = Op.getNode()->getOperand(1);
6365     SDValue Idx = Op.getNode()->getOperand(2);
6366
6367     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6368         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6369       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6370     }
6371   }
6372   return SDValue();
6373 }
6374
6375 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6376 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6377 // one of the above mentioned nodes. It has to be wrapped because otherwise
6378 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6379 // be used to form addressing mode. These wrapped nodes will be selected
6380 // into MOV32ri.
6381 SDValue
6382 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6383   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6384
6385   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6386   // global base reg.
6387   unsigned char OpFlag = 0;
6388   unsigned WrapperKind = X86ISD::Wrapper;
6389   CodeModel::Model M = getTargetMachine().getCodeModel();
6390
6391   if (Subtarget->isPICStyleRIPRel() &&
6392       (M == CodeModel::Small || M == CodeModel::Kernel))
6393     WrapperKind = X86ISD::WrapperRIP;
6394   else if (Subtarget->isPICStyleGOT())
6395     OpFlag = X86II::MO_GOTOFF;
6396   else if (Subtarget->isPICStyleStubPIC())
6397     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6398
6399   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6400                                              CP->getAlignment(),
6401                                              CP->getOffset(), OpFlag);
6402   DebugLoc DL = CP->getDebugLoc();
6403   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6404   // With PIC, the address is actually $g + Offset.
6405   if (OpFlag) {
6406     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6407                          DAG.getNode(X86ISD::GlobalBaseReg,
6408                                      DebugLoc(), getPointerTy()),
6409                          Result);
6410   }
6411
6412   return Result;
6413 }
6414
6415 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6416   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6417
6418   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6419   // global base reg.
6420   unsigned char OpFlag = 0;
6421   unsigned WrapperKind = X86ISD::Wrapper;
6422   CodeModel::Model M = getTargetMachine().getCodeModel();
6423
6424   if (Subtarget->isPICStyleRIPRel() &&
6425       (M == CodeModel::Small || M == CodeModel::Kernel))
6426     WrapperKind = X86ISD::WrapperRIP;
6427   else if (Subtarget->isPICStyleGOT())
6428     OpFlag = X86II::MO_GOTOFF;
6429   else if (Subtarget->isPICStyleStubPIC())
6430     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6431
6432   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6433                                           OpFlag);
6434   DebugLoc DL = JT->getDebugLoc();
6435   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6436
6437   // With PIC, the address is actually $g + Offset.
6438   if (OpFlag)
6439     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6440                          DAG.getNode(X86ISD::GlobalBaseReg,
6441                                      DebugLoc(), getPointerTy()),
6442                          Result);
6443
6444   return Result;
6445 }
6446
6447 SDValue
6448 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6449   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6450
6451   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6452   // global base reg.
6453   unsigned char OpFlag = 0;
6454   unsigned WrapperKind = X86ISD::Wrapper;
6455   CodeModel::Model M = getTargetMachine().getCodeModel();
6456
6457   if (Subtarget->isPICStyleRIPRel() &&
6458       (M == CodeModel::Small || M == CodeModel::Kernel))
6459     WrapperKind = X86ISD::WrapperRIP;
6460   else if (Subtarget->isPICStyleGOT())
6461     OpFlag = X86II::MO_GOTOFF;
6462   else if (Subtarget->isPICStyleStubPIC())
6463     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6464
6465   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6466
6467   DebugLoc DL = Op.getDebugLoc();
6468   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6469
6470
6471   // With PIC, the address is actually $g + Offset.
6472   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6473       !Subtarget->is64Bit()) {
6474     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6475                          DAG.getNode(X86ISD::GlobalBaseReg,
6476                                      DebugLoc(), getPointerTy()),
6477                          Result);
6478   }
6479
6480   return Result;
6481 }
6482
6483 SDValue
6484 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6485   // Create the TargetBlockAddressAddress node.
6486   unsigned char OpFlags =
6487     Subtarget->ClassifyBlockAddressReference();
6488   CodeModel::Model M = getTargetMachine().getCodeModel();
6489   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6490   DebugLoc dl = Op.getDebugLoc();
6491   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6492                                        /*isTarget=*/true, OpFlags);
6493
6494   if (Subtarget->isPICStyleRIPRel() &&
6495       (M == CodeModel::Small || M == CodeModel::Kernel))
6496     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6497   else
6498     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6499
6500   // With PIC, the address is actually $g + Offset.
6501   if (isGlobalRelativeToPICBase(OpFlags)) {
6502     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6503                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6504                          Result);
6505   }
6506
6507   return Result;
6508 }
6509
6510 SDValue
6511 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6512                                       int64_t Offset,
6513                                       SelectionDAG &DAG) const {
6514   // Create the TargetGlobalAddress node, folding in the constant
6515   // offset if it is legal.
6516   unsigned char OpFlags =
6517     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6518   CodeModel::Model M = getTargetMachine().getCodeModel();
6519   SDValue Result;
6520   if (OpFlags == X86II::MO_NO_FLAG &&
6521       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6522     // A direct static reference to a global.
6523     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6524     Offset = 0;
6525   } else {
6526     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6527   }
6528
6529   if (Subtarget->isPICStyleRIPRel() &&
6530       (M == CodeModel::Small || M == CodeModel::Kernel))
6531     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6532   else
6533     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6534
6535   // With PIC, the address is actually $g + Offset.
6536   if (isGlobalRelativeToPICBase(OpFlags)) {
6537     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6538                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6539                          Result);
6540   }
6541
6542   // For globals that require a load from a stub to get the address, emit the
6543   // load.
6544   if (isGlobalStubReference(OpFlags))
6545     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6546                          MachinePointerInfo::getGOT(), false, false, 0);
6547
6548   // If there was a non-zero offset that we didn't fold, create an explicit
6549   // addition for it.
6550   if (Offset != 0)
6551     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6552                          DAG.getConstant(Offset, getPointerTy()));
6553
6554   return Result;
6555 }
6556
6557 SDValue
6558 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6559   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6560   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6561   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6562 }
6563
6564 static SDValue
6565 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6566            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6567            unsigned char OperandFlags) {
6568   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6569   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6570   DebugLoc dl = GA->getDebugLoc();
6571   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6572                                            GA->getValueType(0),
6573                                            GA->getOffset(),
6574                                            OperandFlags);
6575   if (InFlag) {
6576     SDValue Ops[] = { Chain,  TGA, *InFlag };
6577     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6578   } else {
6579     SDValue Ops[]  = { Chain, TGA };
6580     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6581   }
6582
6583   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6584   MFI->setAdjustsStack(true);
6585
6586   SDValue Flag = Chain.getValue(1);
6587   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6588 }
6589
6590 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6591 static SDValue
6592 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6593                                 const EVT PtrVT) {
6594   SDValue InFlag;
6595   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6596   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6597                                      DAG.getNode(X86ISD::GlobalBaseReg,
6598                                                  DebugLoc(), PtrVT), InFlag);
6599   InFlag = Chain.getValue(1);
6600
6601   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6602 }
6603
6604 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6605 static SDValue
6606 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6607                                 const EVT PtrVT) {
6608   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6609                     X86::RAX, X86II::MO_TLSGD);
6610 }
6611
6612 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6613 // "local exec" model.
6614 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6615                                    const EVT PtrVT, TLSModel::Model model,
6616                                    bool is64Bit) {
6617   DebugLoc dl = GA->getDebugLoc();
6618
6619   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6620   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6621                                                          is64Bit ? 257 : 256));
6622
6623   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6624                                       DAG.getIntPtrConstant(0),
6625                                       MachinePointerInfo(Ptr), false, false, 0);
6626
6627   unsigned char OperandFlags = 0;
6628   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6629   // initialexec.
6630   unsigned WrapperKind = X86ISD::Wrapper;
6631   if (model == TLSModel::LocalExec) {
6632     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6633   } else if (is64Bit) {
6634     assert(model == TLSModel::InitialExec);
6635     OperandFlags = X86II::MO_GOTTPOFF;
6636     WrapperKind = X86ISD::WrapperRIP;
6637   } else {
6638     assert(model == TLSModel::InitialExec);
6639     OperandFlags = X86II::MO_INDNTPOFF;
6640   }
6641
6642   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6643   // exec)
6644   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6645                                            GA->getValueType(0),
6646                                            GA->getOffset(), OperandFlags);
6647   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6648
6649   if (model == TLSModel::InitialExec)
6650     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6651                          MachinePointerInfo::getGOT(), false, false, 0);
6652
6653   // The address of the thread local variable is the add of the thread
6654   // pointer with the offset of the variable.
6655   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6656 }
6657
6658 SDValue
6659 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6660
6661   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6662   const GlobalValue *GV = GA->getGlobal();
6663
6664   if (Subtarget->isTargetELF()) {
6665     // TODO: implement the "local dynamic" model
6666     // TODO: implement the "initial exec"model for pic executables
6667
6668     // If GV is an alias then use the aliasee for determining
6669     // thread-localness.
6670     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6671       GV = GA->resolveAliasedGlobal(false);
6672
6673     TLSModel::Model model
6674       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6675
6676     switch (model) {
6677       case TLSModel::GeneralDynamic:
6678       case TLSModel::LocalDynamic: // not implemented
6679         if (Subtarget->is64Bit())
6680           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6681         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6682
6683       case TLSModel::InitialExec:
6684       case TLSModel::LocalExec:
6685         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6686                                    Subtarget->is64Bit());
6687     }
6688   } else if (Subtarget->isTargetDarwin()) {
6689     // Darwin only has one model of TLS.  Lower to that.
6690     unsigned char OpFlag = 0;
6691     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6692                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6693
6694     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6695     // global base reg.
6696     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6697                   !Subtarget->is64Bit();
6698     if (PIC32)
6699       OpFlag = X86II::MO_TLVP_PIC_BASE;
6700     else
6701       OpFlag = X86II::MO_TLVP;
6702     DebugLoc DL = Op.getDebugLoc();
6703     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6704                                                 GA->getValueType(0),
6705                                                 GA->getOffset(), OpFlag);
6706     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6707
6708     // With PIC32, the address is actually $g + Offset.
6709     if (PIC32)
6710       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6711                            DAG.getNode(X86ISD::GlobalBaseReg,
6712                                        DebugLoc(), getPointerTy()),
6713                            Offset);
6714
6715     // Lowering the machine isd will make sure everything is in the right
6716     // location.
6717     SDValue Chain = DAG.getEntryNode();
6718     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6719     SDValue Args[] = { Chain, Offset };
6720     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6721
6722     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6723     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6724     MFI->setAdjustsStack(true);
6725
6726     // And our return value (tls address) is in the standard call return value
6727     // location.
6728     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6729     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6730   }
6731
6732   assert(false &&
6733          "TLS not implemented for this target.");
6734
6735   llvm_unreachable("Unreachable");
6736   return SDValue();
6737 }
6738
6739
6740 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6741 /// take a 2 x i32 value to shift plus a shift amount.
6742 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6743   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6744   EVT VT = Op.getValueType();
6745   unsigned VTBits = VT.getSizeInBits();
6746   DebugLoc dl = Op.getDebugLoc();
6747   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6748   SDValue ShOpLo = Op.getOperand(0);
6749   SDValue ShOpHi = Op.getOperand(1);
6750   SDValue ShAmt  = Op.getOperand(2);
6751   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6752                                      DAG.getConstant(VTBits - 1, MVT::i8))
6753                        : DAG.getConstant(0, VT);
6754
6755   SDValue Tmp2, Tmp3;
6756   if (Op.getOpcode() == ISD::SHL_PARTS) {
6757     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6758     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6759   } else {
6760     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6761     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6762   }
6763
6764   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6765                                 DAG.getConstant(VTBits, MVT::i8));
6766   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6767                              AndNode, DAG.getConstant(0, MVT::i8));
6768
6769   SDValue Hi, Lo;
6770   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6771   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6772   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6773
6774   if (Op.getOpcode() == ISD::SHL_PARTS) {
6775     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6776     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6777   } else {
6778     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6779     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6780   }
6781
6782   SDValue Ops[2] = { Lo, Hi };
6783   return DAG.getMergeValues(Ops, 2, dl);
6784 }
6785
6786 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6787                                            SelectionDAG &DAG) const {
6788   EVT SrcVT = Op.getOperand(0).getValueType();
6789
6790   if (SrcVT.isVector())
6791     return SDValue();
6792
6793   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6794          "Unknown SINT_TO_FP to lower!");
6795
6796   // These are really Legal; return the operand so the caller accepts it as
6797   // Legal.
6798   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6799     return Op;
6800   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6801       Subtarget->is64Bit()) {
6802     return Op;
6803   }
6804
6805   DebugLoc dl = Op.getDebugLoc();
6806   unsigned Size = SrcVT.getSizeInBits()/8;
6807   MachineFunction &MF = DAG.getMachineFunction();
6808   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6809   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6810   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6811                                StackSlot,
6812                                MachinePointerInfo::getFixedStack(SSFI),
6813                                false, false, 0);
6814   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6815 }
6816
6817 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6818                                      SDValue StackSlot,
6819                                      SelectionDAG &DAG) const {
6820   // Build the FILD
6821   DebugLoc DL = Op.getDebugLoc();
6822   SDVTList Tys;
6823   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6824   if (useSSE)
6825     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6826   else
6827     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6828
6829   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6830
6831   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
6832   MachineMemOperand *MMO;
6833   if (FI) {
6834     int SSFI = FI->getIndex();
6835     MMO =
6836       DAG.getMachineFunction()
6837       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6838                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
6839   } else {
6840     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
6841     StackSlot = StackSlot.getOperand(1);
6842   }
6843   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6844   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6845                                            X86ISD::FILD, DL,
6846                                            Tys, Ops, array_lengthof(Ops),
6847                                            SrcVT, MMO);
6848
6849   if (useSSE) {
6850     Chain = Result.getValue(1);
6851     SDValue InFlag = Result.getValue(2);
6852
6853     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6854     // shouldn't be necessary except that RFP cannot be live across
6855     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6856     MachineFunction &MF = DAG.getMachineFunction();
6857     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6858     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6859     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6860     Tys = DAG.getVTList(MVT::Other);
6861     SDValue Ops[] = {
6862       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6863     };
6864     MachineMemOperand *MMO =
6865       DAG.getMachineFunction()
6866       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6867                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6868
6869     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6870                                     Ops, array_lengthof(Ops),
6871                                     Op.getValueType(), MMO);
6872     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6873                          MachinePointerInfo::getFixedStack(SSFI),
6874                          false, false, 0);
6875   }
6876
6877   return Result;
6878 }
6879
6880 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6881 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6882                                                SelectionDAG &DAG) const {
6883   // This algorithm is not obvious. Here it is in C code, more or less:
6884   /*
6885     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6886       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6887       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6888
6889       // Copy ints to xmm registers.
6890       __m128i xh = _mm_cvtsi32_si128( hi );
6891       __m128i xl = _mm_cvtsi32_si128( lo );
6892
6893       // Combine into low half of a single xmm register.
6894       __m128i x = _mm_unpacklo_epi32( xh, xl );
6895       __m128d d;
6896       double sd;
6897
6898       // Merge in appropriate exponents to give the integer bits the right
6899       // magnitude.
6900       x = _mm_unpacklo_epi32( x, exp );
6901
6902       // Subtract away the biases to deal with the IEEE-754 double precision
6903       // implicit 1.
6904       d = _mm_sub_pd( (__m128d) x, bias );
6905
6906       // All conversions up to here are exact. The correctly rounded result is
6907       // calculated using the current rounding mode using the following
6908       // horizontal add.
6909       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6910       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6911                                 // store doesn't really need to be here (except
6912                                 // maybe to zero the other double)
6913       return sd;
6914     }
6915   */
6916
6917   DebugLoc dl = Op.getDebugLoc();
6918   LLVMContext *Context = DAG.getContext();
6919
6920   // Build some magic constants.
6921   std::vector<Constant*> CV0;
6922   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6923   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6924   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6925   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6926   Constant *C0 = ConstantVector::get(CV0);
6927   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6928
6929   std::vector<Constant*> CV1;
6930   CV1.push_back(
6931     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6932   CV1.push_back(
6933     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6934   Constant *C1 = ConstantVector::get(CV1);
6935   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6936
6937   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6938                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6939                                         Op.getOperand(0),
6940                                         DAG.getIntPtrConstant(1)));
6941   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6942                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6943                                         Op.getOperand(0),
6944                                         DAG.getIntPtrConstant(0)));
6945   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6946   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6947                               MachinePointerInfo::getConstantPool(),
6948                               false, false, 16);
6949   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6950   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6951   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6952                               MachinePointerInfo::getConstantPool(),
6953                               false, false, 16);
6954   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6955
6956   // Add the halves; easiest way is to swap them into another reg first.
6957   int ShufMask[2] = { 1, -1 };
6958   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6959                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6960   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6961   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6962                      DAG.getIntPtrConstant(0));
6963 }
6964
6965 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6966 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6967                                                SelectionDAG &DAG) const {
6968   DebugLoc dl = Op.getDebugLoc();
6969   // FP constant to bias correct the final result.
6970   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6971                                    MVT::f64);
6972
6973   // Load the 32-bit value into an XMM register.
6974   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6975                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6976                                          Op.getOperand(0),
6977                                          DAG.getIntPtrConstant(0)));
6978
6979   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6980                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6981                      DAG.getIntPtrConstant(0));
6982
6983   // Or the load with the bias.
6984   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6985                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6986                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6987                                                    MVT::v2f64, Load)),
6988                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6989                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6990                                                    MVT::v2f64, Bias)));
6991   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6992                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6993                    DAG.getIntPtrConstant(0));
6994
6995   // Subtract the bias.
6996   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6997
6998   // Handle final rounding.
6999   EVT DestVT = Op.getValueType();
7000
7001   if (DestVT.bitsLT(MVT::f64)) {
7002     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7003                        DAG.getIntPtrConstant(0));
7004   } else if (DestVT.bitsGT(MVT::f64)) {
7005     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7006   }
7007
7008   // Handle final rounding.
7009   return Sub;
7010 }
7011
7012 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7013                                            SelectionDAG &DAG) const {
7014   SDValue N0 = Op.getOperand(0);
7015   DebugLoc dl = Op.getDebugLoc();
7016
7017   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7018   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7019   // the optimization here.
7020   if (DAG.SignBitIsZero(N0))
7021     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7022
7023   EVT SrcVT = N0.getValueType();
7024   EVT DstVT = Op.getValueType();
7025   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7026     return LowerUINT_TO_FP_i64(Op, DAG);
7027   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7028     return LowerUINT_TO_FP_i32(Op, DAG);
7029
7030   // Make a 64-bit buffer, and use it to build an FILD.
7031   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7032   if (SrcVT == MVT::i32) {
7033     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7034     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7035                                      getPointerTy(), StackSlot, WordOff);
7036     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7037                                   StackSlot, MachinePointerInfo(),
7038                                   false, false, 0);
7039     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7040                                   OffsetSlot, MachinePointerInfo(),
7041                                   false, false, 0);
7042     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7043     return Fild;
7044   }
7045
7046   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7047   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7048                                 StackSlot, MachinePointerInfo(),
7049                                false, false, 0);
7050   // For i64 source, we need to add the appropriate power of 2 if the input
7051   // was negative.  This is the same as the optimization in
7052   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7053   // we must be careful to do the computation in x87 extended precision, not
7054   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7055   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7056   MachineMemOperand *MMO =
7057     DAG.getMachineFunction()
7058     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7059                           MachineMemOperand::MOLoad, 8, 8);
7060
7061   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7062   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7063   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7064                                          MVT::i64, MMO);
7065
7066   APInt FF(32, 0x5F800000ULL);
7067
7068   // Check whether the sign bit is set.
7069   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7070                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7071                                  ISD::SETLT);
7072
7073   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7074   SDValue FudgePtr = DAG.getConstantPool(
7075                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7076                                          getPointerTy());
7077
7078   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7079   SDValue Zero = DAG.getIntPtrConstant(0);
7080   SDValue Four = DAG.getIntPtrConstant(4);
7081   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7082                                Zero, Four);
7083   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7084
7085   // Load the value out, extending it from f32 to f80.
7086   // FIXME: Avoid the extend by constructing the right constant pool?
7087   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7088                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7089                                  MVT::f32, false, false, 4);
7090   // Extend everything to 80 bits to force it to be done on x87.
7091   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7092   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7093 }
7094
7095 std::pair<SDValue,SDValue> X86TargetLowering::
7096 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7097   DebugLoc DL = Op.getDebugLoc();
7098
7099   EVT DstTy = Op.getValueType();
7100
7101   if (!IsSigned) {
7102     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7103     DstTy = MVT::i64;
7104   }
7105
7106   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7107          DstTy.getSimpleVT() >= MVT::i16 &&
7108          "Unknown FP_TO_SINT to lower!");
7109
7110   // These are really Legal.
7111   if (DstTy == MVT::i32 &&
7112       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7113     return std::make_pair(SDValue(), SDValue());
7114   if (Subtarget->is64Bit() &&
7115       DstTy == MVT::i64 &&
7116       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7117     return std::make_pair(SDValue(), SDValue());
7118
7119   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7120   // stack slot.
7121   MachineFunction &MF = DAG.getMachineFunction();
7122   unsigned MemSize = DstTy.getSizeInBits()/8;
7123   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7124   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7125
7126
7127
7128   unsigned Opc;
7129   switch (DstTy.getSimpleVT().SimpleTy) {
7130   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7131   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7132   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7133   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7134   }
7135
7136   SDValue Chain = DAG.getEntryNode();
7137   SDValue Value = Op.getOperand(0);
7138   EVT TheVT = Op.getOperand(0).getValueType();
7139   if (isScalarFPTypeInSSEReg(TheVT)) {
7140     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7141     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7142                          MachinePointerInfo::getFixedStack(SSFI),
7143                          false, false, 0);
7144     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7145     SDValue Ops[] = {
7146       Chain, StackSlot, DAG.getValueType(TheVT)
7147     };
7148
7149     MachineMemOperand *MMO =
7150       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7151                               MachineMemOperand::MOLoad, MemSize, MemSize);
7152     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7153                                     DstTy, MMO);
7154     Chain = Value.getValue(1);
7155     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7156     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7157   }
7158
7159   MachineMemOperand *MMO =
7160     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7161                             MachineMemOperand::MOStore, MemSize, MemSize);
7162
7163   // Build the FP_TO_INT*_IN_MEM
7164   SDValue Ops[] = { Chain, Value, StackSlot };
7165   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7166                                          Ops, 3, DstTy, MMO);
7167
7168   return std::make_pair(FIST, StackSlot);
7169 }
7170
7171 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7172                                            SelectionDAG &DAG) const {
7173   if (Op.getValueType().isVector())
7174     return SDValue();
7175
7176   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7177   SDValue FIST = Vals.first, StackSlot = Vals.second;
7178   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7179   if (FIST.getNode() == 0) return Op;
7180
7181   // Load the result.
7182   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7183                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7184 }
7185
7186 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7187                                            SelectionDAG &DAG) const {
7188   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7189   SDValue FIST = Vals.first, StackSlot = Vals.second;
7190   assert(FIST.getNode() && "Unexpected failure");
7191
7192   // Load the result.
7193   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7194                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7195 }
7196
7197 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7198                                      SelectionDAG &DAG) const {
7199   LLVMContext *Context = DAG.getContext();
7200   DebugLoc dl = Op.getDebugLoc();
7201   EVT VT = Op.getValueType();
7202   EVT EltVT = VT;
7203   if (VT.isVector())
7204     EltVT = VT.getVectorElementType();
7205   std::vector<Constant*> CV;
7206   if (EltVT == MVT::f64) {
7207     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7208     CV.push_back(C);
7209     CV.push_back(C);
7210   } else {
7211     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7212     CV.push_back(C);
7213     CV.push_back(C);
7214     CV.push_back(C);
7215     CV.push_back(C);
7216   }
7217   Constant *C = ConstantVector::get(CV);
7218   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7219   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7220                              MachinePointerInfo::getConstantPool(),
7221                              false, false, 16);
7222   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7223 }
7224
7225 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7226   LLVMContext *Context = DAG.getContext();
7227   DebugLoc dl = Op.getDebugLoc();
7228   EVT VT = Op.getValueType();
7229   EVT EltVT = VT;
7230   if (VT.isVector())
7231     EltVT = VT.getVectorElementType();
7232   std::vector<Constant*> CV;
7233   if (EltVT == MVT::f64) {
7234     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7235     CV.push_back(C);
7236     CV.push_back(C);
7237   } else {
7238     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7239     CV.push_back(C);
7240     CV.push_back(C);
7241     CV.push_back(C);
7242     CV.push_back(C);
7243   }
7244   Constant *C = ConstantVector::get(CV);
7245   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7246   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7247                              MachinePointerInfo::getConstantPool(),
7248                              false, false, 16);
7249   if (VT.isVector()) {
7250     return DAG.getNode(ISD::BITCAST, dl, VT,
7251                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7252                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7253                                 Op.getOperand(0)),
7254                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7255   } else {
7256     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7257   }
7258 }
7259
7260 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7261   LLVMContext *Context = DAG.getContext();
7262   SDValue Op0 = Op.getOperand(0);
7263   SDValue Op1 = Op.getOperand(1);
7264   DebugLoc dl = Op.getDebugLoc();
7265   EVT VT = Op.getValueType();
7266   EVT SrcVT = Op1.getValueType();
7267
7268   // If second operand is smaller, extend it first.
7269   if (SrcVT.bitsLT(VT)) {
7270     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7271     SrcVT = VT;
7272   }
7273   // And if it is bigger, shrink it first.
7274   if (SrcVT.bitsGT(VT)) {
7275     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7276     SrcVT = VT;
7277   }
7278
7279   // At this point the operands and the result should have the same
7280   // type, and that won't be f80 since that is not custom lowered.
7281
7282   // First get the sign bit of second operand.
7283   std::vector<Constant*> CV;
7284   if (SrcVT == MVT::f64) {
7285     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7286     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7287   } else {
7288     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7289     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7290     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7291     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7292   }
7293   Constant *C = ConstantVector::get(CV);
7294   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7295   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7296                               MachinePointerInfo::getConstantPool(),
7297                               false, false, 16);
7298   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7299
7300   // Shift sign bit right or left if the two operands have different types.
7301   if (SrcVT.bitsGT(VT)) {
7302     // Op0 is MVT::f32, Op1 is MVT::f64.
7303     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7304     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7305                           DAG.getConstant(32, MVT::i32));
7306     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7307     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7308                           DAG.getIntPtrConstant(0));
7309   }
7310
7311   // Clear first operand sign bit.
7312   CV.clear();
7313   if (VT == MVT::f64) {
7314     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7315     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7316   } else {
7317     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7318     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7319     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7320     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7321   }
7322   C = ConstantVector::get(CV);
7323   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7324   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7325                               MachinePointerInfo::getConstantPool(),
7326                               false, false, 16);
7327   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7328
7329   // Or the value with the sign bit.
7330   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7331 }
7332
7333 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7334   SDValue N0 = Op.getOperand(0);
7335   DebugLoc dl = Op.getDebugLoc();
7336   EVT VT = Op.getValueType();
7337
7338   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7339   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7340                                   DAG.getConstant(1, VT));
7341   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7342 }
7343
7344 /// Emit nodes that will be selected as "test Op0,Op0", or something
7345 /// equivalent.
7346 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7347                                     SelectionDAG &DAG) const {
7348   DebugLoc dl = Op.getDebugLoc();
7349
7350   // CF and OF aren't always set the way we want. Determine which
7351   // of these we need.
7352   bool NeedCF = false;
7353   bool NeedOF = false;
7354   switch (X86CC) {
7355   default: break;
7356   case X86::COND_A: case X86::COND_AE:
7357   case X86::COND_B: case X86::COND_BE:
7358     NeedCF = true;
7359     break;
7360   case X86::COND_G: case X86::COND_GE:
7361   case X86::COND_L: case X86::COND_LE:
7362   case X86::COND_O: case X86::COND_NO:
7363     NeedOF = true;
7364     break;
7365   }
7366
7367   // See if we can use the EFLAGS value from the operand instead of
7368   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7369   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7370   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7371     // Emit a CMP with 0, which is the TEST pattern.
7372     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7373                        DAG.getConstant(0, Op.getValueType()));
7374
7375   unsigned Opcode = 0;
7376   unsigned NumOperands = 0;
7377   switch (Op.getNode()->getOpcode()) {
7378   case ISD::ADD:
7379     // Due to an isel shortcoming, be conservative if this add is likely to be
7380     // selected as part of a load-modify-store instruction. When the root node
7381     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7382     // uses of other nodes in the match, such as the ADD in this case. This
7383     // leads to the ADD being left around and reselected, with the result being
7384     // two adds in the output.  Alas, even if none our users are stores, that
7385     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7386     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7387     // climbing the DAG back to the root, and it doesn't seem to be worth the
7388     // effort.
7389     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7390            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7391       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7392         goto default_case;
7393
7394     if (ConstantSDNode *C =
7395         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7396       // An add of one will be selected as an INC.
7397       if (C->getAPIntValue() == 1) {
7398         Opcode = X86ISD::INC;
7399         NumOperands = 1;
7400         break;
7401       }
7402
7403       // An add of negative one (subtract of one) will be selected as a DEC.
7404       if (C->getAPIntValue().isAllOnesValue()) {
7405         Opcode = X86ISD::DEC;
7406         NumOperands = 1;
7407         break;
7408       }
7409     }
7410
7411     // Otherwise use a regular EFLAGS-setting add.
7412     Opcode = X86ISD::ADD;
7413     NumOperands = 2;
7414     break;
7415   case ISD::AND: {
7416     // If the primary and result isn't used, don't bother using X86ISD::AND,
7417     // because a TEST instruction will be better.
7418     bool NonFlagUse = false;
7419     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7420            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7421       SDNode *User = *UI;
7422       unsigned UOpNo = UI.getOperandNo();
7423       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7424         // Look pass truncate.
7425         UOpNo = User->use_begin().getOperandNo();
7426         User = *User->use_begin();
7427       }
7428
7429       if (User->getOpcode() != ISD::BRCOND &&
7430           User->getOpcode() != ISD::SETCC &&
7431           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7432         NonFlagUse = true;
7433         break;
7434       }
7435     }
7436
7437     if (!NonFlagUse)
7438       break;
7439   }
7440     // FALL THROUGH
7441   case ISD::SUB:
7442   case ISD::OR:
7443   case ISD::XOR:
7444     // Due to the ISEL shortcoming noted above, be conservative if this op is
7445     // likely to be selected as part of a load-modify-store instruction.
7446     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7447            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7448       if (UI->getOpcode() == ISD::STORE)
7449         goto default_case;
7450
7451     // Otherwise use a regular EFLAGS-setting instruction.
7452     switch (Op.getNode()->getOpcode()) {
7453     default: llvm_unreachable("unexpected operator!");
7454     case ISD::SUB: Opcode = X86ISD::SUB; break;
7455     case ISD::OR:  Opcode = X86ISD::OR;  break;
7456     case ISD::XOR: Opcode = X86ISD::XOR; break;
7457     case ISD::AND: Opcode = X86ISD::AND; break;
7458     }
7459
7460     NumOperands = 2;
7461     break;
7462   case X86ISD::ADD:
7463   case X86ISD::SUB:
7464   case X86ISD::INC:
7465   case X86ISD::DEC:
7466   case X86ISD::OR:
7467   case X86ISD::XOR:
7468   case X86ISD::AND:
7469     return SDValue(Op.getNode(), 1);
7470   default:
7471   default_case:
7472     break;
7473   }
7474
7475   if (Opcode == 0)
7476     // Emit a CMP with 0, which is the TEST pattern.
7477     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7478                        DAG.getConstant(0, Op.getValueType()));
7479
7480   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7481   SmallVector<SDValue, 4> Ops;
7482   for (unsigned i = 0; i != NumOperands; ++i)
7483     Ops.push_back(Op.getOperand(i));
7484
7485   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7486   DAG.ReplaceAllUsesWith(Op, New);
7487   return SDValue(New.getNode(), 1);
7488 }
7489
7490 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7491 /// equivalent.
7492 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7493                                    SelectionDAG &DAG) const {
7494   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7495     if (C->getAPIntValue() == 0)
7496       return EmitTest(Op0, X86CC, DAG);
7497
7498   DebugLoc dl = Op0.getDebugLoc();
7499   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7500 }
7501
7502 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7503 /// if it's possible.
7504 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7505                                      DebugLoc dl, SelectionDAG &DAG) const {
7506   SDValue Op0 = And.getOperand(0);
7507   SDValue Op1 = And.getOperand(1);
7508   if (Op0.getOpcode() == ISD::TRUNCATE)
7509     Op0 = Op0.getOperand(0);
7510   if (Op1.getOpcode() == ISD::TRUNCATE)
7511     Op1 = Op1.getOperand(0);
7512
7513   SDValue LHS, RHS;
7514   if (Op1.getOpcode() == ISD::SHL)
7515     std::swap(Op0, Op1);
7516   if (Op0.getOpcode() == ISD::SHL) {
7517     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7518       if (And00C->getZExtValue() == 1) {
7519         // If we looked past a truncate, check that it's only truncating away
7520         // known zeros.
7521         unsigned BitWidth = Op0.getValueSizeInBits();
7522         unsigned AndBitWidth = And.getValueSizeInBits();
7523         if (BitWidth > AndBitWidth) {
7524           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7525           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7526           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7527             return SDValue();
7528         }
7529         LHS = Op1;
7530         RHS = Op0.getOperand(1);
7531       }
7532   } else if (Op1.getOpcode() == ISD::Constant) {
7533     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7534     SDValue AndLHS = Op0;
7535     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7536       LHS = AndLHS.getOperand(0);
7537       RHS = AndLHS.getOperand(1);
7538     }
7539   }
7540
7541   if (LHS.getNode()) {
7542     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7543     // instruction.  Since the shift amount is in-range-or-undefined, we know
7544     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7545     // the encoding for the i16 version is larger than the i32 version.
7546     // Also promote i16 to i32 for performance / code size reason.
7547     if (LHS.getValueType() == MVT::i8 ||
7548         LHS.getValueType() == MVT::i16)
7549       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7550
7551     // If the operand types disagree, extend the shift amount to match.  Since
7552     // BT ignores high bits (like shifts) we can use anyextend.
7553     if (LHS.getValueType() != RHS.getValueType())
7554       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7555
7556     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7557     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7558     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7559                        DAG.getConstant(Cond, MVT::i8), BT);
7560   }
7561
7562   return SDValue();
7563 }
7564
7565 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7566   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7567   SDValue Op0 = Op.getOperand(0);
7568   SDValue Op1 = Op.getOperand(1);
7569   DebugLoc dl = Op.getDebugLoc();
7570   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7571
7572   // Optimize to BT if possible.
7573   // Lower (X & (1 << N)) == 0 to BT(X, N).
7574   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7575   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7576   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7577       Op1.getOpcode() == ISD::Constant &&
7578       cast<ConstantSDNode>(Op1)->isNullValue() &&
7579       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7580     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7581     if (NewSetCC.getNode())
7582       return NewSetCC;
7583   }
7584
7585   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7586   // these.
7587   if (Op1.getOpcode() == ISD::Constant &&
7588       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7589        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7590       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7591
7592     // If the input is a setcc, then reuse the input setcc or use a new one with
7593     // the inverted condition.
7594     if (Op0.getOpcode() == X86ISD::SETCC) {
7595       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7596       bool Invert = (CC == ISD::SETNE) ^
7597         cast<ConstantSDNode>(Op1)->isNullValue();
7598       if (!Invert) return Op0;
7599
7600       CCode = X86::GetOppositeBranchCondition(CCode);
7601       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7602                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7603     }
7604   }
7605
7606   bool isFP = Op1.getValueType().isFloatingPoint();
7607   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7608   if (X86CC == X86::COND_INVALID)
7609     return SDValue();
7610
7611   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7612   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7613                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7614 }
7615
7616 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7617   SDValue Cond;
7618   SDValue Op0 = Op.getOperand(0);
7619   SDValue Op1 = Op.getOperand(1);
7620   SDValue CC = Op.getOperand(2);
7621   EVT VT = Op.getValueType();
7622   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7623   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7624   DebugLoc dl = Op.getDebugLoc();
7625
7626   if (isFP) {
7627     unsigned SSECC = 8;
7628     EVT VT0 = Op0.getValueType();
7629     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7630     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7631     bool Swap = false;
7632
7633     switch (SetCCOpcode) {
7634     default: break;
7635     case ISD::SETOEQ:
7636     case ISD::SETEQ:  SSECC = 0; break;
7637     case ISD::SETOGT:
7638     case ISD::SETGT: Swap = true; // Fallthrough
7639     case ISD::SETLT:
7640     case ISD::SETOLT: SSECC = 1; break;
7641     case ISD::SETOGE:
7642     case ISD::SETGE: Swap = true; // Fallthrough
7643     case ISD::SETLE:
7644     case ISD::SETOLE: SSECC = 2; break;
7645     case ISD::SETUO:  SSECC = 3; break;
7646     case ISD::SETUNE:
7647     case ISD::SETNE:  SSECC = 4; break;
7648     case ISD::SETULE: Swap = true;
7649     case ISD::SETUGE: SSECC = 5; break;
7650     case ISD::SETULT: Swap = true;
7651     case ISD::SETUGT: SSECC = 6; break;
7652     case ISD::SETO:   SSECC = 7; break;
7653     }
7654     if (Swap)
7655       std::swap(Op0, Op1);
7656
7657     // In the two special cases we can't handle, emit two comparisons.
7658     if (SSECC == 8) {
7659       if (SetCCOpcode == ISD::SETUEQ) {
7660         SDValue UNORD, EQ;
7661         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7662         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7663         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7664       }
7665       else if (SetCCOpcode == ISD::SETONE) {
7666         SDValue ORD, NEQ;
7667         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7668         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7669         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7670       }
7671       llvm_unreachable("Illegal FP comparison");
7672     }
7673     // Handle all other FP comparisons here.
7674     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7675   }
7676
7677   // We are handling one of the integer comparisons here.  Since SSE only has
7678   // GT and EQ comparisons for integer, swapping operands and multiple
7679   // operations may be required for some comparisons.
7680   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7681   bool Swap = false, Invert = false, FlipSigns = false;
7682
7683   switch (VT.getSimpleVT().SimpleTy) {
7684   default: break;
7685   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7686   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7687   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7688   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7689   }
7690
7691   switch (SetCCOpcode) {
7692   default: break;
7693   case ISD::SETNE:  Invert = true;
7694   case ISD::SETEQ:  Opc = EQOpc; break;
7695   case ISD::SETLT:  Swap = true;
7696   case ISD::SETGT:  Opc = GTOpc; break;
7697   case ISD::SETGE:  Swap = true;
7698   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7699   case ISD::SETULT: Swap = true;
7700   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7701   case ISD::SETUGE: Swap = true;
7702   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7703   }
7704   if (Swap)
7705     std::swap(Op0, Op1);
7706
7707   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7708   // bits of the inputs before performing those operations.
7709   if (FlipSigns) {
7710     EVT EltVT = VT.getVectorElementType();
7711     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7712                                       EltVT);
7713     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7714     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7715                                     SignBits.size());
7716     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7717     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7718   }
7719
7720   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7721
7722   // If the logical-not of the result is required, perform that now.
7723   if (Invert)
7724     Result = DAG.getNOT(dl, Result, VT);
7725
7726   return Result;
7727 }
7728
7729 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7730 static bool isX86LogicalCmp(SDValue Op) {
7731   unsigned Opc = Op.getNode()->getOpcode();
7732   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7733     return true;
7734   if (Op.getResNo() == 1 &&
7735       (Opc == X86ISD::ADD ||
7736        Opc == X86ISD::SUB ||
7737        Opc == X86ISD::ADC ||
7738        Opc == X86ISD::SBB ||
7739        Opc == X86ISD::SMUL ||
7740        Opc == X86ISD::UMUL ||
7741        Opc == X86ISD::INC ||
7742        Opc == X86ISD::DEC ||
7743        Opc == X86ISD::OR ||
7744        Opc == X86ISD::XOR ||
7745        Opc == X86ISD::AND))
7746     return true;
7747
7748   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7749     return true;
7750
7751   return false;
7752 }
7753
7754 static bool isZero(SDValue V) {
7755   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7756   return C && C->isNullValue();
7757 }
7758
7759 static bool isAllOnes(SDValue V) {
7760   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7761   return C && C->isAllOnesValue();
7762 }
7763
7764 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7765   bool addTest = true;
7766   SDValue Cond  = Op.getOperand(0);
7767   SDValue Op1 = Op.getOperand(1);
7768   SDValue Op2 = Op.getOperand(2);
7769   DebugLoc DL = Op.getDebugLoc();
7770   SDValue CC;
7771
7772   if (Cond.getOpcode() == ISD::SETCC) {
7773     SDValue NewCond = LowerSETCC(Cond, DAG);
7774     if (NewCond.getNode())
7775       Cond = NewCond;
7776   }
7777
7778   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7779   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7780   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7781   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7782   if (Cond.getOpcode() == X86ISD::SETCC &&
7783       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7784       isZero(Cond.getOperand(1).getOperand(1))) {
7785     SDValue Cmp = Cond.getOperand(1);
7786
7787     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7788
7789     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7790         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7791       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7792
7793       SDValue CmpOp0 = Cmp.getOperand(0);
7794       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7795                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7796
7797       SDValue Res =   // Res = 0 or -1.
7798         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7799                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7800
7801       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7802         Res = DAG.getNOT(DL, Res, Res.getValueType());
7803
7804       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7805       if (N2C == 0 || !N2C->isNullValue())
7806         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7807       return Res;
7808     }
7809   }
7810
7811   // Look past (and (setcc_carry (cmp ...)), 1).
7812   if (Cond.getOpcode() == ISD::AND &&
7813       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7814     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7815     if (C && C->getAPIntValue() == 1)
7816       Cond = Cond.getOperand(0);
7817   }
7818
7819   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7820   // setting operand in place of the X86ISD::SETCC.
7821   if (Cond.getOpcode() == X86ISD::SETCC ||
7822       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7823     CC = Cond.getOperand(0);
7824
7825     SDValue Cmp = Cond.getOperand(1);
7826     unsigned Opc = Cmp.getOpcode();
7827     EVT VT = Op.getValueType();
7828
7829     bool IllegalFPCMov = false;
7830     if (VT.isFloatingPoint() && !VT.isVector() &&
7831         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7832       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7833
7834     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7835         Opc == X86ISD::BT) { // FIXME
7836       Cond = Cmp;
7837       addTest = false;
7838     }
7839   }
7840
7841   if (addTest) {
7842     // Look pass the truncate.
7843     if (Cond.getOpcode() == ISD::TRUNCATE)
7844       Cond = Cond.getOperand(0);
7845
7846     // We know the result of AND is compared against zero. Try to match
7847     // it to BT.
7848     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7849       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7850       if (NewSetCC.getNode()) {
7851         CC = NewSetCC.getOperand(0);
7852         Cond = NewSetCC.getOperand(1);
7853         addTest = false;
7854       }
7855     }
7856   }
7857
7858   if (addTest) {
7859     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7860     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7861   }
7862
7863   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7864   // a <  b ?  0 : -1 -> RES = setcc_carry
7865   // a >= b ? -1 :  0 -> RES = setcc_carry
7866   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7867   if (Cond.getOpcode() == X86ISD::CMP) {
7868     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7869
7870     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7871         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7872       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7873                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7874       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7875         return DAG.getNOT(DL, Res, Res.getValueType());
7876       return Res;
7877     }
7878   }
7879
7880   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7881   // condition is true.
7882   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7883   SDValue Ops[] = { Op2, Op1, CC, Cond };
7884   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7885 }
7886
7887 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7888 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7889 // from the AND / OR.
7890 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7891   Opc = Op.getOpcode();
7892   if (Opc != ISD::OR && Opc != ISD::AND)
7893     return false;
7894   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7895           Op.getOperand(0).hasOneUse() &&
7896           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7897           Op.getOperand(1).hasOneUse());
7898 }
7899
7900 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7901 // 1 and that the SETCC node has a single use.
7902 static bool isXor1OfSetCC(SDValue Op) {
7903   if (Op.getOpcode() != ISD::XOR)
7904     return false;
7905   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7906   if (N1C && N1C->getAPIntValue() == 1) {
7907     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7908       Op.getOperand(0).hasOneUse();
7909   }
7910   return false;
7911 }
7912
7913 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7914   bool addTest = true;
7915   SDValue Chain = Op.getOperand(0);
7916   SDValue Cond  = Op.getOperand(1);
7917   SDValue Dest  = Op.getOperand(2);
7918   DebugLoc dl = Op.getDebugLoc();
7919   SDValue CC;
7920
7921   if (Cond.getOpcode() == ISD::SETCC) {
7922     SDValue NewCond = LowerSETCC(Cond, DAG);
7923     if (NewCond.getNode())
7924       Cond = NewCond;
7925   }
7926 #if 0
7927   // FIXME: LowerXALUO doesn't handle these!!
7928   else if (Cond.getOpcode() == X86ISD::ADD  ||
7929            Cond.getOpcode() == X86ISD::SUB  ||
7930            Cond.getOpcode() == X86ISD::SMUL ||
7931            Cond.getOpcode() == X86ISD::UMUL)
7932     Cond = LowerXALUO(Cond, DAG);
7933 #endif
7934
7935   // Look pass (and (setcc_carry (cmp ...)), 1).
7936   if (Cond.getOpcode() == ISD::AND &&
7937       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7938     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7939     if (C && C->getAPIntValue() == 1)
7940       Cond = Cond.getOperand(0);
7941   }
7942
7943   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7944   // setting operand in place of the X86ISD::SETCC.
7945   if (Cond.getOpcode() == X86ISD::SETCC ||
7946       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7947     CC = Cond.getOperand(0);
7948
7949     SDValue Cmp = Cond.getOperand(1);
7950     unsigned Opc = Cmp.getOpcode();
7951     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7952     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7953       Cond = Cmp;
7954       addTest = false;
7955     } else {
7956       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7957       default: break;
7958       case X86::COND_O:
7959       case X86::COND_B:
7960         // These can only come from an arithmetic instruction with overflow,
7961         // e.g. SADDO, UADDO.
7962         Cond = Cond.getNode()->getOperand(1);
7963         addTest = false;
7964         break;
7965       }
7966     }
7967   } else {
7968     unsigned CondOpc;
7969     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7970       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7971       if (CondOpc == ISD::OR) {
7972         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7973         // two branches instead of an explicit OR instruction with a
7974         // separate test.
7975         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7976             isX86LogicalCmp(Cmp)) {
7977           CC = Cond.getOperand(0).getOperand(0);
7978           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7979                               Chain, Dest, CC, Cmp);
7980           CC = Cond.getOperand(1).getOperand(0);
7981           Cond = Cmp;
7982           addTest = false;
7983         }
7984       } else { // ISD::AND
7985         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7986         // two branches instead of an explicit AND instruction with a
7987         // separate test. However, we only do this if this block doesn't
7988         // have a fall-through edge, because this requires an explicit
7989         // jmp when the condition is false.
7990         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7991             isX86LogicalCmp(Cmp) &&
7992             Op.getNode()->hasOneUse()) {
7993           X86::CondCode CCode =
7994             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7995           CCode = X86::GetOppositeBranchCondition(CCode);
7996           CC = DAG.getConstant(CCode, MVT::i8);
7997           SDNode *User = *Op.getNode()->use_begin();
7998           // Look for an unconditional branch following this conditional branch.
7999           // We need this because we need to reverse the successors in order
8000           // to implement FCMP_OEQ.
8001           if (User->getOpcode() == ISD::BR) {
8002             SDValue FalseBB = User->getOperand(1);
8003             SDNode *NewBR =
8004               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8005             assert(NewBR == User);
8006             (void)NewBR;
8007             Dest = FalseBB;
8008
8009             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8010                                 Chain, Dest, CC, Cmp);
8011             X86::CondCode CCode =
8012               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8013             CCode = X86::GetOppositeBranchCondition(CCode);
8014             CC = DAG.getConstant(CCode, MVT::i8);
8015             Cond = Cmp;
8016             addTest = false;
8017           }
8018         }
8019       }
8020     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8021       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8022       // It should be transformed during dag combiner except when the condition
8023       // is set by a arithmetics with overflow node.
8024       X86::CondCode CCode =
8025         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8026       CCode = X86::GetOppositeBranchCondition(CCode);
8027       CC = DAG.getConstant(CCode, MVT::i8);
8028       Cond = Cond.getOperand(0).getOperand(1);
8029       addTest = false;
8030     }
8031   }
8032
8033   if (addTest) {
8034     // Look pass the truncate.
8035     if (Cond.getOpcode() == ISD::TRUNCATE)
8036       Cond = Cond.getOperand(0);
8037
8038     // We know the result of AND is compared against zero. Try to match
8039     // it to BT.
8040     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8041       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8042       if (NewSetCC.getNode()) {
8043         CC = NewSetCC.getOperand(0);
8044         Cond = NewSetCC.getOperand(1);
8045         addTest = false;
8046       }
8047     }
8048   }
8049
8050   if (addTest) {
8051     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8052     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8053   }
8054   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8055                      Chain, Dest, CC, Cond);
8056 }
8057
8058
8059 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8060 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8061 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8062 // that the guard pages used by the OS virtual memory manager are allocated in
8063 // correct sequence.
8064 SDValue
8065 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8066                                            SelectionDAG &DAG) const {
8067   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8068          "This should be used only on Windows targets");
8069   assert(!Subtarget->isTargetEnvMacho());
8070   DebugLoc dl = Op.getDebugLoc();
8071
8072   // Get the inputs.
8073   SDValue Chain = Op.getOperand(0);
8074   SDValue Size  = Op.getOperand(1);
8075   // FIXME: Ensure alignment here
8076
8077   SDValue Flag;
8078
8079   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8080   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8081
8082   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8083   Flag = Chain.getValue(1);
8084
8085   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8086
8087   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8088   Flag = Chain.getValue(1);
8089
8090   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8091
8092   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8093   return DAG.getMergeValues(Ops1, 2, dl);
8094 }
8095
8096 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8097   MachineFunction &MF = DAG.getMachineFunction();
8098   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8099
8100   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8101   DebugLoc DL = Op.getDebugLoc();
8102
8103   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8104     // vastart just stores the address of the VarArgsFrameIndex slot into the
8105     // memory location argument.
8106     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8107                                    getPointerTy());
8108     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8109                         MachinePointerInfo(SV), false, false, 0);
8110   }
8111
8112   // __va_list_tag:
8113   //   gp_offset         (0 - 6 * 8)
8114   //   fp_offset         (48 - 48 + 8 * 16)
8115   //   overflow_arg_area (point to parameters coming in memory).
8116   //   reg_save_area
8117   SmallVector<SDValue, 8> MemOps;
8118   SDValue FIN = Op.getOperand(1);
8119   // Store gp_offset
8120   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8121                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8122                                                MVT::i32),
8123                                FIN, MachinePointerInfo(SV), false, false, 0);
8124   MemOps.push_back(Store);
8125
8126   // Store fp_offset
8127   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8128                     FIN, DAG.getIntPtrConstant(4));
8129   Store = DAG.getStore(Op.getOperand(0), DL,
8130                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8131                                        MVT::i32),
8132                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8133   MemOps.push_back(Store);
8134
8135   // Store ptr to overflow_arg_area
8136   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8137                     FIN, DAG.getIntPtrConstant(4));
8138   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8139                                     getPointerTy());
8140   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8141                        MachinePointerInfo(SV, 8),
8142                        false, false, 0);
8143   MemOps.push_back(Store);
8144
8145   // Store ptr to reg_save_area.
8146   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8147                     FIN, DAG.getIntPtrConstant(8));
8148   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8149                                     getPointerTy());
8150   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8151                        MachinePointerInfo(SV, 16), false, false, 0);
8152   MemOps.push_back(Store);
8153   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8154                      &MemOps[0], MemOps.size());
8155 }
8156
8157 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8158   assert(Subtarget->is64Bit() &&
8159          "LowerVAARG only handles 64-bit va_arg!");
8160   assert((Subtarget->isTargetLinux() ||
8161           Subtarget->isTargetDarwin()) &&
8162           "Unhandled target in LowerVAARG");
8163   assert(Op.getNode()->getNumOperands() == 4);
8164   SDValue Chain = Op.getOperand(0);
8165   SDValue SrcPtr = Op.getOperand(1);
8166   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8167   unsigned Align = Op.getConstantOperandVal(3);
8168   DebugLoc dl = Op.getDebugLoc();
8169
8170   EVT ArgVT = Op.getNode()->getValueType(0);
8171   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8172   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8173   uint8_t ArgMode;
8174
8175   // Decide which area this value should be read from.
8176   // TODO: Implement the AMD64 ABI in its entirety. This simple
8177   // selection mechanism works only for the basic types.
8178   if (ArgVT == MVT::f80) {
8179     llvm_unreachable("va_arg for f80 not yet implemented");
8180   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8181     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8182   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8183     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8184   } else {
8185     llvm_unreachable("Unhandled argument type in LowerVAARG");
8186   }
8187
8188   if (ArgMode == 2) {
8189     // Sanity Check: Make sure using fp_offset makes sense.
8190     assert(!UseSoftFloat &&
8191            !(DAG.getMachineFunction()
8192                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8193            Subtarget->hasXMM());
8194   }
8195
8196   // Insert VAARG_64 node into the DAG
8197   // VAARG_64 returns two values: Variable Argument Address, Chain
8198   SmallVector<SDValue, 11> InstOps;
8199   InstOps.push_back(Chain);
8200   InstOps.push_back(SrcPtr);
8201   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8202   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8203   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8204   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8205   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8206                                           VTs, &InstOps[0], InstOps.size(),
8207                                           MVT::i64,
8208                                           MachinePointerInfo(SV),
8209                                           /*Align=*/0,
8210                                           /*Volatile=*/false,
8211                                           /*ReadMem=*/true,
8212                                           /*WriteMem=*/true);
8213   Chain = VAARG.getValue(1);
8214
8215   // Load the next argument and return it
8216   return DAG.getLoad(ArgVT, dl,
8217                      Chain,
8218                      VAARG,
8219                      MachinePointerInfo(),
8220                      false, false, 0);
8221 }
8222
8223 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8224   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8225   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8226   SDValue Chain = Op.getOperand(0);
8227   SDValue DstPtr = Op.getOperand(1);
8228   SDValue SrcPtr = Op.getOperand(2);
8229   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8230   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8231   DebugLoc DL = Op.getDebugLoc();
8232
8233   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8234                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8235                        false,
8236                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8237 }
8238
8239 SDValue
8240 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8241   DebugLoc dl = Op.getDebugLoc();
8242   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8243   switch (IntNo) {
8244   default: return SDValue();    // Don't custom lower most intrinsics.
8245   // Comparison intrinsics.
8246   case Intrinsic::x86_sse_comieq_ss:
8247   case Intrinsic::x86_sse_comilt_ss:
8248   case Intrinsic::x86_sse_comile_ss:
8249   case Intrinsic::x86_sse_comigt_ss:
8250   case Intrinsic::x86_sse_comige_ss:
8251   case Intrinsic::x86_sse_comineq_ss:
8252   case Intrinsic::x86_sse_ucomieq_ss:
8253   case Intrinsic::x86_sse_ucomilt_ss:
8254   case Intrinsic::x86_sse_ucomile_ss:
8255   case Intrinsic::x86_sse_ucomigt_ss:
8256   case Intrinsic::x86_sse_ucomige_ss:
8257   case Intrinsic::x86_sse_ucomineq_ss:
8258   case Intrinsic::x86_sse2_comieq_sd:
8259   case Intrinsic::x86_sse2_comilt_sd:
8260   case Intrinsic::x86_sse2_comile_sd:
8261   case Intrinsic::x86_sse2_comigt_sd:
8262   case Intrinsic::x86_sse2_comige_sd:
8263   case Intrinsic::x86_sse2_comineq_sd:
8264   case Intrinsic::x86_sse2_ucomieq_sd:
8265   case Intrinsic::x86_sse2_ucomilt_sd:
8266   case Intrinsic::x86_sse2_ucomile_sd:
8267   case Intrinsic::x86_sse2_ucomigt_sd:
8268   case Intrinsic::x86_sse2_ucomige_sd:
8269   case Intrinsic::x86_sse2_ucomineq_sd: {
8270     unsigned Opc = 0;
8271     ISD::CondCode CC = ISD::SETCC_INVALID;
8272     switch (IntNo) {
8273     default: break;
8274     case Intrinsic::x86_sse_comieq_ss:
8275     case Intrinsic::x86_sse2_comieq_sd:
8276       Opc = X86ISD::COMI;
8277       CC = ISD::SETEQ;
8278       break;
8279     case Intrinsic::x86_sse_comilt_ss:
8280     case Intrinsic::x86_sse2_comilt_sd:
8281       Opc = X86ISD::COMI;
8282       CC = ISD::SETLT;
8283       break;
8284     case Intrinsic::x86_sse_comile_ss:
8285     case Intrinsic::x86_sse2_comile_sd:
8286       Opc = X86ISD::COMI;
8287       CC = ISD::SETLE;
8288       break;
8289     case Intrinsic::x86_sse_comigt_ss:
8290     case Intrinsic::x86_sse2_comigt_sd:
8291       Opc = X86ISD::COMI;
8292       CC = ISD::SETGT;
8293       break;
8294     case Intrinsic::x86_sse_comige_ss:
8295     case Intrinsic::x86_sse2_comige_sd:
8296       Opc = X86ISD::COMI;
8297       CC = ISD::SETGE;
8298       break;
8299     case Intrinsic::x86_sse_comineq_ss:
8300     case Intrinsic::x86_sse2_comineq_sd:
8301       Opc = X86ISD::COMI;
8302       CC = ISD::SETNE;
8303       break;
8304     case Intrinsic::x86_sse_ucomieq_ss:
8305     case Intrinsic::x86_sse2_ucomieq_sd:
8306       Opc = X86ISD::UCOMI;
8307       CC = ISD::SETEQ;
8308       break;
8309     case Intrinsic::x86_sse_ucomilt_ss:
8310     case Intrinsic::x86_sse2_ucomilt_sd:
8311       Opc = X86ISD::UCOMI;
8312       CC = ISD::SETLT;
8313       break;
8314     case Intrinsic::x86_sse_ucomile_ss:
8315     case Intrinsic::x86_sse2_ucomile_sd:
8316       Opc = X86ISD::UCOMI;
8317       CC = ISD::SETLE;
8318       break;
8319     case Intrinsic::x86_sse_ucomigt_ss:
8320     case Intrinsic::x86_sse2_ucomigt_sd:
8321       Opc = X86ISD::UCOMI;
8322       CC = ISD::SETGT;
8323       break;
8324     case Intrinsic::x86_sse_ucomige_ss:
8325     case Intrinsic::x86_sse2_ucomige_sd:
8326       Opc = X86ISD::UCOMI;
8327       CC = ISD::SETGE;
8328       break;
8329     case Intrinsic::x86_sse_ucomineq_ss:
8330     case Intrinsic::x86_sse2_ucomineq_sd:
8331       Opc = X86ISD::UCOMI;
8332       CC = ISD::SETNE;
8333       break;
8334     }
8335
8336     SDValue LHS = Op.getOperand(1);
8337     SDValue RHS = Op.getOperand(2);
8338     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8339     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8340     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8341     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8342                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8343     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8344   }
8345   // ptest and testp intrinsics. The intrinsic these come from are designed to
8346   // return an integer value, not just an instruction so lower it to the ptest
8347   // or testp pattern and a setcc for the result.
8348   case Intrinsic::x86_sse41_ptestz:
8349   case Intrinsic::x86_sse41_ptestc:
8350   case Intrinsic::x86_sse41_ptestnzc:
8351   case Intrinsic::x86_avx_ptestz_256:
8352   case Intrinsic::x86_avx_ptestc_256:
8353   case Intrinsic::x86_avx_ptestnzc_256:
8354   case Intrinsic::x86_avx_vtestz_ps:
8355   case Intrinsic::x86_avx_vtestc_ps:
8356   case Intrinsic::x86_avx_vtestnzc_ps:
8357   case Intrinsic::x86_avx_vtestz_pd:
8358   case Intrinsic::x86_avx_vtestc_pd:
8359   case Intrinsic::x86_avx_vtestnzc_pd:
8360   case Intrinsic::x86_avx_vtestz_ps_256:
8361   case Intrinsic::x86_avx_vtestc_ps_256:
8362   case Intrinsic::x86_avx_vtestnzc_ps_256:
8363   case Intrinsic::x86_avx_vtestz_pd_256:
8364   case Intrinsic::x86_avx_vtestc_pd_256:
8365   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8366     bool IsTestPacked = false;
8367     unsigned X86CC = 0;
8368     switch (IntNo) {
8369     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8370     case Intrinsic::x86_avx_vtestz_ps:
8371     case Intrinsic::x86_avx_vtestz_pd:
8372     case Intrinsic::x86_avx_vtestz_ps_256:
8373     case Intrinsic::x86_avx_vtestz_pd_256:
8374       IsTestPacked = true; // Fallthrough
8375     case Intrinsic::x86_sse41_ptestz:
8376     case Intrinsic::x86_avx_ptestz_256:
8377       // ZF = 1
8378       X86CC = X86::COND_E;
8379       break;
8380     case Intrinsic::x86_avx_vtestc_ps:
8381     case Intrinsic::x86_avx_vtestc_pd:
8382     case Intrinsic::x86_avx_vtestc_ps_256:
8383     case Intrinsic::x86_avx_vtestc_pd_256:
8384       IsTestPacked = true; // Fallthrough
8385     case Intrinsic::x86_sse41_ptestc:
8386     case Intrinsic::x86_avx_ptestc_256:
8387       // CF = 1
8388       X86CC = X86::COND_B;
8389       break;
8390     case Intrinsic::x86_avx_vtestnzc_ps:
8391     case Intrinsic::x86_avx_vtestnzc_pd:
8392     case Intrinsic::x86_avx_vtestnzc_ps_256:
8393     case Intrinsic::x86_avx_vtestnzc_pd_256:
8394       IsTestPacked = true; // Fallthrough
8395     case Intrinsic::x86_sse41_ptestnzc:
8396     case Intrinsic::x86_avx_ptestnzc_256:
8397       // ZF and CF = 0
8398       X86CC = X86::COND_A;
8399       break;
8400     }
8401
8402     SDValue LHS = Op.getOperand(1);
8403     SDValue RHS = Op.getOperand(2);
8404     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8405     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8406     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8407     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8408     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8409   }
8410
8411   // Fix vector shift instructions where the last operand is a non-immediate
8412   // i32 value.
8413   case Intrinsic::x86_sse2_pslli_w:
8414   case Intrinsic::x86_sse2_pslli_d:
8415   case Intrinsic::x86_sse2_pslli_q:
8416   case Intrinsic::x86_sse2_psrli_w:
8417   case Intrinsic::x86_sse2_psrli_d:
8418   case Intrinsic::x86_sse2_psrli_q:
8419   case Intrinsic::x86_sse2_psrai_w:
8420   case Intrinsic::x86_sse2_psrai_d:
8421   case Intrinsic::x86_mmx_pslli_w:
8422   case Intrinsic::x86_mmx_pslli_d:
8423   case Intrinsic::x86_mmx_pslli_q:
8424   case Intrinsic::x86_mmx_psrli_w:
8425   case Intrinsic::x86_mmx_psrli_d:
8426   case Intrinsic::x86_mmx_psrli_q:
8427   case Intrinsic::x86_mmx_psrai_w:
8428   case Intrinsic::x86_mmx_psrai_d: {
8429     SDValue ShAmt = Op.getOperand(2);
8430     if (isa<ConstantSDNode>(ShAmt))
8431       return SDValue();
8432
8433     unsigned NewIntNo = 0;
8434     EVT ShAmtVT = MVT::v4i32;
8435     switch (IntNo) {
8436     case Intrinsic::x86_sse2_pslli_w:
8437       NewIntNo = Intrinsic::x86_sse2_psll_w;
8438       break;
8439     case Intrinsic::x86_sse2_pslli_d:
8440       NewIntNo = Intrinsic::x86_sse2_psll_d;
8441       break;
8442     case Intrinsic::x86_sse2_pslli_q:
8443       NewIntNo = Intrinsic::x86_sse2_psll_q;
8444       break;
8445     case Intrinsic::x86_sse2_psrli_w:
8446       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8447       break;
8448     case Intrinsic::x86_sse2_psrli_d:
8449       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8450       break;
8451     case Intrinsic::x86_sse2_psrli_q:
8452       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8453       break;
8454     case Intrinsic::x86_sse2_psrai_w:
8455       NewIntNo = Intrinsic::x86_sse2_psra_w;
8456       break;
8457     case Intrinsic::x86_sse2_psrai_d:
8458       NewIntNo = Intrinsic::x86_sse2_psra_d;
8459       break;
8460     default: {
8461       ShAmtVT = MVT::v2i32;
8462       switch (IntNo) {
8463       case Intrinsic::x86_mmx_pslli_w:
8464         NewIntNo = Intrinsic::x86_mmx_psll_w;
8465         break;
8466       case Intrinsic::x86_mmx_pslli_d:
8467         NewIntNo = Intrinsic::x86_mmx_psll_d;
8468         break;
8469       case Intrinsic::x86_mmx_pslli_q:
8470         NewIntNo = Intrinsic::x86_mmx_psll_q;
8471         break;
8472       case Intrinsic::x86_mmx_psrli_w:
8473         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8474         break;
8475       case Intrinsic::x86_mmx_psrli_d:
8476         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8477         break;
8478       case Intrinsic::x86_mmx_psrli_q:
8479         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8480         break;
8481       case Intrinsic::x86_mmx_psrai_w:
8482         NewIntNo = Intrinsic::x86_mmx_psra_w;
8483         break;
8484       case Intrinsic::x86_mmx_psrai_d:
8485         NewIntNo = Intrinsic::x86_mmx_psra_d;
8486         break;
8487       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8488       }
8489       break;
8490     }
8491     }
8492
8493     // The vector shift intrinsics with scalars uses 32b shift amounts but
8494     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8495     // to be zero.
8496     SDValue ShOps[4];
8497     ShOps[0] = ShAmt;
8498     ShOps[1] = DAG.getConstant(0, MVT::i32);
8499     if (ShAmtVT == MVT::v4i32) {
8500       ShOps[2] = DAG.getUNDEF(MVT::i32);
8501       ShOps[3] = DAG.getUNDEF(MVT::i32);
8502       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8503     } else {
8504       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8505 // FIXME this must be lowered to get rid of the invalid type.
8506     }
8507
8508     EVT VT = Op.getValueType();
8509     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8510     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8511                        DAG.getConstant(NewIntNo, MVT::i32),
8512                        Op.getOperand(1), ShAmt);
8513   }
8514   }
8515 }
8516
8517 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8518                                            SelectionDAG &DAG) const {
8519   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8520   MFI->setReturnAddressIsTaken(true);
8521
8522   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8523   DebugLoc dl = Op.getDebugLoc();
8524
8525   if (Depth > 0) {
8526     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8527     SDValue Offset =
8528       DAG.getConstant(TD->getPointerSize(),
8529                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8530     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8531                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8532                                    FrameAddr, Offset),
8533                        MachinePointerInfo(), false, false, 0);
8534   }
8535
8536   // Just load the return address.
8537   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8538   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8539                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8540 }
8541
8542 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8543   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8544   MFI->setFrameAddressIsTaken(true);
8545
8546   EVT VT = Op.getValueType();
8547   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8548   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8549   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8550   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8551   while (Depth--)
8552     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8553                             MachinePointerInfo(),
8554                             false, false, 0);
8555   return FrameAddr;
8556 }
8557
8558 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8559                                                      SelectionDAG &DAG) const {
8560   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8561 }
8562
8563 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8564   MachineFunction &MF = DAG.getMachineFunction();
8565   SDValue Chain     = Op.getOperand(0);
8566   SDValue Offset    = Op.getOperand(1);
8567   SDValue Handler   = Op.getOperand(2);
8568   DebugLoc dl       = Op.getDebugLoc();
8569
8570   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8571                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8572                                      getPointerTy());
8573   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8574
8575   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8576                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8577   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8578   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8579                        false, false, 0);
8580   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8581   MF.getRegInfo().addLiveOut(StoreAddrReg);
8582
8583   return DAG.getNode(X86ISD::EH_RETURN, dl,
8584                      MVT::Other,
8585                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8586 }
8587
8588 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8589                                              SelectionDAG &DAG) const {
8590   SDValue Root = Op.getOperand(0);
8591   SDValue Trmp = Op.getOperand(1); // trampoline
8592   SDValue FPtr = Op.getOperand(2); // nested function
8593   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8594   DebugLoc dl  = Op.getDebugLoc();
8595
8596   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8597
8598   if (Subtarget->is64Bit()) {
8599     SDValue OutChains[6];
8600
8601     // Large code-model.
8602     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8603     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8604
8605     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
8606     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
8607
8608     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8609
8610     // Load the pointer to the nested function into R11.
8611     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8612     SDValue Addr = Trmp;
8613     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8614                                 Addr, MachinePointerInfo(TrmpAddr),
8615                                 false, false, 0);
8616
8617     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8618                        DAG.getConstant(2, MVT::i64));
8619     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8620                                 MachinePointerInfo(TrmpAddr, 2),
8621                                 false, false, 2);
8622
8623     // Load the 'nest' parameter value into R10.
8624     // R10 is specified in X86CallingConv.td
8625     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8626     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8627                        DAG.getConstant(10, MVT::i64));
8628     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8629                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8630                                 false, false, 0);
8631
8632     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8633                        DAG.getConstant(12, MVT::i64));
8634     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8635                                 MachinePointerInfo(TrmpAddr, 12),
8636                                 false, false, 2);
8637
8638     // Jump to the nested function.
8639     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8640     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8641                        DAG.getConstant(20, MVT::i64));
8642     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8643                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8644                                 false, false, 0);
8645
8646     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8647     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8648                        DAG.getConstant(22, MVT::i64));
8649     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8650                                 MachinePointerInfo(TrmpAddr, 22),
8651                                 false, false, 0);
8652
8653     SDValue Ops[] =
8654       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8655     return DAG.getMergeValues(Ops, 2, dl);
8656   } else {
8657     const Function *Func =
8658       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8659     CallingConv::ID CC = Func->getCallingConv();
8660     unsigned NestReg;
8661
8662     switch (CC) {
8663     default:
8664       llvm_unreachable("Unsupported calling convention");
8665     case CallingConv::C:
8666     case CallingConv::X86_StdCall: {
8667       // Pass 'nest' parameter in ECX.
8668       // Must be kept in sync with X86CallingConv.td
8669       NestReg = X86::ECX;
8670
8671       // Check that ECX wasn't needed by an 'inreg' parameter.
8672       FunctionType *FTy = Func->getFunctionType();
8673       const AttrListPtr &Attrs = Func->getAttributes();
8674
8675       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8676         unsigned InRegCount = 0;
8677         unsigned Idx = 1;
8678
8679         for (FunctionType::param_iterator I = FTy->param_begin(),
8680              E = FTy->param_end(); I != E; ++I, ++Idx)
8681           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8682             // FIXME: should only count parameters that are lowered to integers.
8683             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8684
8685         if (InRegCount > 2) {
8686           report_fatal_error("Nest register in use - reduce number of inreg"
8687                              " parameters!");
8688         }
8689       }
8690       break;
8691     }
8692     case CallingConv::X86_FastCall:
8693     case CallingConv::X86_ThisCall:
8694     case CallingConv::Fast:
8695       // Pass 'nest' parameter in EAX.
8696       // Must be kept in sync with X86CallingConv.td
8697       NestReg = X86::EAX;
8698       break;
8699     }
8700
8701     SDValue OutChains[4];
8702     SDValue Addr, Disp;
8703
8704     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8705                        DAG.getConstant(10, MVT::i32));
8706     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8707
8708     // This is storing the opcode for MOV32ri.
8709     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8710     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
8711     OutChains[0] = DAG.getStore(Root, dl,
8712                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8713                                 Trmp, MachinePointerInfo(TrmpAddr),
8714                                 false, false, 0);
8715
8716     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8717                        DAG.getConstant(1, MVT::i32));
8718     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8719                                 MachinePointerInfo(TrmpAddr, 1),
8720                                 false, false, 1);
8721
8722     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8723     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8724                        DAG.getConstant(5, MVT::i32));
8725     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8726                                 MachinePointerInfo(TrmpAddr, 5),
8727                                 false, false, 1);
8728
8729     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8730                        DAG.getConstant(6, MVT::i32));
8731     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8732                                 MachinePointerInfo(TrmpAddr, 6),
8733                                 false, false, 1);
8734
8735     SDValue Ops[] =
8736       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8737     return DAG.getMergeValues(Ops, 2, dl);
8738   }
8739 }
8740
8741 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8742                                             SelectionDAG &DAG) const {
8743   /*
8744    The rounding mode is in bits 11:10 of FPSR, and has the following
8745    settings:
8746      00 Round to nearest
8747      01 Round to -inf
8748      10 Round to +inf
8749      11 Round to 0
8750
8751   FLT_ROUNDS, on the other hand, expects the following:
8752     -1 Undefined
8753      0 Round to 0
8754      1 Round to nearest
8755      2 Round to +inf
8756      3 Round to -inf
8757
8758   To perform the conversion, we do:
8759     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8760   */
8761
8762   MachineFunction &MF = DAG.getMachineFunction();
8763   const TargetMachine &TM = MF.getTarget();
8764   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8765   unsigned StackAlignment = TFI.getStackAlignment();
8766   EVT VT = Op.getValueType();
8767   DebugLoc DL = Op.getDebugLoc();
8768
8769   // Save FP Control Word to stack slot
8770   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8771   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8772
8773
8774   MachineMemOperand *MMO =
8775    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8776                            MachineMemOperand::MOStore, 2, 2);
8777
8778   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8779   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8780                                           DAG.getVTList(MVT::Other),
8781                                           Ops, 2, MVT::i16, MMO);
8782
8783   // Load FP Control Word from stack slot
8784   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8785                             MachinePointerInfo(), false, false, 0);
8786
8787   // Transform as necessary
8788   SDValue CWD1 =
8789     DAG.getNode(ISD::SRL, DL, MVT::i16,
8790                 DAG.getNode(ISD::AND, DL, MVT::i16,
8791                             CWD, DAG.getConstant(0x800, MVT::i16)),
8792                 DAG.getConstant(11, MVT::i8));
8793   SDValue CWD2 =
8794     DAG.getNode(ISD::SRL, DL, MVT::i16,
8795                 DAG.getNode(ISD::AND, DL, MVT::i16,
8796                             CWD, DAG.getConstant(0x400, MVT::i16)),
8797                 DAG.getConstant(9, MVT::i8));
8798
8799   SDValue RetVal =
8800     DAG.getNode(ISD::AND, DL, MVT::i16,
8801                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8802                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8803                             DAG.getConstant(1, MVT::i16)),
8804                 DAG.getConstant(3, MVT::i16));
8805
8806
8807   return DAG.getNode((VT.getSizeInBits() < 16 ?
8808                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8809 }
8810
8811 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8812   EVT VT = Op.getValueType();
8813   EVT OpVT = VT;
8814   unsigned NumBits = VT.getSizeInBits();
8815   DebugLoc dl = Op.getDebugLoc();
8816
8817   Op = Op.getOperand(0);
8818   if (VT == MVT::i8) {
8819     // Zero extend to i32 since there is not an i8 bsr.
8820     OpVT = MVT::i32;
8821     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8822   }
8823
8824   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8825   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8826   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8827
8828   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8829   SDValue Ops[] = {
8830     Op,
8831     DAG.getConstant(NumBits+NumBits-1, OpVT),
8832     DAG.getConstant(X86::COND_E, MVT::i8),
8833     Op.getValue(1)
8834   };
8835   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8836
8837   // Finally xor with NumBits-1.
8838   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8839
8840   if (VT == MVT::i8)
8841     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8842   return Op;
8843 }
8844
8845 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8846   EVT VT = Op.getValueType();
8847   EVT OpVT = VT;
8848   unsigned NumBits = VT.getSizeInBits();
8849   DebugLoc dl = Op.getDebugLoc();
8850
8851   Op = Op.getOperand(0);
8852   if (VT == MVT::i8) {
8853     OpVT = MVT::i32;
8854     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8855   }
8856
8857   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8858   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8859   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8860
8861   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8862   SDValue Ops[] = {
8863     Op,
8864     DAG.getConstant(NumBits, OpVT),
8865     DAG.getConstant(X86::COND_E, MVT::i8),
8866     Op.getValue(1)
8867   };
8868   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8869
8870   if (VT == MVT::i8)
8871     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8872   return Op;
8873 }
8874
8875 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8876   EVT VT = Op.getValueType();
8877   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8878   DebugLoc dl = Op.getDebugLoc();
8879
8880   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8881   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8882   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8883   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8884   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8885   //
8886   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8887   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8888   //  return AloBlo + AloBhi + AhiBlo;
8889
8890   SDValue A = Op.getOperand(0);
8891   SDValue B = Op.getOperand(1);
8892
8893   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8894                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8895                        A, DAG.getConstant(32, MVT::i32));
8896   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8897                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8898                        B, DAG.getConstant(32, MVT::i32));
8899   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8900                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8901                        A, B);
8902   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8903                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8904                        A, Bhi);
8905   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8906                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8907                        Ahi, B);
8908   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8909                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8910                        AloBhi, DAG.getConstant(32, MVT::i32));
8911   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8912                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8913                        AhiBlo, DAG.getConstant(32, MVT::i32));
8914   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8915   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8916   return Res;
8917 }
8918
8919 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8920
8921   EVT VT = Op.getValueType();
8922   DebugLoc dl = Op.getDebugLoc();
8923   SDValue R = Op.getOperand(0);
8924   SDValue Amt = Op.getOperand(1);
8925
8926   LLVMContext *Context = DAG.getContext();
8927
8928   // Must have SSE2.
8929   if (!Subtarget->hasSSE2()) return SDValue();
8930
8931   // Optimize shl/srl/sra with constant shift amount.
8932   if (isSplatVector(Amt.getNode())) {
8933     SDValue SclrAmt = Amt->getOperand(0);
8934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8935       uint64_t ShiftAmt = C->getZExtValue();
8936
8937       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8938        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8939                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8940                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8941
8942       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8943        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8944                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8945                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8946
8947       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8948        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8949                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8950                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8951
8952       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8953        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8954                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8955                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8956
8957       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8958        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8959                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8960                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8961
8962       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8963        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8964                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8965                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8966
8967       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8968        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8969                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8970                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8971
8972       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8973        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8974                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8975                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8976     }
8977   }
8978
8979   // Lower SHL with variable shift amount.
8980   // Cannot lower SHL without SSE2 or later.
8981   if (!Subtarget->hasSSE2()) return SDValue();
8982
8983   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8984     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8985                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8986                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8987
8988     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8989
8990     std::vector<Constant*> CV(4, CI);
8991     Constant *C = ConstantVector::get(CV);
8992     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8993     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8994                                  MachinePointerInfo::getConstantPool(),
8995                                  false, false, 16);
8996
8997     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8998     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8999     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9000     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9001   }
9002   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9003     // a = a << 5;
9004     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9005                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9006                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9007
9008     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9009     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9010
9011     std::vector<Constant*> CVM1(16, CM1);
9012     std::vector<Constant*> CVM2(16, CM2);
9013     Constant *C = ConstantVector::get(CVM1);
9014     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9015     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9016                             MachinePointerInfo::getConstantPool(),
9017                             false, false, 16);
9018
9019     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9020     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9021     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9022                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9023                     DAG.getConstant(4, MVT::i32));
9024     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9025     // a += a
9026     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9027
9028     C = ConstantVector::get(CVM2);
9029     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9030     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9031                     MachinePointerInfo::getConstantPool(),
9032                     false, false, 16);
9033
9034     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9035     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9036     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9037                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9038                     DAG.getConstant(2, MVT::i32));
9039     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9040     // a += a
9041     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9042
9043     // return pblendv(r, r+r, a);
9044     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9045                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9046     return R;
9047   }
9048   return SDValue();
9049 }
9050
9051 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9052   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9053   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9054   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9055   // has only one use.
9056   SDNode *N = Op.getNode();
9057   SDValue LHS = N->getOperand(0);
9058   SDValue RHS = N->getOperand(1);
9059   unsigned BaseOp = 0;
9060   unsigned Cond = 0;
9061   DebugLoc DL = Op.getDebugLoc();
9062   switch (Op.getOpcode()) {
9063   default: llvm_unreachable("Unknown ovf instruction!");
9064   case ISD::SADDO:
9065     // A subtract of one will be selected as a INC. Note that INC doesn't
9066     // set CF, so we can't do this for UADDO.
9067     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9068       if (C->isOne()) {
9069         BaseOp = X86ISD::INC;
9070         Cond = X86::COND_O;
9071         break;
9072       }
9073     BaseOp = X86ISD::ADD;
9074     Cond = X86::COND_O;
9075     break;
9076   case ISD::UADDO:
9077     BaseOp = X86ISD::ADD;
9078     Cond = X86::COND_B;
9079     break;
9080   case ISD::SSUBO:
9081     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9082     // set CF, so we can't do this for USUBO.
9083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9084       if (C->isOne()) {
9085         BaseOp = X86ISD::DEC;
9086         Cond = X86::COND_O;
9087         break;
9088       }
9089     BaseOp = X86ISD::SUB;
9090     Cond = X86::COND_O;
9091     break;
9092   case ISD::USUBO:
9093     BaseOp = X86ISD::SUB;
9094     Cond = X86::COND_B;
9095     break;
9096   case ISD::SMULO:
9097     BaseOp = X86ISD::SMUL;
9098     Cond = X86::COND_O;
9099     break;
9100   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9101     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9102                                  MVT::i32);
9103     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9104
9105     SDValue SetCC =
9106       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9107                   DAG.getConstant(X86::COND_O, MVT::i32),
9108                   SDValue(Sum.getNode(), 2));
9109
9110     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9111     return Sum;
9112   }
9113   }
9114
9115   // Also sets EFLAGS.
9116   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9117   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9118
9119   SDValue SetCC =
9120     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9121                 DAG.getConstant(Cond, MVT::i32),
9122                 SDValue(Sum.getNode(), 1));
9123
9124   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9125   return Sum;
9126 }
9127
9128 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9129   DebugLoc dl = Op.getDebugLoc();
9130   SDNode* Node = Op.getNode();
9131   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9132   EVT VT = Node->getValueType(0);
9133
9134   if (Subtarget->hasSSE2() && VT.isVector()) {
9135     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9136                         ExtraVT.getScalarType().getSizeInBits();
9137     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9138
9139     unsigned SHLIntrinsicsID = 0;
9140     unsigned SRAIntrinsicsID = 0;
9141     switch (VT.getSimpleVT().SimpleTy) {
9142       default:
9143         return SDValue();
9144       case MVT::v2i64: {
9145         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9146         SRAIntrinsicsID = 0;
9147         break;
9148       }
9149       case MVT::v4i32: {
9150         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9151         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9152         break;
9153       }
9154       case MVT::v8i16: {
9155         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9156         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9157         break;
9158       }
9159     }
9160
9161     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9162                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9163                          Node->getOperand(0), ShAmt);
9164
9165     // In case of 1 bit sext, no need to shr
9166     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9167
9168     if (SRAIntrinsicsID) {
9169       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9170                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9171                          Tmp1, ShAmt);
9172     }
9173     return Tmp1;
9174   }
9175
9176   return SDValue();
9177 }
9178
9179
9180 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9181   DebugLoc dl = Op.getDebugLoc();
9182
9183   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9184   // There isn't any reason to disable it if the target processor supports it.
9185   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9186     SDValue Chain = Op.getOperand(0);
9187     SDValue Zero = DAG.getConstant(0, MVT::i32);
9188     SDValue Ops[] = {
9189       DAG.getRegister(X86::ESP, MVT::i32), // Base
9190       DAG.getTargetConstant(1, MVT::i8),   // Scale
9191       DAG.getRegister(0, MVT::i32),        // Index
9192       DAG.getTargetConstant(0, MVT::i32),  // Disp
9193       DAG.getRegister(0, MVT::i32),        // Segment.
9194       Zero,
9195       Chain
9196     };
9197     SDNode *Res =
9198       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9199                           array_lengthof(Ops));
9200     return SDValue(Res, 0);
9201   }
9202
9203   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9204   if (!isDev)
9205     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9206
9207   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9208   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9209   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9210   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9211
9212   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9213   if (!Op1 && !Op2 && !Op3 && Op4)
9214     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9215
9216   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9217   if (Op1 && !Op2 && !Op3 && !Op4)
9218     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9219
9220   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9221   //           (MFENCE)>;
9222   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9223 }
9224
9225 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9226   EVT T = Op.getValueType();
9227   DebugLoc DL = Op.getDebugLoc();
9228   unsigned Reg = 0;
9229   unsigned size = 0;
9230   switch(T.getSimpleVT().SimpleTy) {
9231   default:
9232     assert(false && "Invalid value type!");
9233   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9234   case MVT::i16: Reg = X86::AX;  size = 2; break;
9235   case MVT::i32: Reg = X86::EAX; size = 4; break;
9236   case MVT::i64:
9237     assert(Subtarget->is64Bit() && "Node not type legal!");
9238     Reg = X86::RAX; size = 8;
9239     break;
9240   }
9241   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9242                                     Op.getOperand(2), SDValue());
9243   SDValue Ops[] = { cpIn.getValue(0),
9244                     Op.getOperand(1),
9245                     Op.getOperand(3),
9246                     DAG.getTargetConstant(size, MVT::i8),
9247                     cpIn.getValue(1) };
9248   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9249   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9250   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9251                                            Ops, 5, T, MMO);
9252   SDValue cpOut =
9253     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9254   return cpOut;
9255 }
9256
9257 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9258                                                  SelectionDAG &DAG) const {
9259   assert(Subtarget->is64Bit() && "Result not type legalized?");
9260   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9261   SDValue TheChain = Op.getOperand(0);
9262   DebugLoc dl = Op.getDebugLoc();
9263   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9264   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9265   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9266                                    rax.getValue(2));
9267   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9268                             DAG.getConstant(32, MVT::i8));
9269   SDValue Ops[] = {
9270     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9271     rdx.getValue(1)
9272   };
9273   return DAG.getMergeValues(Ops, 2, dl);
9274 }
9275
9276 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9277                                             SelectionDAG &DAG) const {
9278   EVT SrcVT = Op.getOperand(0).getValueType();
9279   EVT DstVT = Op.getValueType();
9280   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9281          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9282   assert((DstVT == MVT::i64 ||
9283           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9284          "Unexpected custom BITCAST");
9285   // i64 <=> MMX conversions are Legal.
9286   if (SrcVT==MVT::i64 && DstVT.isVector())
9287     return Op;
9288   if (DstVT==MVT::i64 && SrcVT.isVector())
9289     return Op;
9290   // MMX <=> MMX conversions are Legal.
9291   if (SrcVT.isVector() && DstVT.isVector())
9292     return Op;
9293   // All other conversions need to be expanded.
9294   return SDValue();
9295 }
9296
9297 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9298   SDNode *Node = Op.getNode();
9299   DebugLoc dl = Node->getDebugLoc();
9300   EVT T = Node->getValueType(0);
9301   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9302                               DAG.getConstant(0, T), Node->getOperand(2));
9303   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9304                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9305                        Node->getOperand(0),
9306                        Node->getOperand(1), negOp,
9307                        cast<AtomicSDNode>(Node)->getSrcValue(),
9308                        cast<AtomicSDNode>(Node)->getAlignment());
9309 }
9310
9311 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9312   EVT VT = Op.getNode()->getValueType(0);
9313
9314   // Let legalize expand this if it isn't a legal type yet.
9315   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9316     return SDValue();
9317
9318   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9319
9320   unsigned Opc;
9321   bool ExtraOp = false;
9322   switch (Op.getOpcode()) {
9323   default: assert(0 && "Invalid code");
9324   case ISD::ADDC: Opc = X86ISD::ADD; break;
9325   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9326   case ISD::SUBC: Opc = X86ISD::SUB; break;
9327   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9328   }
9329
9330   if (!ExtraOp)
9331     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9332                        Op.getOperand(1));
9333   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9334                      Op.getOperand(1), Op.getOperand(2));
9335 }
9336
9337 /// LowerOperation - Provide custom lowering hooks for some operations.
9338 ///
9339 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9340   switch (Op.getOpcode()) {
9341   default: llvm_unreachable("Should not custom lower this!");
9342   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
9343   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9344   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9345   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9346   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9347   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9348   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9349   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9350   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9351   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9352   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9353   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9354   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9355   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9356   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9357   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9358   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9359   case ISD::SHL_PARTS:
9360   case ISD::SRA_PARTS:
9361   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9362   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9363   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9364   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9365   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9366   case ISD::FABS:               return LowerFABS(Op, DAG);
9367   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9368   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9369   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9370   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9371   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9372   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9373   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9374   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9375   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9376   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9377   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9378   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9379   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9380   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9381   case ISD::FRAME_TO_ARGS_OFFSET:
9382                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9383   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9384   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9385   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9386   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9387   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9388   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9389   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9390   case ISD::SRA:
9391   case ISD::SRL:
9392   case ISD::SHL:                return LowerShift(Op, DAG);
9393   case ISD::SADDO:
9394   case ISD::UADDO:
9395   case ISD::SSUBO:
9396   case ISD::USUBO:
9397   case ISD::SMULO:
9398   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9399   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9400   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9401   case ISD::ADDC:
9402   case ISD::ADDE:
9403   case ISD::SUBC:
9404   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9405   }
9406 }
9407
9408 void X86TargetLowering::
9409 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9410                         SelectionDAG &DAG, unsigned NewOp) const {
9411   EVT T = Node->getValueType(0);
9412   DebugLoc dl = Node->getDebugLoc();
9413   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9414
9415   SDValue Chain = Node->getOperand(0);
9416   SDValue In1 = Node->getOperand(1);
9417   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9418                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9419   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9420                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9421   SDValue Ops[] = { Chain, In1, In2L, In2H };
9422   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9423   SDValue Result =
9424     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9425                             cast<MemSDNode>(Node)->getMemOperand());
9426   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9427   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9428   Results.push_back(Result.getValue(2));
9429 }
9430
9431 /// ReplaceNodeResults - Replace a node with an illegal result type
9432 /// with a new node built out of custom code.
9433 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9434                                            SmallVectorImpl<SDValue>&Results,
9435                                            SelectionDAG &DAG) const {
9436   DebugLoc dl = N->getDebugLoc();
9437   switch (N->getOpcode()) {
9438   default:
9439     assert(false && "Do not know how to custom type legalize this operation!");
9440     return;
9441   case ISD::SIGN_EXTEND_INREG:
9442   case ISD::ADDC:
9443   case ISD::ADDE:
9444   case ISD::SUBC:
9445   case ISD::SUBE:
9446     // We don't want to expand or promote these.
9447     return;
9448   case ISD::FP_TO_SINT: {
9449     std::pair<SDValue,SDValue> Vals =
9450         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9451     SDValue FIST = Vals.first, StackSlot = Vals.second;
9452     if (FIST.getNode() != 0) {
9453       EVT VT = N->getValueType(0);
9454       // Return a load from the stack slot.
9455       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9456                                     MachinePointerInfo(), false, false, 0));
9457     }
9458     return;
9459   }
9460   case ISD::READCYCLECOUNTER: {
9461     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9462     SDValue TheChain = N->getOperand(0);
9463     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9464     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9465                                      rd.getValue(1));
9466     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9467                                      eax.getValue(2));
9468     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9469     SDValue Ops[] = { eax, edx };
9470     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9471     Results.push_back(edx.getValue(1));
9472     return;
9473   }
9474   case ISD::ATOMIC_CMP_SWAP: {
9475     EVT T = N->getValueType(0);
9476     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9477     SDValue cpInL, cpInH;
9478     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9479                         DAG.getConstant(0, MVT::i32));
9480     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9481                         DAG.getConstant(1, MVT::i32));
9482     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9483     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9484                              cpInL.getValue(1));
9485     SDValue swapInL, swapInH;
9486     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9487                           DAG.getConstant(0, MVT::i32));
9488     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9489                           DAG.getConstant(1, MVT::i32));
9490     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9491                                cpInH.getValue(1));
9492     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9493                                swapInL.getValue(1));
9494     SDValue Ops[] = { swapInH.getValue(0),
9495                       N->getOperand(1),
9496                       swapInH.getValue(1) };
9497     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9498     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9499     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9500                                              Ops, 3, T, MMO);
9501     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9502                                         MVT::i32, Result.getValue(1));
9503     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9504                                         MVT::i32, cpOutL.getValue(2));
9505     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9506     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9507     Results.push_back(cpOutH.getValue(1));
9508     return;
9509   }
9510   case ISD::ATOMIC_LOAD_ADD:
9511     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9512     return;
9513   case ISD::ATOMIC_LOAD_AND:
9514     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9515     return;
9516   case ISD::ATOMIC_LOAD_NAND:
9517     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9518     return;
9519   case ISD::ATOMIC_LOAD_OR:
9520     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9521     return;
9522   case ISD::ATOMIC_LOAD_SUB:
9523     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9524     return;
9525   case ISD::ATOMIC_LOAD_XOR:
9526     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9527     return;
9528   case ISD::ATOMIC_SWAP:
9529     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9530     return;
9531   }
9532 }
9533
9534 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9535   switch (Opcode) {
9536   default: return NULL;
9537   case X86ISD::BSF:                return "X86ISD::BSF";
9538   case X86ISD::BSR:                return "X86ISD::BSR";
9539   case X86ISD::SHLD:               return "X86ISD::SHLD";
9540   case X86ISD::SHRD:               return "X86ISD::SHRD";
9541   case X86ISD::FAND:               return "X86ISD::FAND";
9542   case X86ISD::FOR:                return "X86ISD::FOR";
9543   case X86ISD::FXOR:               return "X86ISD::FXOR";
9544   case X86ISD::FSRL:               return "X86ISD::FSRL";
9545   case X86ISD::FILD:               return "X86ISD::FILD";
9546   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9547   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9548   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9549   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9550   case X86ISD::FLD:                return "X86ISD::FLD";
9551   case X86ISD::FST:                return "X86ISD::FST";
9552   case X86ISD::CALL:               return "X86ISD::CALL";
9553   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9554   case X86ISD::BT:                 return "X86ISD::BT";
9555   case X86ISD::CMP:                return "X86ISD::CMP";
9556   case X86ISD::COMI:               return "X86ISD::COMI";
9557   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9558   case X86ISD::SETCC:              return "X86ISD::SETCC";
9559   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9560   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9561   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9562   case X86ISD::CMOV:               return "X86ISD::CMOV";
9563   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9564   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9565   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9566   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9567   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9568   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9569   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9570   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9571   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9572   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9573   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9574   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9575   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9576   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
9577   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9578   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9579   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9580   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9581   case X86ISD::FMAX:               return "X86ISD::FMAX";
9582   case X86ISD::FMIN:               return "X86ISD::FMIN";
9583   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9584   case X86ISD::FRCP:               return "X86ISD::FRCP";
9585   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9586   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9587   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9588   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9589   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9590   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9591   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9592   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9593   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9594   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9595   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9596   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9597   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9598   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9599   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9600   case X86ISD::VSHL:               return "X86ISD::VSHL";
9601   case X86ISD::VSRL:               return "X86ISD::VSRL";
9602   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9603   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9604   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9605   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9606   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9607   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9608   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9609   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9610   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9611   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9612   case X86ISD::ADD:                return "X86ISD::ADD";
9613   case X86ISD::SUB:                return "X86ISD::SUB";
9614   case X86ISD::ADC:                return "X86ISD::ADC";
9615   case X86ISD::SBB:                return "X86ISD::SBB";
9616   case X86ISD::SMUL:               return "X86ISD::SMUL";
9617   case X86ISD::UMUL:               return "X86ISD::UMUL";
9618   case X86ISD::INC:                return "X86ISD::INC";
9619   case X86ISD::DEC:                return "X86ISD::DEC";
9620   case X86ISD::OR:                 return "X86ISD::OR";
9621   case X86ISD::XOR:                return "X86ISD::XOR";
9622   case X86ISD::AND:                return "X86ISD::AND";
9623   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9624   case X86ISD::PTEST:              return "X86ISD::PTEST";
9625   case X86ISD::TESTP:              return "X86ISD::TESTP";
9626   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9627   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9628   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9629   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9630   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9631   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9632   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9633   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9634   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9635   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9636   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9637   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9638   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9639   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9640   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9641   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9642   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9643   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9644   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9645   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9646   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9647   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9648   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9649   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9650   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9651   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9652   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9653   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9654   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9655   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9656   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9657   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9658   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9659   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9660   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9661   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9662   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9663   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9664   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9665   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9666   }
9667 }
9668
9669 // isLegalAddressingMode - Return true if the addressing mode represented
9670 // by AM is legal for this target, for a load/store of the specified type.
9671 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9672                                               Type *Ty) const {
9673   // X86 supports extremely general addressing modes.
9674   CodeModel::Model M = getTargetMachine().getCodeModel();
9675   Reloc::Model R = getTargetMachine().getRelocationModel();
9676
9677   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9678   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9679     return false;
9680
9681   if (AM.BaseGV) {
9682     unsigned GVFlags =
9683       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9684
9685     // If a reference to this global requires an extra load, we can't fold it.
9686     if (isGlobalStubReference(GVFlags))
9687       return false;
9688
9689     // If BaseGV requires a register for the PIC base, we cannot also have a
9690     // BaseReg specified.
9691     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9692       return false;
9693
9694     // If lower 4G is not available, then we must use rip-relative addressing.
9695     if ((M != CodeModel::Small || R != Reloc::Static) &&
9696         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9697       return false;
9698   }
9699
9700   switch (AM.Scale) {
9701   case 0:
9702   case 1:
9703   case 2:
9704   case 4:
9705   case 8:
9706     // These scales always work.
9707     break;
9708   case 3:
9709   case 5:
9710   case 9:
9711     // These scales are formed with basereg+scalereg.  Only accept if there is
9712     // no basereg yet.
9713     if (AM.HasBaseReg)
9714       return false;
9715     break;
9716   default:  // Other stuff never works.
9717     return false;
9718   }
9719
9720   return true;
9721 }
9722
9723
9724 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9725   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9726     return false;
9727   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9728   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9729   if (NumBits1 <= NumBits2)
9730     return false;
9731   return true;
9732 }
9733
9734 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9735   if (!VT1.isInteger() || !VT2.isInteger())
9736     return false;
9737   unsigned NumBits1 = VT1.getSizeInBits();
9738   unsigned NumBits2 = VT2.getSizeInBits();
9739   if (NumBits1 <= NumBits2)
9740     return false;
9741   return true;
9742 }
9743
9744 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9745   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9746   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9747 }
9748
9749 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9750   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9751   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9752 }
9753
9754 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9755   // i16 instructions are longer (0x66 prefix) and potentially slower.
9756   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9757 }
9758
9759 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9760 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9761 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9762 /// are assumed to be legal.
9763 bool
9764 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9765                                       EVT VT) const {
9766   // Very little shuffling can be done for 64-bit vectors right now.
9767   if (VT.getSizeInBits() == 64)
9768     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9769
9770   // FIXME: pshufb, blends, shifts.
9771   return (VT.getVectorNumElements() == 2 ||
9772           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9773           isMOVLMask(M, VT) ||
9774           isSHUFPMask(M, VT) ||
9775           isPSHUFDMask(M, VT) ||
9776           isPSHUFHWMask(M, VT) ||
9777           isPSHUFLWMask(M, VT) ||
9778           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9779           isUNPCKLMask(M, VT) ||
9780           isUNPCKHMask(M, VT) ||
9781           isUNPCKL_v_undef_Mask(M, VT) ||
9782           isUNPCKH_v_undef_Mask(M, VT));
9783 }
9784
9785 bool
9786 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9787                                           EVT VT) const {
9788   unsigned NumElts = VT.getVectorNumElements();
9789   // FIXME: This collection of masks seems suspect.
9790   if (NumElts == 2)
9791     return true;
9792   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9793     return (isMOVLMask(Mask, VT)  ||
9794             isCommutedMOVLMask(Mask, VT, true) ||
9795             isSHUFPMask(Mask, VT) ||
9796             isCommutedSHUFPMask(Mask, VT));
9797   }
9798   return false;
9799 }
9800
9801 //===----------------------------------------------------------------------===//
9802 //                           X86 Scheduler Hooks
9803 //===----------------------------------------------------------------------===//
9804
9805 // private utility function
9806 MachineBasicBlock *
9807 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9808                                                        MachineBasicBlock *MBB,
9809                                                        unsigned regOpc,
9810                                                        unsigned immOpc,
9811                                                        unsigned LoadOpc,
9812                                                        unsigned CXchgOpc,
9813                                                        unsigned notOpc,
9814                                                        unsigned EAXreg,
9815                                                        TargetRegisterClass *RC,
9816                                                        bool invSrc) const {
9817   // For the atomic bitwise operator, we generate
9818   //   thisMBB:
9819   //   newMBB:
9820   //     ld  t1 = [bitinstr.addr]
9821   //     op  t2 = t1, [bitinstr.val]
9822   //     mov EAX = t1
9823   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9824   //     bz  newMBB
9825   //     fallthrough -->nextMBB
9826   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9827   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9828   MachineFunction::iterator MBBIter = MBB;
9829   ++MBBIter;
9830
9831   /// First build the CFG
9832   MachineFunction *F = MBB->getParent();
9833   MachineBasicBlock *thisMBB = MBB;
9834   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9835   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9836   F->insert(MBBIter, newMBB);
9837   F->insert(MBBIter, nextMBB);
9838
9839   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9840   nextMBB->splice(nextMBB->begin(), thisMBB,
9841                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9842                   thisMBB->end());
9843   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9844
9845   // Update thisMBB to fall through to newMBB
9846   thisMBB->addSuccessor(newMBB);
9847
9848   // newMBB jumps to itself and fall through to nextMBB
9849   newMBB->addSuccessor(nextMBB);
9850   newMBB->addSuccessor(newMBB);
9851
9852   // Insert instructions into newMBB based on incoming instruction
9853   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9854          "unexpected number of operands");
9855   DebugLoc dl = bInstr->getDebugLoc();
9856   MachineOperand& destOper = bInstr->getOperand(0);
9857   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9858   int numArgs = bInstr->getNumOperands() - 1;
9859   for (int i=0; i < numArgs; ++i)
9860     argOpers[i] = &bInstr->getOperand(i+1);
9861
9862   // x86 address has 4 operands: base, index, scale, and displacement
9863   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9864   int valArgIndx = lastAddrIndx + 1;
9865
9866   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9867   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9868   for (int i=0; i <= lastAddrIndx; ++i)
9869     (*MIB).addOperand(*argOpers[i]);
9870
9871   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9872   if (invSrc) {
9873     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9874   }
9875   else
9876     tt = t1;
9877
9878   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9879   assert((argOpers[valArgIndx]->isReg() ||
9880           argOpers[valArgIndx]->isImm()) &&
9881          "invalid operand");
9882   if (argOpers[valArgIndx]->isReg())
9883     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9884   else
9885     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9886   MIB.addReg(tt);
9887   (*MIB).addOperand(*argOpers[valArgIndx]);
9888
9889   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9890   MIB.addReg(t1);
9891
9892   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9893   for (int i=0; i <= lastAddrIndx; ++i)
9894     (*MIB).addOperand(*argOpers[i]);
9895   MIB.addReg(t2);
9896   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9897   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9898                     bInstr->memoperands_end());
9899
9900   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9901   MIB.addReg(EAXreg);
9902
9903   // insert branch
9904   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9905
9906   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9907   return nextMBB;
9908 }
9909
9910 // private utility function:  64 bit atomics on 32 bit host.
9911 MachineBasicBlock *
9912 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9913                                                        MachineBasicBlock *MBB,
9914                                                        unsigned regOpcL,
9915                                                        unsigned regOpcH,
9916                                                        unsigned immOpcL,
9917                                                        unsigned immOpcH,
9918                                                        bool invSrc) const {
9919   // For the atomic bitwise operator, we generate
9920   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9921   //     ld t1,t2 = [bitinstr.addr]
9922   //   newMBB:
9923   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9924   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9925   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9926   //     mov ECX, EBX <- t5, t6
9927   //     mov EAX, EDX <- t1, t2
9928   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9929   //     mov t3, t4 <- EAX, EDX
9930   //     bz  newMBB
9931   //     result in out1, out2
9932   //     fallthrough -->nextMBB
9933
9934   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9935   const unsigned LoadOpc = X86::MOV32rm;
9936   const unsigned NotOpc = X86::NOT32r;
9937   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9938   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9939   MachineFunction::iterator MBBIter = MBB;
9940   ++MBBIter;
9941
9942   /// First build the CFG
9943   MachineFunction *F = MBB->getParent();
9944   MachineBasicBlock *thisMBB = MBB;
9945   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9946   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9947   F->insert(MBBIter, newMBB);
9948   F->insert(MBBIter, nextMBB);
9949
9950   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9951   nextMBB->splice(nextMBB->begin(), thisMBB,
9952                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9953                   thisMBB->end());
9954   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9955
9956   // Update thisMBB to fall through to newMBB
9957   thisMBB->addSuccessor(newMBB);
9958
9959   // newMBB jumps to itself and fall through to nextMBB
9960   newMBB->addSuccessor(nextMBB);
9961   newMBB->addSuccessor(newMBB);
9962
9963   DebugLoc dl = bInstr->getDebugLoc();
9964   // Insert instructions into newMBB based on incoming instruction
9965   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9966   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9967          "unexpected number of operands");
9968   MachineOperand& dest1Oper = bInstr->getOperand(0);
9969   MachineOperand& dest2Oper = bInstr->getOperand(1);
9970   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9971   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9972     argOpers[i] = &bInstr->getOperand(i+2);
9973
9974     // We use some of the operands multiple times, so conservatively just
9975     // clear any kill flags that might be present.
9976     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9977       argOpers[i]->setIsKill(false);
9978   }
9979
9980   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9981   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9982
9983   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9984   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9985   for (int i=0; i <= lastAddrIndx; ++i)
9986     (*MIB).addOperand(*argOpers[i]);
9987   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9988   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9989   // add 4 to displacement.
9990   for (int i=0; i <= lastAddrIndx-2; ++i)
9991     (*MIB).addOperand(*argOpers[i]);
9992   MachineOperand newOp3 = *(argOpers[3]);
9993   if (newOp3.isImm())
9994     newOp3.setImm(newOp3.getImm()+4);
9995   else
9996     newOp3.setOffset(newOp3.getOffset()+4);
9997   (*MIB).addOperand(newOp3);
9998   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9999
10000   // t3/4 are defined later, at the bottom of the loop
10001   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10002   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10003   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10004     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10005   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10006     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10007
10008   // The subsequent operations should be using the destination registers of
10009   //the PHI instructions.
10010   if (invSrc) {
10011     t1 = F->getRegInfo().createVirtualRegister(RC);
10012     t2 = F->getRegInfo().createVirtualRegister(RC);
10013     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10014     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10015   } else {
10016     t1 = dest1Oper.getReg();
10017     t2 = dest2Oper.getReg();
10018   }
10019
10020   int valArgIndx = lastAddrIndx + 1;
10021   assert((argOpers[valArgIndx]->isReg() ||
10022           argOpers[valArgIndx]->isImm()) &&
10023          "invalid operand");
10024   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10025   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10026   if (argOpers[valArgIndx]->isReg())
10027     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10028   else
10029     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10030   if (regOpcL != X86::MOV32rr)
10031     MIB.addReg(t1);
10032   (*MIB).addOperand(*argOpers[valArgIndx]);
10033   assert(argOpers[valArgIndx + 1]->isReg() ==
10034          argOpers[valArgIndx]->isReg());
10035   assert(argOpers[valArgIndx + 1]->isImm() ==
10036          argOpers[valArgIndx]->isImm());
10037   if (argOpers[valArgIndx + 1]->isReg())
10038     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10039   else
10040     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10041   if (regOpcH != X86::MOV32rr)
10042     MIB.addReg(t2);
10043   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10044
10045   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10046   MIB.addReg(t1);
10047   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10048   MIB.addReg(t2);
10049
10050   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10051   MIB.addReg(t5);
10052   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10053   MIB.addReg(t6);
10054
10055   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10056   for (int i=0; i <= lastAddrIndx; ++i)
10057     (*MIB).addOperand(*argOpers[i]);
10058
10059   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10060   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10061                     bInstr->memoperands_end());
10062
10063   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10064   MIB.addReg(X86::EAX);
10065   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10066   MIB.addReg(X86::EDX);
10067
10068   // insert branch
10069   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10070
10071   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10072   return nextMBB;
10073 }
10074
10075 // private utility function
10076 MachineBasicBlock *
10077 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10078                                                       MachineBasicBlock *MBB,
10079                                                       unsigned cmovOpc) const {
10080   // For the atomic min/max operator, we generate
10081   //   thisMBB:
10082   //   newMBB:
10083   //     ld t1 = [min/max.addr]
10084   //     mov t2 = [min/max.val]
10085   //     cmp  t1, t2
10086   //     cmov[cond] t2 = t1
10087   //     mov EAX = t1
10088   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10089   //     bz   newMBB
10090   //     fallthrough -->nextMBB
10091   //
10092   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10093   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10094   MachineFunction::iterator MBBIter = MBB;
10095   ++MBBIter;
10096
10097   /// First build the CFG
10098   MachineFunction *F = MBB->getParent();
10099   MachineBasicBlock *thisMBB = MBB;
10100   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10101   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10102   F->insert(MBBIter, newMBB);
10103   F->insert(MBBIter, nextMBB);
10104
10105   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10106   nextMBB->splice(nextMBB->begin(), thisMBB,
10107                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10108                   thisMBB->end());
10109   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10110
10111   // Update thisMBB to fall through to newMBB
10112   thisMBB->addSuccessor(newMBB);
10113
10114   // newMBB jumps to newMBB and fall through to nextMBB
10115   newMBB->addSuccessor(nextMBB);
10116   newMBB->addSuccessor(newMBB);
10117
10118   DebugLoc dl = mInstr->getDebugLoc();
10119   // Insert instructions into newMBB based on incoming instruction
10120   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10121          "unexpected number of operands");
10122   MachineOperand& destOper = mInstr->getOperand(0);
10123   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10124   int numArgs = mInstr->getNumOperands() - 1;
10125   for (int i=0; i < numArgs; ++i)
10126     argOpers[i] = &mInstr->getOperand(i+1);
10127
10128   // x86 address has 4 operands: base, index, scale, and displacement
10129   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10130   int valArgIndx = lastAddrIndx + 1;
10131
10132   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10133   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10134   for (int i=0; i <= lastAddrIndx; ++i)
10135     (*MIB).addOperand(*argOpers[i]);
10136
10137   // We only support register and immediate values
10138   assert((argOpers[valArgIndx]->isReg() ||
10139           argOpers[valArgIndx]->isImm()) &&
10140          "invalid operand");
10141
10142   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10143   if (argOpers[valArgIndx]->isReg())
10144     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10145   else
10146     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10147   (*MIB).addOperand(*argOpers[valArgIndx]);
10148
10149   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10150   MIB.addReg(t1);
10151
10152   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10153   MIB.addReg(t1);
10154   MIB.addReg(t2);
10155
10156   // Generate movc
10157   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10158   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10159   MIB.addReg(t2);
10160   MIB.addReg(t1);
10161
10162   // Cmp and exchange if none has modified the memory location
10163   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10164   for (int i=0; i <= lastAddrIndx; ++i)
10165     (*MIB).addOperand(*argOpers[i]);
10166   MIB.addReg(t3);
10167   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10168   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10169                     mInstr->memoperands_end());
10170
10171   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10172   MIB.addReg(X86::EAX);
10173
10174   // insert branch
10175   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10176
10177   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10178   return nextMBB;
10179 }
10180
10181 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10182 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10183 // in the .td file.
10184 MachineBasicBlock *
10185 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10186                             unsigned numArgs, bool memArg) const {
10187   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10188          "Target must have SSE4.2 or AVX features enabled");
10189
10190   DebugLoc dl = MI->getDebugLoc();
10191   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10192   unsigned Opc;
10193   if (!Subtarget->hasAVX()) {
10194     if (memArg)
10195       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10196     else
10197       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10198   } else {
10199     if (memArg)
10200       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10201     else
10202       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10203   }
10204
10205   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10206   for (unsigned i = 0; i < numArgs; ++i) {
10207     MachineOperand &Op = MI->getOperand(i+1);
10208     if (!(Op.isReg() && Op.isImplicit()))
10209       MIB.addOperand(Op);
10210   }
10211   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10212     .addReg(X86::XMM0);
10213
10214   MI->eraseFromParent();
10215   return BB;
10216 }
10217
10218 MachineBasicBlock *
10219 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10220   DebugLoc dl = MI->getDebugLoc();
10221   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10222
10223   // Address into RAX/EAX, other two args into ECX, EDX.
10224   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10225   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10226   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10227   for (int i = 0; i < X86::AddrNumOperands; ++i)
10228     MIB.addOperand(MI->getOperand(i));
10229
10230   unsigned ValOps = X86::AddrNumOperands;
10231   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10232     .addReg(MI->getOperand(ValOps).getReg());
10233   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10234     .addReg(MI->getOperand(ValOps+1).getReg());
10235
10236   // The instruction doesn't actually take any operands though.
10237   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10238
10239   MI->eraseFromParent(); // The pseudo is gone now.
10240   return BB;
10241 }
10242
10243 MachineBasicBlock *
10244 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10245   DebugLoc dl = MI->getDebugLoc();
10246   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10247
10248   // First arg in ECX, the second in EAX.
10249   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10250     .addReg(MI->getOperand(0).getReg());
10251   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10252     .addReg(MI->getOperand(1).getReg());
10253
10254   // The instruction doesn't actually take any operands though.
10255   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10256
10257   MI->eraseFromParent(); // The pseudo is gone now.
10258   return BB;
10259 }
10260
10261 MachineBasicBlock *
10262 X86TargetLowering::EmitVAARG64WithCustomInserter(
10263                    MachineInstr *MI,
10264                    MachineBasicBlock *MBB) const {
10265   // Emit va_arg instruction on X86-64.
10266
10267   // Operands to this pseudo-instruction:
10268   // 0  ) Output        : destination address (reg)
10269   // 1-5) Input         : va_list address (addr, i64mem)
10270   // 6  ) ArgSize       : Size (in bytes) of vararg type
10271   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10272   // 8  ) Align         : Alignment of type
10273   // 9  ) EFLAGS (implicit-def)
10274
10275   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10276   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10277
10278   unsigned DestReg = MI->getOperand(0).getReg();
10279   MachineOperand &Base = MI->getOperand(1);
10280   MachineOperand &Scale = MI->getOperand(2);
10281   MachineOperand &Index = MI->getOperand(3);
10282   MachineOperand &Disp = MI->getOperand(4);
10283   MachineOperand &Segment = MI->getOperand(5);
10284   unsigned ArgSize = MI->getOperand(6).getImm();
10285   unsigned ArgMode = MI->getOperand(7).getImm();
10286   unsigned Align = MI->getOperand(8).getImm();
10287
10288   // Memory Reference
10289   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10290   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10291   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10292
10293   // Machine Information
10294   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10295   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10296   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10297   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10298   DebugLoc DL = MI->getDebugLoc();
10299
10300   // struct va_list {
10301   //   i32   gp_offset
10302   //   i32   fp_offset
10303   //   i64   overflow_area (address)
10304   //   i64   reg_save_area (address)
10305   // }
10306   // sizeof(va_list) = 24
10307   // alignment(va_list) = 8
10308
10309   unsigned TotalNumIntRegs = 6;
10310   unsigned TotalNumXMMRegs = 8;
10311   bool UseGPOffset = (ArgMode == 1);
10312   bool UseFPOffset = (ArgMode == 2);
10313   unsigned MaxOffset = TotalNumIntRegs * 8 +
10314                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10315
10316   /* Align ArgSize to a multiple of 8 */
10317   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10318   bool NeedsAlign = (Align > 8);
10319
10320   MachineBasicBlock *thisMBB = MBB;
10321   MachineBasicBlock *overflowMBB;
10322   MachineBasicBlock *offsetMBB;
10323   MachineBasicBlock *endMBB;
10324
10325   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10326   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10327   unsigned OffsetReg = 0;
10328
10329   if (!UseGPOffset && !UseFPOffset) {
10330     // If we only pull from the overflow region, we don't create a branch.
10331     // We don't need to alter control flow.
10332     OffsetDestReg = 0; // unused
10333     OverflowDestReg = DestReg;
10334
10335     offsetMBB = NULL;
10336     overflowMBB = thisMBB;
10337     endMBB = thisMBB;
10338   } else {
10339     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10340     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10341     // If not, pull from overflow_area. (branch to overflowMBB)
10342     //
10343     //       thisMBB
10344     //         |     .
10345     //         |        .
10346     //     offsetMBB   overflowMBB
10347     //         |        .
10348     //         |     .
10349     //        endMBB
10350
10351     // Registers for the PHI in endMBB
10352     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10353     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10354
10355     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10356     MachineFunction *MF = MBB->getParent();
10357     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10358     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10359     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10360
10361     MachineFunction::iterator MBBIter = MBB;
10362     ++MBBIter;
10363
10364     // Insert the new basic blocks
10365     MF->insert(MBBIter, offsetMBB);
10366     MF->insert(MBBIter, overflowMBB);
10367     MF->insert(MBBIter, endMBB);
10368
10369     // Transfer the remainder of MBB and its successor edges to endMBB.
10370     endMBB->splice(endMBB->begin(), thisMBB,
10371                     llvm::next(MachineBasicBlock::iterator(MI)),
10372                     thisMBB->end());
10373     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10374
10375     // Make offsetMBB and overflowMBB successors of thisMBB
10376     thisMBB->addSuccessor(offsetMBB);
10377     thisMBB->addSuccessor(overflowMBB);
10378
10379     // endMBB is a successor of both offsetMBB and overflowMBB
10380     offsetMBB->addSuccessor(endMBB);
10381     overflowMBB->addSuccessor(endMBB);
10382
10383     // Load the offset value into a register
10384     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10385     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10386       .addOperand(Base)
10387       .addOperand(Scale)
10388       .addOperand(Index)
10389       .addDisp(Disp, UseFPOffset ? 4 : 0)
10390       .addOperand(Segment)
10391       .setMemRefs(MMOBegin, MMOEnd);
10392
10393     // Check if there is enough room left to pull this argument.
10394     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10395       .addReg(OffsetReg)
10396       .addImm(MaxOffset + 8 - ArgSizeA8);
10397
10398     // Branch to "overflowMBB" if offset >= max
10399     // Fall through to "offsetMBB" otherwise
10400     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10401       .addMBB(overflowMBB);
10402   }
10403
10404   // In offsetMBB, emit code to use the reg_save_area.
10405   if (offsetMBB) {
10406     assert(OffsetReg != 0);
10407
10408     // Read the reg_save_area address.
10409     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10410     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10411       .addOperand(Base)
10412       .addOperand(Scale)
10413       .addOperand(Index)
10414       .addDisp(Disp, 16)
10415       .addOperand(Segment)
10416       .setMemRefs(MMOBegin, MMOEnd);
10417
10418     // Zero-extend the offset
10419     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10420       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10421         .addImm(0)
10422         .addReg(OffsetReg)
10423         .addImm(X86::sub_32bit);
10424
10425     // Add the offset to the reg_save_area to get the final address.
10426     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10427       .addReg(OffsetReg64)
10428       .addReg(RegSaveReg);
10429
10430     // Compute the offset for the next argument
10431     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10432     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10433       .addReg(OffsetReg)
10434       .addImm(UseFPOffset ? 16 : 8);
10435
10436     // Store it back into the va_list.
10437     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10438       .addOperand(Base)
10439       .addOperand(Scale)
10440       .addOperand(Index)
10441       .addDisp(Disp, UseFPOffset ? 4 : 0)
10442       .addOperand(Segment)
10443       .addReg(NextOffsetReg)
10444       .setMemRefs(MMOBegin, MMOEnd);
10445
10446     // Jump to endMBB
10447     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10448       .addMBB(endMBB);
10449   }
10450
10451   //
10452   // Emit code to use overflow area
10453   //
10454
10455   // Load the overflow_area address into a register.
10456   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10457   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10458     .addOperand(Base)
10459     .addOperand(Scale)
10460     .addOperand(Index)
10461     .addDisp(Disp, 8)
10462     .addOperand(Segment)
10463     .setMemRefs(MMOBegin, MMOEnd);
10464
10465   // If we need to align it, do so. Otherwise, just copy the address
10466   // to OverflowDestReg.
10467   if (NeedsAlign) {
10468     // Align the overflow address
10469     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10470     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10471
10472     // aligned_addr = (addr + (align-1)) & ~(align-1)
10473     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10474       .addReg(OverflowAddrReg)
10475       .addImm(Align-1);
10476
10477     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10478       .addReg(TmpReg)
10479       .addImm(~(uint64_t)(Align-1));
10480   } else {
10481     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10482       .addReg(OverflowAddrReg);
10483   }
10484
10485   // Compute the next overflow address after this argument.
10486   // (the overflow address should be kept 8-byte aligned)
10487   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10488   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10489     .addReg(OverflowDestReg)
10490     .addImm(ArgSizeA8);
10491
10492   // Store the new overflow address.
10493   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10494     .addOperand(Base)
10495     .addOperand(Scale)
10496     .addOperand(Index)
10497     .addDisp(Disp, 8)
10498     .addOperand(Segment)
10499     .addReg(NextAddrReg)
10500     .setMemRefs(MMOBegin, MMOEnd);
10501
10502   // If we branched, emit the PHI to the front of endMBB.
10503   if (offsetMBB) {
10504     BuildMI(*endMBB, endMBB->begin(), DL,
10505             TII->get(X86::PHI), DestReg)
10506       .addReg(OffsetDestReg).addMBB(offsetMBB)
10507       .addReg(OverflowDestReg).addMBB(overflowMBB);
10508   }
10509
10510   // Erase the pseudo instruction
10511   MI->eraseFromParent();
10512
10513   return endMBB;
10514 }
10515
10516 MachineBasicBlock *
10517 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10518                                                  MachineInstr *MI,
10519                                                  MachineBasicBlock *MBB) const {
10520   // Emit code to save XMM registers to the stack. The ABI says that the
10521   // number of registers to save is given in %al, so it's theoretically
10522   // possible to do an indirect jump trick to avoid saving all of them,
10523   // however this code takes a simpler approach and just executes all
10524   // of the stores if %al is non-zero. It's less code, and it's probably
10525   // easier on the hardware branch predictor, and stores aren't all that
10526   // expensive anyway.
10527
10528   // Create the new basic blocks. One block contains all the XMM stores,
10529   // and one block is the final destination regardless of whether any
10530   // stores were performed.
10531   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10532   MachineFunction *F = MBB->getParent();
10533   MachineFunction::iterator MBBIter = MBB;
10534   ++MBBIter;
10535   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10536   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10537   F->insert(MBBIter, XMMSaveMBB);
10538   F->insert(MBBIter, EndMBB);
10539
10540   // Transfer the remainder of MBB and its successor edges to EndMBB.
10541   EndMBB->splice(EndMBB->begin(), MBB,
10542                  llvm::next(MachineBasicBlock::iterator(MI)),
10543                  MBB->end());
10544   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10545
10546   // The original block will now fall through to the XMM save block.
10547   MBB->addSuccessor(XMMSaveMBB);
10548   // The XMMSaveMBB will fall through to the end block.
10549   XMMSaveMBB->addSuccessor(EndMBB);
10550
10551   // Now add the instructions.
10552   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10553   DebugLoc DL = MI->getDebugLoc();
10554
10555   unsigned CountReg = MI->getOperand(0).getReg();
10556   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10557   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10558
10559   if (!Subtarget->isTargetWin64()) {
10560     // If %al is 0, branch around the XMM save block.
10561     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10562     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10563     MBB->addSuccessor(EndMBB);
10564   }
10565
10566   // In the XMM save block, save all the XMM argument registers.
10567   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10568     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10569     MachineMemOperand *MMO =
10570       F->getMachineMemOperand(
10571           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10572         MachineMemOperand::MOStore,
10573         /*Size=*/16, /*Align=*/16);
10574     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10575       .addFrameIndex(RegSaveFrameIndex)
10576       .addImm(/*Scale=*/1)
10577       .addReg(/*IndexReg=*/0)
10578       .addImm(/*Disp=*/Offset)
10579       .addReg(/*Segment=*/0)
10580       .addReg(MI->getOperand(i).getReg())
10581       .addMemOperand(MMO);
10582   }
10583
10584   MI->eraseFromParent();   // The pseudo instruction is gone now.
10585
10586   return EndMBB;
10587 }
10588
10589 MachineBasicBlock *
10590 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10591                                      MachineBasicBlock *BB) const {
10592   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10593   DebugLoc DL = MI->getDebugLoc();
10594
10595   // To "insert" a SELECT_CC instruction, we actually have to insert the
10596   // diamond control-flow pattern.  The incoming instruction knows the
10597   // destination vreg to set, the condition code register to branch on, the
10598   // true/false values to select between, and a branch opcode to use.
10599   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10600   MachineFunction::iterator It = BB;
10601   ++It;
10602
10603   //  thisMBB:
10604   //  ...
10605   //   TrueVal = ...
10606   //   cmpTY ccX, r1, r2
10607   //   bCC copy1MBB
10608   //   fallthrough --> copy0MBB
10609   MachineBasicBlock *thisMBB = BB;
10610   MachineFunction *F = BB->getParent();
10611   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10612   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10613   F->insert(It, copy0MBB);
10614   F->insert(It, sinkMBB);
10615
10616   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10617   // live into the sink and copy blocks.
10618   const MachineFunction *MF = BB->getParent();
10619   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10620   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10621
10622   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10623     const MachineOperand &MO = MI->getOperand(I);
10624     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10625     unsigned Reg = MO.getReg();
10626     if (Reg != X86::EFLAGS) continue;
10627     copy0MBB->addLiveIn(Reg);
10628     sinkMBB->addLiveIn(Reg);
10629   }
10630
10631   // Transfer the remainder of BB and its successor edges to sinkMBB.
10632   sinkMBB->splice(sinkMBB->begin(), BB,
10633                   llvm::next(MachineBasicBlock::iterator(MI)),
10634                   BB->end());
10635   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10636
10637   // Add the true and fallthrough blocks as its successors.
10638   BB->addSuccessor(copy0MBB);
10639   BB->addSuccessor(sinkMBB);
10640
10641   // Create the conditional branch instruction.
10642   unsigned Opc =
10643     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10644   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10645
10646   //  copy0MBB:
10647   //   %FalseValue = ...
10648   //   # fallthrough to sinkMBB
10649   copy0MBB->addSuccessor(sinkMBB);
10650
10651   //  sinkMBB:
10652   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10653   //  ...
10654   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10655           TII->get(X86::PHI), MI->getOperand(0).getReg())
10656     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10657     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10658
10659   MI->eraseFromParent();   // The pseudo instruction is gone now.
10660   return sinkMBB;
10661 }
10662
10663 MachineBasicBlock *
10664 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10665                                           MachineBasicBlock *BB) const {
10666   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10667   DebugLoc DL = MI->getDebugLoc();
10668
10669   assert(!Subtarget->isTargetEnvMacho());
10670
10671   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10672   // non-trivial part is impdef of ESP.
10673
10674   if (Subtarget->isTargetWin64()) {
10675     if (Subtarget->isTargetCygMing()) {
10676       // ___chkstk(Mingw64):
10677       // Clobbers R10, R11, RAX and EFLAGS.
10678       // Updates RSP.
10679       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10680         .addExternalSymbol("___chkstk")
10681         .addReg(X86::RAX, RegState::Implicit)
10682         .addReg(X86::RSP, RegState::Implicit)
10683         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10684         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10685         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10686     } else {
10687       // __chkstk(MSVCRT): does not update stack pointer.
10688       // Clobbers R10, R11 and EFLAGS.
10689       // FIXME: RAX(allocated size) might be reused and not killed.
10690       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10691         .addExternalSymbol("__chkstk")
10692         .addReg(X86::RAX, RegState::Implicit)
10693         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10694       // RAX has the offset to subtracted from RSP.
10695       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10696         .addReg(X86::RSP)
10697         .addReg(X86::RAX);
10698     }
10699   } else {
10700     const char *StackProbeSymbol =
10701       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10702
10703     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10704       .addExternalSymbol(StackProbeSymbol)
10705       .addReg(X86::EAX, RegState::Implicit)
10706       .addReg(X86::ESP, RegState::Implicit)
10707       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10708       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10709       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10710   }
10711
10712   MI->eraseFromParent();   // The pseudo instruction is gone now.
10713   return BB;
10714 }
10715
10716 MachineBasicBlock *
10717 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10718                                       MachineBasicBlock *BB) const {
10719   // This is pretty easy.  We're taking the value that we received from
10720   // our load from the relocation, sticking it in either RDI (x86-64)
10721   // or EAX and doing an indirect call.  The return value will then
10722   // be in the normal return register.
10723   const X86InstrInfo *TII
10724     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10725   DebugLoc DL = MI->getDebugLoc();
10726   MachineFunction *F = BB->getParent();
10727
10728   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10729   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10730
10731   if (Subtarget->is64Bit()) {
10732     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10733                                       TII->get(X86::MOV64rm), X86::RDI)
10734     .addReg(X86::RIP)
10735     .addImm(0).addReg(0)
10736     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10737                       MI->getOperand(3).getTargetFlags())
10738     .addReg(0);
10739     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10740     addDirectMem(MIB, X86::RDI);
10741   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10742     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10743                                       TII->get(X86::MOV32rm), X86::EAX)
10744     .addReg(0)
10745     .addImm(0).addReg(0)
10746     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10747                       MI->getOperand(3).getTargetFlags())
10748     .addReg(0);
10749     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10750     addDirectMem(MIB, X86::EAX);
10751   } else {
10752     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10753                                       TII->get(X86::MOV32rm), X86::EAX)
10754     .addReg(TII->getGlobalBaseReg(F))
10755     .addImm(0).addReg(0)
10756     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10757                       MI->getOperand(3).getTargetFlags())
10758     .addReg(0);
10759     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10760     addDirectMem(MIB, X86::EAX);
10761   }
10762
10763   MI->eraseFromParent(); // The pseudo instruction is gone now.
10764   return BB;
10765 }
10766
10767 MachineBasicBlock *
10768 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10769                                                MachineBasicBlock *BB) const {
10770   switch (MI->getOpcode()) {
10771   default: assert(false && "Unexpected instr type to insert");
10772   case X86::TAILJMPd64:
10773   case X86::TAILJMPr64:
10774   case X86::TAILJMPm64:
10775     assert(!"TAILJMP64 would not be touched here.");
10776   case X86::TCRETURNdi64:
10777   case X86::TCRETURNri64:
10778   case X86::TCRETURNmi64:
10779     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10780     // On AMD64, additional defs should be added before register allocation.
10781     if (!Subtarget->isTargetWin64()) {
10782       MI->addRegisterDefined(X86::RSI);
10783       MI->addRegisterDefined(X86::RDI);
10784       MI->addRegisterDefined(X86::XMM6);
10785       MI->addRegisterDefined(X86::XMM7);
10786       MI->addRegisterDefined(X86::XMM8);
10787       MI->addRegisterDefined(X86::XMM9);
10788       MI->addRegisterDefined(X86::XMM10);
10789       MI->addRegisterDefined(X86::XMM11);
10790       MI->addRegisterDefined(X86::XMM12);
10791       MI->addRegisterDefined(X86::XMM13);
10792       MI->addRegisterDefined(X86::XMM14);
10793       MI->addRegisterDefined(X86::XMM15);
10794     }
10795     return BB;
10796   case X86::WIN_ALLOCA:
10797     return EmitLoweredWinAlloca(MI, BB);
10798   case X86::TLSCall_32:
10799   case X86::TLSCall_64:
10800     return EmitLoweredTLSCall(MI, BB);
10801   case X86::CMOV_GR8:
10802   case X86::CMOV_FR32:
10803   case X86::CMOV_FR64:
10804   case X86::CMOV_V4F32:
10805   case X86::CMOV_V2F64:
10806   case X86::CMOV_V2I64:
10807   case X86::CMOV_GR16:
10808   case X86::CMOV_GR32:
10809   case X86::CMOV_RFP32:
10810   case X86::CMOV_RFP64:
10811   case X86::CMOV_RFP80:
10812     return EmitLoweredSelect(MI, BB);
10813
10814   case X86::FP32_TO_INT16_IN_MEM:
10815   case X86::FP32_TO_INT32_IN_MEM:
10816   case X86::FP32_TO_INT64_IN_MEM:
10817   case X86::FP64_TO_INT16_IN_MEM:
10818   case X86::FP64_TO_INT32_IN_MEM:
10819   case X86::FP64_TO_INT64_IN_MEM:
10820   case X86::FP80_TO_INT16_IN_MEM:
10821   case X86::FP80_TO_INT32_IN_MEM:
10822   case X86::FP80_TO_INT64_IN_MEM: {
10823     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10824     DebugLoc DL = MI->getDebugLoc();
10825
10826     // Change the floating point control register to use "round towards zero"
10827     // mode when truncating to an integer value.
10828     MachineFunction *F = BB->getParent();
10829     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10830     addFrameReference(BuildMI(*BB, MI, DL,
10831                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10832
10833     // Load the old value of the high byte of the control word...
10834     unsigned OldCW =
10835       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10836     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10837                       CWFrameIdx);
10838
10839     // Set the high part to be round to zero...
10840     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10841       .addImm(0xC7F);
10842
10843     // Reload the modified control word now...
10844     addFrameReference(BuildMI(*BB, MI, DL,
10845                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10846
10847     // Restore the memory image of control word to original value
10848     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10849       .addReg(OldCW);
10850
10851     // Get the X86 opcode to use.
10852     unsigned Opc;
10853     switch (MI->getOpcode()) {
10854     default: llvm_unreachable("illegal opcode!");
10855     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10856     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10857     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10858     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10859     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10860     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10861     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10862     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10863     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10864     }
10865
10866     X86AddressMode AM;
10867     MachineOperand &Op = MI->getOperand(0);
10868     if (Op.isReg()) {
10869       AM.BaseType = X86AddressMode::RegBase;
10870       AM.Base.Reg = Op.getReg();
10871     } else {
10872       AM.BaseType = X86AddressMode::FrameIndexBase;
10873       AM.Base.FrameIndex = Op.getIndex();
10874     }
10875     Op = MI->getOperand(1);
10876     if (Op.isImm())
10877       AM.Scale = Op.getImm();
10878     Op = MI->getOperand(2);
10879     if (Op.isImm())
10880       AM.IndexReg = Op.getImm();
10881     Op = MI->getOperand(3);
10882     if (Op.isGlobal()) {
10883       AM.GV = Op.getGlobal();
10884     } else {
10885       AM.Disp = Op.getImm();
10886     }
10887     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10888                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10889
10890     // Reload the original control word now.
10891     addFrameReference(BuildMI(*BB, MI, DL,
10892                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10893
10894     MI->eraseFromParent();   // The pseudo instruction is gone now.
10895     return BB;
10896   }
10897     // String/text processing lowering.
10898   case X86::PCMPISTRM128REG:
10899   case X86::VPCMPISTRM128REG:
10900     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10901   case X86::PCMPISTRM128MEM:
10902   case X86::VPCMPISTRM128MEM:
10903     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10904   case X86::PCMPESTRM128REG:
10905   case X86::VPCMPESTRM128REG:
10906     return EmitPCMP(MI, BB, 5, false /* in mem */);
10907   case X86::PCMPESTRM128MEM:
10908   case X86::VPCMPESTRM128MEM:
10909     return EmitPCMP(MI, BB, 5, true /* in mem */);
10910
10911     // Thread synchronization.
10912   case X86::MONITOR:
10913     return EmitMonitor(MI, BB);
10914   case X86::MWAIT:
10915     return EmitMwait(MI, BB);
10916
10917     // Atomic Lowering.
10918   case X86::ATOMAND32:
10919     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10920                                                X86::AND32ri, X86::MOV32rm,
10921                                                X86::LCMPXCHG32,
10922                                                X86::NOT32r, X86::EAX,
10923                                                X86::GR32RegisterClass);
10924   case X86::ATOMOR32:
10925     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10926                                                X86::OR32ri, X86::MOV32rm,
10927                                                X86::LCMPXCHG32,
10928                                                X86::NOT32r, X86::EAX,
10929                                                X86::GR32RegisterClass);
10930   case X86::ATOMXOR32:
10931     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10932                                                X86::XOR32ri, X86::MOV32rm,
10933                                                X86::LCMPXCHG32,
10934                                                X86::NOT32r, X86::EAX,
10935                                                X86::GR32RegisterClass);
10936   case X86::ATOMNAND32:
10937     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10938                                                X86::AND32ri, X86::MOV32rm,
10939                                                X86::LCMPXCHG32,
10940                                                X86::NOT32r, X86::EAX,
10941                                                X86::GR32RegisterClass, true);
10942   case X86::ATOMMIN32:
10943     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10944   case X86::ATOMMAX32:
10945     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10946   case X86::ATOMUMIN32:
10947     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10948   case X86::ATOMUMAX32:
10949     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10950
10951   case X86::ATOMAND16:
10952     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10953                                                X86::AND16ri, X86::MOV16rm,
10954                                                X86::LCMPXCHG16,
10955                                                X86::NOT16r, X86::AX,
10956                                                X86::GR16RegisterClass);
10957   case X86::ATOMOR16:
10958     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10959                                                X86::OR16ri, X86::MOV16rm,
10960                                                X86::LCMPXCHG16,
10961                                                X86::NOT16r, X86::AX,
10962                                                X86::GR16RegisterClass);
10963   case X86::ATOMXOR16:
10964     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10965                                                X86::XOR16ri, X86::MOV16rm,
10966                                                X86::LCMPXCHG16,
10967                                                X86::NOT16r, X86::AX,
10968                                                X86::GR16RegisterClass);
10969   case X86::ATOMNAND16:
10970     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10971                                                X86::AND16ri, X86::MOV16rm,
10972                                                X86::LCMPXCHG16,
10973                                                X86::NOT16r, X86::AX,
10974                                                X86::GR16RegisterClass, true);
10975   case X86::ATOMMIN16:
10976     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10977   case X86::ATOMMAX16:
10978     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10979   case X86::ATOMUMIN16:
10980     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10981   case X86::ATOMUMAX16:
10982     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10983
10984   case X86::ATOMAND8:
10985     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10986                                                X86::AND8ri, X86::MOV8rm,
10987                                                X86::LCMPXCHG8,
10988                                                X86::NOT8r, X86::AL,
10989                                                X86::GR8RegisterClass);
10990   case X86::ATOMOR8:
10991     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10992                                                X86::OR8ri, X86::MOV8rm,
10993                                                X86::LCMPXCHG8,
10994                                                X86::NOT8r, X86::AL,
10995                                                X86::GR8RegisterClass);
10996   case X86::ATOMXOR8:
10997     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10998                                                X86::XOR8ri, X86::MOV8rm,
10999                                                X86::LCMPXCHG8,
11000                                                X86::NOT8r, X86::AL,
11001                                                X86::GR8RegisterClass);
11002   case X86::ATOMNAND8:
11003     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11004                                                X86::AND8ri, X86::MOV8rm,
11005                                                X86::LCMPXCHG8,
11006                                                X86::NOT8r, X86::AL,
11007                                                X86::GR8RegisterClass, true);
11008   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11009   // This group is for 64-bit host.
11010   case X86::ATOMAND64:
11011     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11012                                                X86::AND64ri32, X86::MOV64rm,
11013                                                X86::LCMPXCHG64,
11014                                                X86::NOT64r, X86::RAX,
11015                                                X86::GR64RegisterClass);
11016   case X86::ATOMOR64:
11017     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11018                                                X86::OR64ri32, X86::MOV64rm,
11019                                                X86::LCMPXCHG64,
11020                                                X86::NOT64r, X86::RAX,
11021                                                X86::GR64RegisterClass);
11022   case X86::ATOMXOR64:
11023     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11024                                                X86::XOR64ri32, X86::MOV64rm,
11025                                                X86::LCMPXCHG64,
11026                                                X86::NOT64r, X86::RAX,
11027                                                X86::GR64RegisterClass);
11028   case X86::ATOMNAND64:
11029     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11030                                                X86::AND64ri32, X86::MOV64rm,
11031                                                X86::LCMPXCHG64,
11032                                                X86::NOT64r, X86::RAX,
11033                                                X86::GR64RegisterClass, true);
11034   case X86::ATOMMIN64:
11035     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11036   case X86::ATOMMAX64:
11037     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11038   case X86::ATOMUMIN64:
11039     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11040   case X86::ATOMUMAX64:
11041     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11042
11043   // This group does 64-bit operations on a 32-bit host.
11044   case X86::ATOMAND6432:
11045     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11046                                                X86::AND32rr, X86::AND32rr,
11047                                                X86::AND32ri, X86::AND32ri,
11048                                                false);
11049   case X86::ATOMOR6432:
11050     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11051                                                X86::OR32rr, X86::OR32rr,
11052                                                X86::OR32ri, X86::OR32ri,
11053                                                false);
11054   case X86::ATOMXOR6432:
11055     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11056                                                X86::XOR32rr, X86::XOR32rr,
11057                                                X86::XOR32ri, X86::XOR32ri,
11058                                                false);
11059   case X86::ATOMNAND6432:
11060     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11061                                                X86::AND32rr, X86::AND32rr,
11062                                                X86::AND32ri, X86::AND32ri,
11063                                                true);
11064   case X86::ATOMADD6432:
11065     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11066                                                X86::ADD32rr, X86::ADC32rr,
11067                                                X86::ADD32ri, X86::ADC32ri,
11068                                                false);
11069   case X86::ATOMSUB6432:
11070     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11071                                                X86::SUB32rr, X86::SBB32rr,
11072                                                X86::SUB32ri, X86::SBB32ri,
11073                                                false);
11074   case X86::ATOMSWAP6432:
11075     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11076                                                X86::MOV32rr, X86::MOV32rr,
11077                                                X86::MOV32ri, X86::MOV32ri,
11078                                                false);
11079   case X86::VASTART_SAVE_XMM_REGS:
11080     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11081
11082   case X86::VAARG_64:
11083     return EmitVAARG64WithCustomInserter(MI, BB);
11084   }
11085 }
11086
11087 //===----------------------------------------------------------------------===//
11088 //                           X86 Optimization Hooks
11089 //===----------------------------------------------------------------------===//
11090
11091 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11092                                                        const APInt &Mask,
11093                                                        APInt &KnownZero,
11094                                                        APInt &KnownOne,
11095                                                        const SelectionDAG &DAG,
11096                                                        unsigned Depth) const {
11097   unsigned Opc = Op.getOpcode();
11098   assert((Opc >= ISD::BUILTIN_OP_END ||
11099           Opc == ISD::INTRINSIC_WO_CHAIN ||
11100           Opc == ISD::INTRINSIC_W_CHAIN ||
11101           Opc == ISD::INTRINSIC_VOID) &&
11102          "Should use MaskedValueIsZero if you don't know whether Op"
11103          " is a target node!");
11104
11105   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11106   switch (Opc) {
11107   default: break;
11108   case X86ISD::ADD:
11109   case X86ISD::SUB:
11110   case X86ISD::ADC:
11111   case X86ISD::SBB:
11112   case X86ISD::SMUL:
11113   case X86ISD::UMUL:
11114   case X86ISD::INC:
11115   case X86ISD::DEC:
11116   case X86ISD::OR:
11117   case X86ISD::XOR:
11118   case X86ISD::AND:
11119     // These nodes' second result is a boolean.
11120     if (Op.getResNo() == 0)
11121       break;
11122     // Fallthrough
11123   case X86ISD::SETCC:
11124     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11125                                        Mask.getBitWidth() - 1);
11126     break;
11127   }
11128 }
11129
11130 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11131                                                          unsigned Depth) const {
11132   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11133   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11134     return Op.getValueType().getScalarType().getSizeInBits();
11135
11136   // Fallback case.
11137   return 1;
11138 }
11139
11140 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11141 /// node is a GlobalAddress + offset.
11142 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11143                                        const GlobalValue* &GA,
11144                                        int64_t &Offset) const {
11145   if (N->getOpcode() == X86ISD::Wrapper) {
11146     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11147       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11148       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11149       return true;
11150     }
11151   }
11152   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11153 }
11154
11155 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
11156 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
11157 /// if the load addresses are consecutive, non-overlapping, and in the right
11158 /// order.
11159 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
11160                                      TargetLowering::DAGCombinerInfo &DCI) {
11161   DebugLoc dl = N->getDebugLoc();
11162   EVT VT = N->getValueType(0);
11163
11164   if (VT.getSizeInBits() != 128)
11165     return SDValue();
11166
11167   // Don't create instructions with illegal types after legalize types has run.
11168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11169   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11170     return SDValue();
11171
11172   SmallVector<SDValue, 16> Elts;
11173   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11174     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11175
11176   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11177 }
11178
11179 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11180 /// generation and convert it from being a bunch of shuffles and extracts
11181 /// to a simple store and scalar loads to extract the elements.
11182 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11183                                                 const TargetLowering &TLI) {
11184   SDValue InputVector = N->getOperand(0);
11185
11186   // Only operate on vectors of 4 elements, where the alternative shuffling
11187   // gets to be more expensive.
11188   if (InputVector.getValueType() != MVT::v4i32)
11189     return SDValue();
11190
11191   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11192   // single use which is a sign-extend or zero-extend, and all elements are
11193   // used.
11194   SmallVector<SDNode *, 4> Uses;
11195   unsigned ExtractedElements = 0;
11196   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11197        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11198     if (UI.getUse().getResNo() != InputVector.getResNo())
11199       return SDValue();
11200
11201     SDNode *Extract = *UI;
11202     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11203       return SDValue();
11204
11205     if (Extract->getValueType(0) != MVT::i32)
11206       return SDValue();
11207     if (!Extract->hasOneUse())
11208       return SDValue();
11209     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11210         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11211       return SDValue();
11212     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11213       return SDValue();
11214
11215     // Record which element was extracted.
11216     ExtractedElements |=
11217       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11218
11219     Uses.push_back(Extract);
11220   }
11221
11222   // If not all the elements were used, this may not be worthwhile.
11223   if (ExtractedElements != 15)
11224     return SDValue();
11225
11226   // Ok, we've now decided to do the transformation.
11227   DebugLoc dl = InputVector.getDebugLoc();
11228
11229   // Store the value to a temporary stack slot.
11230   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11231   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11232                             MachinePointerInfo(), false, false, 0);
11233
11234   // Replace each use (extract) with a load of the appropriate element.
11235   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11236        UE = Uses.end(); UI != UE; ++UI) {
11237     SDNode *Extract = *UI;
11238
11239     // cOMpute the element's address.
11240     SDValue Idx = Extract->getOperand(1);
11241     unsigned EltSize =
11242         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11243     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11244     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11245
11246     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11247                                      StackPtr, OffsetVal);
11248
11249     // Load the scalar.
11250     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11251                                      ScalarAddr, MachinePointerInfo(),
11252                                      false, false, 0);
11253
11254     // Replace the exact with the load.
11255     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11256   }
11257
11258   // The replacement was made in place; don't return anything.
11259   return SDValue();
11260 }
11261
11262 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11263 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11264                                     const X86Subtarget *Subtarget) {
11265   DebugLoc DL = N->getDebugLoc();
11266   SDValue Cond = N->getOperand(0);
11267   // Get the LHS/RHS of the select.
11268   SDValue LHS = N->getOperand(1);
11269   SDValue RHS = N->getOperand(2);
11270
11271   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11272   // instructions match the semantics of the common C idiom x<y?x:y but not
11273   // x<=y?x:y, because of how they handle negative zero (which can be
11274   // ignored in unsafe-math mode).
11275   if (Subtarget->hasSSE2() &&
11276       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11277       Cond.getOpcode() == ISD::SETCC) {
11278     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11279
11280     unsigned Opcode = 0;
11281     // Check for x CC y ? x : y.
11282     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11283         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11284       switch (CC) {
11285       default: break;
11286       case ISD::SETULT:
11287         // Converting this to a min would handle NaNs incorrectly, and swapping
11288         // the operands would cause it to handle comparisons between positive
11289         // and negative zero incorrectly.
11290         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11291           if (!UnsafeFPMath &&
11292               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11293             break;
11294           std::swap(LHS, RHS);
11295         }
11296         Opcode = X86ISD::FMIN;
11297         break;
11298       case ISD::SETOLE:
11299         // Converting this to a min would handle comparisons between positive
11300         // and negative zero incorrectly.
11301         if (!UnsafeFPMath &&
11302             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11303           break;
11304         Opcode = X86ISD::FMIN;
11305         break;
11306       case ISD::SETULE:
11307         // Converting this to a min would handle both negative zeros and NaNs
11308         // incorrectly, but we can swap the operands to fix both.
11309         std::swap(LHS, RHS);
11310       case ISD::SETOLT:
11311       case ISD::SETLT:
11312       case ISD::SETLE:
11313         Opcode = X86ISD::FMIN;
11314         break;
11315
11316       case ISD::SETOGE:
11317         // Converting this to a max would handle comparisons between positive
11318         // and negative zero incorrectly.
11319         if (!UnsafeFPMath &&
11320             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11321           break;
11322         Opcode = X86ISD::FMAX;
11323         break;
11324       case ISD::SETUGT:
11325         // Converting this to a max would handle NaNs incorrectly, and swapping
11326         // the operands would cause it to handle comparisons between positive
11327         // and negative zero incorrectly.
11328         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11329           if (!UnsafeFPMath &&
11330               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11331             break;
11332           std::swap(LHS, RHS);
11333         }
11334         Opcode = X86ISD::FMAX;
11335         break;
11336       case ISD::SETUGE:
11337         // Converting this to a max would handle both negative zeros and NaNs
11338         // incorrectly, but we can swap the operands to fix both.
11339         std::swap(LHS, RHS);
11340       case ISD::SETOGT:
11341       case ISD::SETGT:
11342       case ISD::SETGE:
11343         Opcode = X86ISD::FMAX;
11344         break;
11345       }
11346     // Check for x CC y ? y : x -- a min/max with reversed arms.
11347     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11348                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11349       switch (CC) {
11350       default: break;
11351       case ISD::SETOGE:
11352         // Converting this to a min would handle comparisons between positive
11353         // and negative zero incorrectly, and swapping the operands would
11354         // cause it to handle NaNs incorrectly.
11355         if (!UnsafeFPMath &&
11356             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11357           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11358             break;
11359           std::swap(LHS, RHS);
11360         }
11361         Opcode = X86ISD::FMIN;
11362         break;
11363       case ISD::SETUGT:
11364         // Converting this to a min would handle NaNs incorrectly.
11365         if (!UnsafeFPMath &&
11366             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11367           break;
11368         Opcode = X86ISD::FMIN;
11369         break;
11370       case ISD::SETUGE:
11371         // Converting this to a min would handle both negative zeros and NaNs
11372         // incorrectly, but we can swap the operands to fix both.
11373         std::swap(LHS, RHS);
11374       case ISD::SETOGT:
11375       case ISD::SETGT:
11376       case ISD::SETGE:
11377         Opcode = X86ISD::FMIN;
11378         break;
11379
11380       case ISD::SETULT:
11381         // Converting this to a max would handle NaNs incorrectly.
11382         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11383           break;
11384         Opcode = X86ISD::FMAX;
11385         break;
11386       case ISD::SETOLE:
11387         // Converting this to a max would handle comparisons between positive
11388         // and negative zero incorrectly, and swapping the operands would
11389         // cause it to handle NaNs incorrectly.
11390         if (!UnsafeFPMath &&
11391             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11392           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11393             break;
11394           std::swap(LHS, RHS);
11395         }
11396         Opcode = X86ISD::FMAX;
11397         break;
11398       case ISD::SETULE:
11399         // Converting this to a max would handle both negative zeros and NaNs
11400         // incorrectly, but we can swap the operands to fix both.
11401         std::swap(LHS, RHS);
11402       case ISD::SETOLT:
11403       case ISD::SETLT:
11404       case ISD::SETLE:
11405         Opcode = X86ISD::FMAX;
11406         break;
11407       }
11408     }
11409
11410     if (Opcode)
11411       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11412   }
11413
11414   // If this is a select between two integer constants, try to do some
11415   // optimizations.
11416   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11417     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11418       // Don't do this for crazy integer types.
11419       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11420         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11421         // so that TrueC (the true value) is larger than FalseC.
11422         bool NeedsCondInvert = false;
11423
11424         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11425             // Efficiently invertible.
11426             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11427              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11428               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11429           NeedsCondInvert = true;
11430           std::swap(TrueC, FalseC);
11431         }
11432
11433         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11434         if (FalseC->getAPIntValue() == 0 &&
11435             TrueC->getAPIntValue().isPowerOf2()) {
11436           if (NeedsCondInvert) // Invert the condition if needed.
11437             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11438                                DAG.getConstant(1, Cond.getValueType()));
11439
11440           // Zero extend the condition if needed.
11441           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11442
11443           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11444           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11445                              DAG.getConstant(ShAmt, MVT::i8));
11446         }
11447
11448         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11449         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11450           if (NeedsCondInvert) // Invert the condition if needed.
11451             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11452                                DAG.getConstant(1, Cond.getValueType()));
11453
11454           // Zero extend the condition if needed.
11455           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11456                              FalseC->getValueType(0), Cond);
11457           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11458                              SDValue(FalseC, 0));
11459         }
11460
11461         // Optimize cases that will turn into an LEA instruction.  This requires
11462         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11463         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11464           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11465           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11466
11467           bool isFastMultiplier = false;
11468           if (Diff < 10) {
11469             switch ((unsigned char)Diff) {
11470               default: break;
11471               case 1:  // result = add base, cond
11472               case 2:  // result = lea base(    , cond*2)
11473               case 3:  // result = lea base(cond, cond*2)
11474               case 4:  // result = lea base(    , cond*4)
11475               case 5:  // result = lea base(cond, cond*4)
11476               case 8:  // result = lea base(    , cond*8)
11477               case 9:  // result = lea base(cond, cond*8)
11478                 isFastMultiplier = true;
11479                 break;
11480             }
11481           }
11482
11483           if (isFastMultiplier) {
11484             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11485             if (NeedsCondInvert) // Invert the condition if needed.
11486               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11487                                  DAG.getConstant(1, Cond.getValueType()));
11488
11489             // Zero extend the condition if needed.
11490             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11491                                Cond);
11492             // Scale the condition by the difference.
11493             if (Diff != 1)
11494               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11495                                  DAG.getConstant(Diff, Cond.getValueType()));
11496
11497             // Add the base if non-zero.
11498             if (FalseC->getAPIntValue() != 0)
11499               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11500                                  SDValue(FalseC, 0));
11501             return Cond;
11502           }
11503         }
11504       }
11505   }
11506
11507   return SDValue();
11508 }
11509
11510 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11511 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11512                                   TargetLowering::DAGCombinerInfo &DCI) {
11513   DebugLoc DL = N->getDebugLoc();
11514
11515   // If the flag operand isn't dead, don't touch this CMOV.
11516   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11517     return SDValue();
11518
11519   SDValue FalseOp = N->getOperand(0);
11520   SDValue TrueOp = N->getOperand(1);
11521   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11522   SDValue Cond = N->getOperand(3);
11523   if (CC == X86::COND_E || CC == X86::COND_NE) {
11524     switch (Cond.getOpcode()) {
11525     default: break;
11526     case X86ISD::BSR:
11527     case X86ISD::BSF:
11528       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11529       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11530         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11531     }
11532   }
11533
11534   // If this is a select between two integer constants, try to do some
11535   // optimizations.  Note that the operands are ordered the opposite of SELECT
11536   // operands.
11537   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11538     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11539       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11540       // larger than FalseC (the false value).
11541       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11542         CC = X86::GetOppositeBranchCondition(CC);
11543         std::swap(TrueC, FalseC);
11544       }
11545
11546       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11547       // This is efficient for any integer data type (including i8/i16) and
11548       // shift amount.
11549       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11550         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11551                            DAG.getConstant(CC, MVT::i8), Cond);
11552
11553         // Zero extend the condition if needed.
11554         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11555
11556         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11557         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11558                            DAG.getConstant(ShAmt, MVT::i8));
11559         if (N->getNumValues() == 2)  // Dead flag value?
11560           return DCI.CombineTo(N, Cond, SDValue());
11561         return Cond;
11562       }
11563
11564       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11565       // for any integer data type, including i8/i16.
11566       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11567         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11568                            DAG.getConstant(CC, MVT::i8), Cond);
11569
11570         // Zero extend the condition if needed.
11571         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11572                            FalseC->getValueType(0), Cond);
11573         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11574                            SDValue(FalseC, 0));
11575
11576         if (N->getNumValues() == 2)  // Dead flag value?
11577           return DCI.CombineTo(N, Cond, SDValue());
11578         return Cond;
11579       }
11580
11581       // Optimize cases that will turn into an LEA instruction.  This requires
11582       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11583       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11584         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11585         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11586
11587         bool isFastMultiplier = false;
11588         if (Diff < 10) {
11589           switch ((unsigned char)Diff) {
11590           default: break;
11591           case 1:  // result = add base, cond
11592           case 2:  // result = lea base(    , cond*2)
11593           case 3:  // result = lea base(cond, cond*2)
11594           case 4:  // result = lea base(    , cond*4)
11595           case 5:  // result = lea base(cond, cond*4)
11596           case 8:  // result = lea base(    , cond*8)
11597           case 9:  // result = lea base(cond, cond*8)
11598             isFastMultiplier = true;
11599             break;
11600           }
11601         }
11602
11603         if (isFastMultiplier) {
11604           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11605           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11606                              DAG.getConstant(CC, MVT::i8), Cond);
11607           // Zero extend the condition if needed.
11608           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11609                              Cond);
11610           // Scale the condition by the difference.
11611           if (Diff != 1)
11612             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11613                                DAG.getConstant(Diff, Cond.getValueType()));
11614
11615           // Add the base if non-zero.
11616           if (FalseC->getAPIntValue() != 0)
11617             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11618                                SDValue(FalseC, 0));
11619           if (N->getNumValues() == 2)  // Dead flag value?
11620             return DCI.CombineTo(N, Cond, SDValue());
11621           return Cond;
11622         }
11623       }
11624     }
11625   }
11626   return SDValue();
11627 }
11628
11629
11630 /// PerformMulCombine - Optimize a single multiply with constant into two
11631 /// in order to implement it with two cheaper instructions, e.g.
11632 /// LEA + SHL, LEA + LEA.
11633 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11634                                  TargetLowering::DAGCombinerInfo &DCI) {
11635   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11636     return SDValue();
11637
11638   EVT VT = N->getValueType(0);
11639   if (VT != MVT::i64)
11640     return SDValue();
11641
11642   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11643   if (!C)
11644     return SDValue();
11645   uint64_t MulAmt = C->getZExtValue();
11646   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11647     return SDValue();
11648
11649   uint64_t MulAmt1 = 0;
11650   uint64_t MulAmt2 = 0;
11651   if ((MulAmt % 9) == 0) {
11652     MulAmt1 = 9;
11653     MulAmt2 = MulAmt / 9;
11654   } else if ((MulAmt % 5) == 0) {
11655     MulAmt1 = 5;
11656     MulAmt2 = MulAmt / 5;
11657   } else if ((MulAmt % 3) == 0) {
11658     MulAmt1 = 3;
11659     MulAmt2 = MulAmt / 3;
11660   }
11661   if (MulAmt2 &&
11662       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11663     DebugLoc DL = N->getDebugLoc();
11664
11665     if (isPowerOf2_64(MulAmt2) &&
11666         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11667       // If second multiplifer is pow2, issue it first. We want the multiply by
11668       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11669       // is an add.
11670       std::swap(MulAmt1, MulAmt2);
11671
11672     SDValue NewMul;
11673     if (isPowerOf2_64(MulAmt1))
11674       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11675                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11676     else
11677       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11678                            DAG.getConstant(MulAmt1, VT));
11679
11680     if (isPowerOf2_64(MulAmt2))
11681       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11682                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11683     else
11684       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11685                            DAG.getConstant(MulAmt2, VT));
11686
11687     // Do not add new nodes to DAG combiner worklist.
11688     DCI.CombineTo(N, NewMul, false);
11689   }
11690   return SDValue();
11691 }
11692
11693 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11694   SDValue N0 = N->getOperand(0);
11695   SDValue N1 = N->getOperand(1);
11696   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11697   EVT VT = N0.getValueType();
11698
11699   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11700   // since the result of setcc_c is all zero's or all ones.
11701   if (N1C && N0.getOpcode() == ISD::AND &&
11702       N0.getOperand(1).getOpcode() == ISD::Constant) {
11703     SDValue N00 = N0.getOperand(0);
11704     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11705         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11706           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11707          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11708       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11709       APInt ShAmt = N1C->getAPIntValue();
11710       Mask = Mask.shl(ShAmt);
11711       if (Mask != 0)
11712         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11713                            N00, DAG.getConstant(Mask, VT));
11714     }
11715   }
11716
11717   return SDValue();
11718 }
11719
11720 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11721 ///                       when possible.
11722 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11723                                    const X86Subtarget *Subtarget) {
11724   EVT VT = N->getValueType(0);
11725   if (!VT.isVector() && VT.isInteger() &&
11726       N->getOpcode() == ISD::SHL)
11727     return PerformSHLCombine(N, DAG);
11728
11729   // On X86 with SSE2 support, we can transform this to a vector shift if
11730   // all elements are shifted by the same amount.  We can't do this in legalize
11731   // because the a constant vector is typically transformed to a constant pool
11732   // so we have no knowledge of the shift amount.
11733   if (!Subtarget->hasSSE2())
11734     return SDValue();
11735
11736   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11737     return SDValue();
11738
11739   SDValue ShAmtOp = N->getOperand(1);
11740   EVT EltVT = VT.getVectorElementType();
11741   DebugLoc DL = N->getDebugLoc();
11742   SDValue BaseShAmt = SDValue();
11743   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11744     unsigned NumElts = VT.getVectorNumElements();
11745     unsigned i = 0;
11746     for (; i != NumElts; ++i) {
11747       SDValue Arg = ShAmtOp.getOperand(i);
11748       if (Arg.getOpcode() == ISD::UNDEF) continue;
11749       BaseShAmt = Arg;
11750       break;
11751     }
11752     for (; i != NumElts; ++i) {
11753       SDValue Arg = ShAmtOp.getOperand(i);
11754       if (Arg.getOpcode() == ISD::UNDEF) continue;
11755       if (Arg != BaseShAmt) {
11756         return SDValue();
11757       }
11758     }
11759   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11760              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11761     SDValue InVec = ShAmtOp.getOperand(0);
11762     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11763       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11764       unsigned i = 0;
11765       for (; i != NumElts; ++i) {
11766         SDValue Arg = InVec.getOperand(i);
11767         if (Arg.getOpcode() == ISD::UNDEF) continue;
11768         BaseShAmt = Arg;
11769         break;
11770       }
11771     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11772        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11773          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11774          if (C->getZExtValue() == SplatIdx)
11775            BaseShAmt = InVec.getOperand(1);
11776        }
11777     }
11778     if (BaseShAmt.getNode() == 0)
11779       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11780                               DAG.getIntPtrConstant(0));
11781   } else
11782     return SDValue();
11783
11784   // The shift amount is an i32.
11785   if (EltVT.bitsGT(MVT::i32))
11786     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11787   else if (EltVT.bitsLT(MVT::i32))
11788     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11789
11790   // The shift amount is identical so we can do a vector shift.
11791   SDValue  ValOp = N->getOperand(0);
11792   switch (N->getOpcode()) {
11793   default:
11794     llvm_unreachable("Unknown shift opcode!");
11795     break;
11796   case ISD::SHL:
11797     if (VT == MVT::v2i64)
11798       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11799                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11800                          ValOp, BaseShAmt);
11801     if (VT == MVT::v4i32)
11802       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11803                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11804                          ValOp, BaseShAmt);
11805     if (VT == MVT::v8i16)
11806       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11807                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11808                          ValOp, BaseShAmt);
11809     break;
11810   case ISD::SRA:
11811     if (VT == MVT::v4i32)
11812       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11813                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11814                          ValOp, BaseShAmt);
11815     if (VT == MVT::v8i16)
11816       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11817                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11818                          ValOp, BaseShAmt);
11819     break;
11820   case ISD::SRL:
11821     if (VT == MVT::v2i64)
11822       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11823                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11824                          ValOp, BaseShAmt);
11825     if (VT == MVT::v4i32)
11826       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11827                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11828                          ValOp, BaseShAmt);
11829     if (VT ==  MVT::v8i16)
11830       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11831                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11832                          ValOp, BaseShAmt);
11833     break;
11834   }
11835   return SDValue();
11836 }
11837
11838
11839 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11840 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11841 // and friends.  Likewise for OR -> CMPNEQSS.
11842 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11843                             TargetLowering::DAGCombinerInfo &DCI,
11844                             const X86Subtarget *Subtarget) {
11845   unsigned opcode;
11846
11847   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11848   // we're requiring SSE2 for both.
11849   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11850     SDValue N0 = N->getOperand(0);
11851     SDValue N1 = N->getOperand(1);
11852     SDValue CMP0 = N0->getOperand(1);
11853     SDValue CMP1 = N1->getOperand(1);
11854     DebugLoc DL = N->getDebugLoc();
11855
11856     // The SETCCs should both refer to the same CMP.
11857     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
11858       return SDValue();
11859
11860     SDValue CMP00 = CMP0->getOperand(0);
11861     SDValue CMP01 = CMP0->getOperand(1);
11862     EVT     VT    = CMP00.getValueType();
11863
11864     if (VT == MVT::f32 || VT == MVT::f64) {
11865       bool ExpectingFlags = false;
11866       // Check for any users that want flags:
11867       for (SDNode::use_iterator UI = N->use_begin(),
11868              UE = N->use_end();
11869            !ExpectingFlags && UI != UE; ++UI)
11870         switch (UI->getOpcode()) {
11871         default:
11872         case ISD::BR_CC:
11873         case ISD::BRCOND:
11874         case ISD::SELECT:
11875           ExpectingFlags = true;
11876           break;
11877         case ISD::CopyToReg:
11878         case ISD::SIGN_EXTEND:
11879         case ISD::ZERO_EXTEND:
11880         case ISD::ANY_EXTEND:
11881           break;
11882         }
11883
11884       if (!ExpectingFlags) {
11885         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11886         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11887
11888         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11889           X86::CondCode tmp = cc0;
11890           cc0 = cc1;
11891           cc1 = tmp;
11892         }
11893
11894         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11895             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11896           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
11897           X86ISD::NodeType NTOperator = is64BitFP ?
11898             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11899           // FIXME: need symbolic constants for these magic numbers.
11900           // See X86ATTInstPrinter.cpp:printSSECC().
11901           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11902           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
11903                                               DAG.getConstant(x86cc, MVT::i8));
11904           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11905                                               OnesOrZeroesF);
11906           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11907                                       DAG.getConstant(1, MVT::i32));
11908           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11909           return OneBitOfTruth;
11910         }
11911       }
11912     }
11913   }
11914   return SDValue();
11915 }
11916
11917 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11918                                  TargetLowering::DAGCombinerInfo &DCI,
11919                                  const X86Subtarget *Subtarget) {
11920   if (DCI.isBeforeLegalizeOps())
11921     return SDValue();
11922
11923   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11924   if (R.getNode())
11925     return R;
11926
11927   // Want to form ANDNP nodes:
11928   // 1) In the hopes of then easily combining them with OR and AND nodes
11929   //    to form PBLEND/PSIGN.
11930   // 2) To match ANDN packed intrinsics
11931   EVT VT = N->getValueType(0);
11932   if (VT != MVT::v2i64 && VT != MVT::v4i64)
11933     return SDValue();
11934
11935   SDValue N0 = N->getOperand(0);
11936   SDValue N1 = N->getOperand(1);
11937   DebugLoc DL = N->getDebugLoc();
11938
11939   // Check LHS for vnot
11940   if (N0.getOpcode() == ISD::XOR &&
11941       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11942     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
11943
11944   // Check RHS for vnot
11945   if (N1.getOpcode() == ISD::XOR &&
11946       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11947     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
11948
11949   return SDValue();
11950 }
11951
11952 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11953                                 TargetLowering::DAGCombinerInfo &DCI,
11954                                 const X86Subtarget *Subtarget) {
11955   if (DCI.isBeforeLegalizeOps())
11956     return SDValue();
11957
11958   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11959   if (R.getNode())
11960     return R;
11961
11962   EVT VT = N->getValueType(0);
11963   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11964     return SDValue();
11965
11966   SDValue N0 = N->getOperand(0);
11967   SDValue N1 = N->getOperand(1);
11968
11969   // look for psign/blend
11970   if (Subtarget->hasSSSE3()) {
11971     if (VT == MVT::v2i64) {
11972       // Canonicalize pandn to RHS
11973       if (N0.getOpcode() == X86ISD::ANDNP)
11974         std::swap(N0, N1);
11975       // or (and (m, x), (pandn m, y))
11976       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
11977         SDValue Mask = N1.getOperand(0);
11978         SDValue X    = N1.getOperand(1);
11979         SDValue Y;
11980         if (N0.getOperand(0) == Mask)
11981           Y = N0.getOperand(1);
11982         if (N0.getOperand(1) == Mask)
11983           Y = N0.getOperand(0);
11984
11985         // Check to see if the mask appeared in both the AND and ANDNP and
11986         if (!Y.getNode())
11987           return SDValue();
11988
11989         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11990         if (Mask.getOpcode() != ISD::BITCAST ||
11991             X.getOpcode() != ISD::BITCAST ||
11992             Y.getOpcode() != ISD::BITCAST)
11993           return SDValue();
11994
11995         // Look through mask bitcast.
11996         Mask = Mask.getOperand(0);
11997         EVT MaskVT = Mask.getValueType();
11998
11999         // Validate that the Mask operand is a vector sra node.  The sra node
12000         // will be an intrinsic.
12001         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12002           return SDValue();
12003
12004         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12005         // there is no psrai.b
12006         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12007         case Intrinsic::x86_sse2_psrai_w:
12008         case Intrinsic::x86_sse2_psrai_d:
12009           break;
12010         default: return SDValue();
12011         }
12012
12013         // Check that the SRA is all signbits.
12014         SDValue SraC = Mask.getOperand(2);
12015         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
12016         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12017         if ((SraAmt + 1) != EltBits)
12018           return SDValue();
12019
12020         DebugLoc DL = N->getDebugLoc();
12021
12022         // Now we know we at least have a plendvb with the mask val.  See if
12023         // we can form a psignb/w/d.
12024         // psign = x.type == y.type == mask.type && y = sub(0, x);
12025         X = X.getOperand(0);
12026         Y = Y.getOperand(0);
12027         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12028             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12029             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12030           unsigned Opc = 0;
12031           switch (EltBits) {
12032           case 8: Opc = X86ISD::PSIGNB; break;
12033           case 16: Opc = X86ISD::PSIGNW; break;
12034           case 32: Opc = X86ISD::PSIGND; break;
12035           default: break;
12036           }
12037           if (Opc) {
12038             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12039             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12040           }
12041         }
12042         // PBLENDVB only available on SSE 4.1
12043         if (!Subtarget->hasSSE41())
12044           return SDValue();
12045
12046         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12047         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12048         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12049         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12050         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12051       }
12052     }
12053   }
12054
12055   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12056   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12057     std::swap(N0, N1);
12058   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12059     return SDValue();
12060   if (!N0.hasOneUse() || !N1.hasOneUse())
12061     return SDValue();
12062
12063   SDValue ShAmt0 = N0.getOperand(1);
12064   if (ShAmt0.getValueType() != MVT::i8)
12065     return SDValue();
12066   SDValue ShAmt1 = N1.getOperand(1);
12067   if (ShAmt1.getValueType() != MVT::i8)
12068     return SDValue();
12069   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12070     ShAmt0 = ShAmt0.getOperand(0);
12071   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12072     ShAmt1 = ShAmt1.getOperand(0);
12073
12074   DebugLoc DL = N->getDebugLoc();
12075   unsigned Opc = X86ISD::SHLD;
12076   SDValue Op0 = N0.getOperand(0);
12077   SDValue Op1 = N1.getOperand(0);
12078   if (ShAmt0.getOpcode() == ISD::SUB) {
12079     Opc = X86ISD::SHRD;
12080     std::swap(Op0, Op1);
12081     std::swap(ShAmt0, ShAmt1);
12082   }
12083
12084   unsigned Bits = VT.getSizeInBits();
12085   if (ShAmt1.getOpcode() == ISD::SUB) {
12086     SDValue Sum = ShAmt1.getOperand(0);
12087     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12088       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12089       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12090         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12091       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12092         return DAG.getNode(Opc, DL, VT,
12093                            Op0, Op1,
12094                            DAG.getNode(ISD::TRUNCATE, DL,
12095                                        MVT::i8, ShAmt0));
12096     }
12097   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12098     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12099     if (ShAmt0C &&
12100         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
12101       return DAG.getNode(Opc, DL, VT,
12102                          N0.getOperand(0), N1.getOperand(0),
12103                          DAG.getNode(ISD::TRUNCATE, DL,
12104                                        MVT::i8, ShAmt0));
12105   }
12106
12107   return SDValue();
12108 }
12109
12110 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
12111 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
12112                                    const X86Subtarget *Subtarget) {
12113   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
12114   // the FP state in cases where an emms may be missing.
12115   // A preferable solution to the general problem is to figure out the right
12116   // places to insert EMMS.  This qualifies as a quick hack.
12117
12118   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
12119   StoreSDNode *St = cast<StoreSDNode>(N);
12120   EVT VT = St->getValue().getValueType();
12121   if (VT.getSizeInBits() != 64)
12122     return SDValue();
12123
12124   const Function *F = DAG.getMachineFunction().getFunction();
12125   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
12126   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
12127     && Subtarget->hasSSE2();
12128   if ((VT.isVector() ||
12129        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
12130       isa<LoadSDNode>(St->getValue()) &&
12131       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
12132       St->getChain().hasOneUse() && !St->isVolatile()) {
12133     SDNode* LdVal = St->getValue().getNode();
12134     LoadSDNode *Ld = 0;
12135     int TokenFactorIndex = -1;
12136     SmallVector<SDValue, 8> Ops;
12137     SDNode* ChainVal = St->getChain().getNode();
12138     // Must be a store of a load.  We currently handle two cases:  the load
12139     // is a direct child, and it's under an intervening TokenFactor.  It is
12140     // possible to dig deeper under nested TokenFactors.
12141     if (ChainVal == LdVal)
12142       Ld = cast<LoadSDNode>(St->getChain());
12143     else if (St->getValue().hasOneUse() &&
12144              ChainVal->getOpcode() == ISD::TokenFactor) {
12145       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
12146         if (ChainVal->getOperand(i).getNode() == LdVal) {
12147           TokenFactorIndex = i;
12148           Ld = cast<LoadSDNode>(St->getValue());
12149         } else
12150           Ops.push_back(ChainVal->getOperand(i));
12151       }
12152     }
12153
12154     if (!Ld || !ISD::isNormalLoad(Ld))
12155       return SDValue();
12156
12157     // If this is not the MMX case, i.e. we are just turning i64 load/store
12158     // into f64 load/store, avoid the transformation if there are multiple
12159     // uses of the loaded value.
12160     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
12161       return SDValue();
12162
12163     DebugLoc LdDL = Ld->getDebugLoc();
12164     DebugLoc StDL = N->getDebugLoc();
12165     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
12166     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
12167     // pair instead.
12168     if (Subtarget->is64Bit() || F64IsLegal) {
12169       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
12170       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
12171                                   Ld->getPointerInfo(), Ld->isVolatile(),
12172                                   Ld->isNonTemporal(), Ld->getAlignment());
12173       SDValue NewChain = NewLd.getValue(1);
12174       if (TokenFactorIndex != -1) {
12175         Ops.push_back(NewChain);
12176         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12177                                Ops.size());
12178       }
12179       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12180                           St->getPointerInfo(),
12181                           St->isVolatile(), St->isNonTemporal(),
12182                           St->getAlignment());
12183     }
12184
12185     // Otherwise, lower to two pairs of 32-bit loads / stores.
12186     SDValue LoAddr = Ld->getBasePtr();
12187     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12188                                  DAG.getConstant(4, MVT::i32));
12189
12190     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12191                                Ld->getPointerInfo(),
12192                                Ld->isVolatile(), Ld->isNonTemporal(),
12193                                Ld->getAlignment());
12194     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12195                                Ld->getPointerInfo().getWithOffset(4),
12196                                Ld->isVolatile(), Ld->isNonTemporal(),
12197                                MinAlign(Ld->getAlignment(), 4));
12198
12199     SDValue NewChain = LoLd.getValue(1);
12200     if (TokenFactorIndex != -1) {
12201       Ops.push_back(LoLd);
12202       Ops.push_back(HiLd);
12203       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12204                              Ops.size());
12205     }
12206
12207     LoAddr = St->getBasePtr();
12208     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12209                          DAG.getConstant(4, MVT::i32));
12210
12211     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12212                                 St->getPointerInfo(),
12213                                 St->isVolatile(), St->isNonTemporal(),
12214                                 St->getAlignment());
12215     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12216                                 St->getPointerInfo().getWithOffset(4),
12217                                 St->isVolatile(),
12218                                 St->isNonTemporal(),
12219                                 MinAlign(St->getAlignment(), 4));
12220     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12221   }
12222   return SDValue();
12223 }
12224
12225 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12226 /// X86ISD::FXOR nodes.
12227 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12228   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12229   // F[X]OR(0.0, x) -> x
12230   // F[X]OR(x, 0.0) -> x
12231   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12232     if (C->getValueAPF().isPosZero())
12233       return N->getOperand(1);
12234   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12235     if (C->getValueAPF().isPosZero())
12236       return N->getOperand(0);
12237   return SDValue();
12238 }
12239
12240 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12241 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12242   // FAND(0.0, x) -> 0.0
12243   // FAND(x, 0.0) -> 0.0
12244   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12245     if (C->getValueAPF().isPosZero())
12246       return N->getOperand(0);
12247   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12248     if (C->getValueAPF().isPosZero())
12249       return N->getOperand(1);
12250   return SDValue();
12251 }
12252
12253 static SDValue PerformBTCombine(SDNode *N,
12254                                 SelectionDAG &DAG,
12255                                 TargetLowering::DAGCombinerInfo &DCI) {
12256   // BT ignores high bits in the bit index operand.
12257   SDValue Op1 = N->getOperand(1);
12258   if (Op1.hasOneUse()) {
12259     unsigned BitWidth = Op1.getValueSizeInBits();
12260     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12261     APInt KnownZero, KnownOne;
12262     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12263                                           !DCI.isBeforeLegalizeOps());
12264     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12265     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12266         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12267       DCI.CommitTargetLoweringOpt(TLO);
12268   }
12269   return SDValue();
12270 }
12271
12272 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12273   SDValue Op = N->getOperand(0);
12274   if (Op.getOpcode() == ISD::BITCAST)
12275     Op = Op.getOperand(0);
12276   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12277   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12278       VT.getVectorElementType().getSizeInBits() ==
12279       OpVT.getVectorElementType().getSizeInBits()) {
12280     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12281   }
12282   return SDValue();
12283 }
12284
12285 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12286   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12287   //           (and (i32 x86isd::setcc_carry), 1)
12288   // This eliminates the zext. This transformation is necessary because
12289   // ISD::SETCC is always legalized to i8.
12290   DebugLoc dl = N->getDebugLoc();
12291   SDValue N0 = N->getOperand(0);
12292   EVT VT = N->getValueType(0);
12293   if (N0.getOpcode() == ISD::AND &&
12294       N0.hasOneUse() &&
12295       N0.getOperand(0).hasOneUse()) {
12296     SDValue N00 = N0.getOperand(0);
12297     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12298       return SDValue();
12299     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12300     if (!C || C->getZExtValue() != 1)
12301       return SDValue();
12302     return DAG.getNode(ISD::AND, dl, VT,
12303                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12304                                    N00.getOperand(0), N00.getOperand(1)),
12305                        DAG.getConstant(1, VT));
12306   }
12307
12308   return SDValue();
12309 }
12310
12311 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12312 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12313   unsigned X86CC = N->getConstantOperandVal(0);
12314   SDValue EFLAG = N->getOperand(1);
12315   DebugLoc DL = N->getDebugLoc();
12316
12317   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12318   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12319   // cases.
12320   if (X86CC == X86::COND_B)
12321     return DAG.getNode(ISD::AND, DL, MVT::i8,
12322                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12323                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12324                        DAG.getConstant(1, MVT::i8));
12325
12326   return SDValue();
12327 }
12328
12329 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
12330                                         const X86TargetLowering *XTLI) {
12331   SDValue Op0 = N->getOperand(0);
12332   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
12333   // a 32-bit target where SSE doesn't support i64->FP operations.
12334   if (Op0.getOpcode() == ISD::LOAD) {
12335     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
12336     EVT VT = Ld->getValueType(0);
12337     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
12338         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
12339         !XTLI->getSubtarget()->is64Bit() &&
12340         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12341       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
12342                                           Ld->getChain(), Op0, DAG);
12343       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
12344       return FILDChain;
12345     }
12346   }
12347   return SDValue();
12348 }
12349
12350 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12351 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12352                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12353   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12354   // the result is either zero or one (depending on the input carry bit).
12355   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12356   if (X86::isZeroNode(N->getOperand(0)) &&
12357       X86::isZeroNode(N->getOperand(1)) &&
12358       // We don't have a good way to replace an EFLAGS use, so only do this when
12359       // dead right now.
12360       SDValue(N, 1).use_empty()) {
12361     DebugLoc DL = N->getDebugLoc();
12362     EVT VT = N->getValueType(0);
12363     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12364     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12365                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12366                                            DAG.getConstant(X86::COND_B,MVT::i8),
12367                                            N->getOperand(2)),
12368                                DAG.getConstant(1, VT));
12369     return DCI.CombineTo(N, Res1, CarryOut);
12370   }
12371
12372   return SDValue();
12373 }
12374
12375 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12376 //      (add Y, (setne X, 0)) -> sbb -1, Y
12377 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12378 //      (sub (setne X, 0), Y) -> adc -1, Y
12379 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12380   DebugLoc DL = N->getDebugLoc();
12381
12382   // Look through ZExts.
12383   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12384   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12385     return SDValue();
12386
12387   SDValue SetCC = Ext.getOperand(0);
12388   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12389     return SDValue();
12390
12391   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12392   if (CC != X86::COND_E && CC != X86::COND_NE)
12393     return SDValue();
12394
12395   SDValue Cmp = SetCC.getOperand(1);
12396   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12397       !X86::isZeroNode(Cmp.getOperand(1)) ||
12398       !Cmp.getOperand(0).getValueType().isInteger())
12399     return SDValue();
12400
12401   SDValue CmpOp0 = Cmp.getOperand(0);
12402   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12403                                DAG.getConstant(1, CmpOp0.getValueType()));
12404
12405   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12406   if (CC == X86::COND_NE)
12407     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12408                        DL, OtherVal.getValueType(), OtherVal,
12409                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12410   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12411                      DL, OtherVal.getValueType(), OtherVal,
12412                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12413 }
12414
12415 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12416                                              DAGCombinerInfo &DCI) const {
12417   SelectionDAG &DAG = DCI.DAG;
12418   switch (N->getOpcode()) {
12419   default: break;
12420   case ISD::EXTRACT_VECTOR_ELT:
12421     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12422   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12423   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12424   case ISD::ADD:
12425   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12426   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12427   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12428   case ISD::SHL:
12429   case ISD::SRA:
12430   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12431   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12432   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12433   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12434   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
12435   case X86ISD::FXOR:
12436   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12437   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12438   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12439   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12440   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12441   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12442   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12443   case X86ISD::SHUFPD:
12444   case X86ISD::PALIGN:
12445   case X86ISD::PUNPCKHBW:
12446   case X86ISD::PUNPCKHWD:
12447   case X86ISD::PUNPCKHDQ:
12448   case X86ISD::PUNPCKHQDQ:
12449   case X86ISD::UNPCKHPS:
12450   case X86ISD::UNPCKHPD:
12451   case X86ISD::PUNPCKLBW:
12452   case X86ISD::PUNPCKLWD:
12453   case X86ISD::PUNPCKLDQ:
12454   case X86ISD::PUNPCKLQDQ:
12455   case X86ISD::UNPCKLPS:
12456   case X86ISD::UNPCKLPD:
12457   case X86ISD::VUNPCKLPS:
12458   case X86ISD::VUNPCKLPD:
12459   case X86ISD::VUNPCKLPSY:
12460   case X86ISD::VUNPCKLPDY:
12461   case X86ISD::MOVHLPS:
12462   case X86ISD::MOVLHPS:
12463   case X86ISD::PSHUFD:
12464   case X86ISD::PSHUFHW:
12465   case X86ISD::PSHUFLW:
12466   case X86ISD::MOVSS:
12467   case X86ISD::MOVSD:
12468   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12469   }
12470
12471   return SDValue();
12472 }
12473
12474 /// isTypeDesirableForOp - Return true if the target has native support for
12475 /// the specified value type and it is 'desirable' to use the type for the
12476 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12477 /// instruction encodings are longer and some i16 instructions are slow.
12478 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12479   if (!isTypeLegal(VT))
12480     return false;
12481   if (VT != MVT::i16)
12482     return true;
12483
12484   switch (Opc) {
12485   default:
12486     return true;
12487   case ISD::LOAD:
12488   case ISD::SIGN_EXTEND:
12489   case ISD::ZERO_EXTEND:
12490   case ISD::ANY_EXTEND:
12491   case ISD::SHL:
12492   case ISD::SRL:
12493   case ISD::SUB:
12494   case ISD::ADD:
12495   case ISD::MUL:
12496   case ISD::AND:
12497   case ISD::OR:
12498   case ISD::XOR:
12499     return false;
12500   }
12501 }
12502
12503 /// IsDesirableToPromoteOp - This method query the target whether it is
12504 /// beneficial for dag combiner to promote the specified node. If true, it
12505 /// should return the desired promotion type by reference.
12506 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12507   EVT VT = Op.getValueType();
12508   if (VT != MVT::i16)
12509     return false;
12510
12511   bool Promote = false;
12512   bool Commute = false;
12513   switch (Op.getOpcode()) {
12514   default: break;
12515   case ISD::LOAD: {
12516     LoadSDNode *LD = cast<LoadSDNode>(Op);
12517     // If the non-extending load has a single use and it's not live out, then it
12518     // might be folded.
12519     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12520                                                      Op.hasOneUse()*/) {
12521       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12522              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12523         // The only case where we'd want to promote LOAD (rather then it being
12524         // promoted as an operand is when it's only use is liveout.
12525         if (UI->getOpcode() != ISD::CopyToReg)
12526           return false;
12527       }
12528     }
12529     Promote = true;
12530     break;
12531   }
12532   case ISD::SIGN_EXTEND:
12533   case ISD::ZERO_EXTEND:
12534   case ISD::ANY_EXTEND:
12535     Promote = true;
12536     break;
12537   case ISD::SHL:
12538   case ISD::SRL: {
12539     SDValue N0 = Op.getOperand(0);
12540     // Look out for (store (shl (load), x)).
12541     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12542       return false;
12543     Promote = true;
12544     break;
12545   }
12546   case ISD::ADD:
12547   case ISD::MUL:
12548   case ISD::AND:
12549   case ISD::OR:
12550   case ISD::XOR:
12551     Commute = true;
12552     // fallthrough
12553   case ISD::SUB: {
12554     SDValue N0 = Op.getOperand(0);
12555     SDValue N1 = Op.getOperand(1);
12556     if (!Commute && MayFoldLoad(N1))
12557       return false;
12558     // Avoid disabling potential load folding opportunities.
12559     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12560       return false;
12561     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12562       return false;
12563     Promote = true;
12564   }
12565   }
12566
12567   PVT = MVT::i32;
12568   return Promote;
12569 }
12570
12571 //===----------------------------------------------------------------------===//
12572 //                           X86 Inline Assembly Support
12573 //===----------------------------------------------------------------------===//
12574
12575 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12576   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12577
12578   std::string AsmStr = IA->getAsmString();
12579
12580   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12581   SmallVector<StringRef, 4> AsmPieces;
12582   SplitString(AsmStr, AsmPieces, ";\n");
12583
12584   switch (AsmPieces.size()) {
12585   default: return false;
12586   case 1:
12587     AsmStr = AsmPieces[0];
12588     AsmPieces.clear();
12589     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12590
12591     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12592     // we will turn this bswap into something that will be lowered to logical ops
12593     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12594     // so don't worry about this.
12595     // bswap $0
12596     if (AsmPieces.size() == 2 &&
12597         (AsmPieces[0] == "bswap" ||
12598          AsmPieces[0] == "bswapq" ||
12599          AsmPieces[0] == "bswapl") &&
12600         (AsmPieces[1] == "$0" ||
12601          AsmPieces[1] == "${0:q}")) {
12602       // No need to check constraints, nothing other than the equivalent of
12603       // "=r,0" would be valid here.
12604       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12605       if (!Ty || Ty->getBitWidth() % 16 != 0)
12606         return false;
12607       return IntrinsicLowering::LowerToByteSwap(CI);
12608     }
12609     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12610     if (CI->getType()->isIntegerTy(16) &&
12611         AsmPieces.size() == 3 &&
12612         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12613         AsmPieces[1] == "$$8," &&
12614         AsmPieces[2] == "${0:w}" &&
12615         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12616       AsmPieces.clear();
12617       const std::string &ConstraintsStr = IA->getConstraintString();
12618       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12619       std::sort(AsmPieces.begin(), AsmPieces.end());
12620       if (AsmPieces.size() == 4 &&
12621           AsmPieces[0] == "~{cc}" &&
12622           AsmPieces[1] == "~{dirflag}" &&
12623           AsmPieces[2] == "~{flags}" &&
12624           AsmPieces[3] == "~{fpsr}") {
12625         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12626         if (!Ty || Ty->getBitWidth() % 16 != 0)
12627           return false;
12628         return IntrinsicLowering::LowerToByteSwap(CI);
12629       }
12630     }
12631     break;
12632   case 3:
12633     if (CI->getType()->isIntegerTy(32) &&
12634         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12635       SmallVector<StringRef, 4> Words;
12636       SplitString(AsmPieces[0], Words, " \t,");
12637       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12638           Words[2] == "${0:w}") {
12639         Words.clear();
12640         SplitString(AsmPieces[1], Words, " \t,");
12641         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12642             Words[2] == "$0") {
12643           Words.clear();
12644           SplitString(AsmPieces[2], Words, " \t,");
12645           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12646               Words[2] == "${0:w}") {
12647             AsmPieces.clear();
12648             const std::string &ConstraintsStr = IA->getConstraintString();
12649             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12650             std::sort(AsmPieces.begin(), AsmPieces.end());
12651             if (AsmPieces.size() == 4 &&
12652                 AsmPieces[0] == "~{cc}" &&
12653                 AsmPieces[1] == "~{dirflag}" &&
12654                 AsmPieces[2] == "~{flags}" &&
12655                 AsmPieces[3] == "~{fpsr}") {
12656               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12657               if (!Ty || Ty->getBitWidth() % 16 != 0)
12658                 return false;
12659               return IntrinsicLowering::LowerToByteSwap(CI);
12660             }
12661           }
12662         }
12663       }
12664     }
12665
12666     if (CI->getType()->isIntegerTy(64)) {
12667       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12668       if (Constraints.size() >= 2 &&
12669           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12670           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12671         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12672         SmallVector<StringRef, 4> Words;
12673         SplitString(AsmPieces[0], Words, " \t");
12674         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12675           Words.clear();
12676           SplitString(AsmPieces[1], Words, " \t");
12677           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12678             Words.clear();
12679             SplitString(AsmPieces[2], Words, " \t,");
12680             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12681                 Words[2] == "%edx") {
12682               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12683               if (!Ty || Ty->getBitWidth() % 16 != 0)
12684                 return false;
12685               return IntrinsicLowering::LowerToByteSwap(CI);
12686             }
12687           }
12688         }
12689       }
12690     }
12691     break;
12692   }
12693   return false;
12694 }
12695
12696
12697
12698 /// getConstraintType - Given a constraint letter, return the type of
12699 /// constraint it is for this target.
12700 X86TargetLowering::ConstraintType
12701 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12702   if (Constraint.size() == 1) {
12703     switch (Constraint[0]) {
12704     case 'R':
12705     case 'q':
12706     case 'Q':
12707     case 'f':
12708     case 't':
12709     case 'u':
12710     case 'y':
12711     case 'x':
12712     case 'Y':
12713     case 'l':
12714       return C_RegisterClass;
12715     case 'a':
12716     case 'b':
12717     case 'c':
12718     case 'd':
12719     case 'S':
12720     case 'D':
12721     case 'A':
12722       return C_Register;
12723     case 'I':
12724     case 'J':
12725     case 'K':
12726     case 'L':
12727     case 'M':
12728     case 'N':
12729     case 'G':
12730     case 'C':
12731     case 'e':
12732     case 'Z':
12733       return C_Other;
12734     default:
12735       break;
12736     }
12737   }
12738   return TargetLowering::getConstraintType(Constraint);
12739 }
12740
12741 /// Examine constraint type and operand type and determine a weight value.
12742 /// This object must already have been set up with the operand type
12743 /// and the current alternative constraint selected.
12744 TargetLowering::ConstraintWeight
12745   X86TargetLowering::getSingleConstraintMatchWeight(
12746     AsmOperandInfo &info, const char *constraint) const {
12747   ConstraintWeight weight = CW_Invalid;
12748   Value *CallOperandVal = info.CallOperandVal;
12749     // If we don't have a value, we can't do a match,
12750     // but allow it at the lowest weight.
12751   if (CallOperandVal == NULL)
12752     return CW_Default;
12753   Type *type = CallOperandVal->getType();
12754   // Look at the constraint type.
12755   switch (*constraint) {
12756   default:
12757     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12758   case 'R':
12759   case 'q':
12760   case 'Q':
12761   case 'a':
12762   case 'b':
12763   case 'c':
12764   case 'd':
12765   case 'S':
12766   case 'D':
12767   case 'A':
12768     if (CallOperandVal->getType()->isIntegerTy())
12769       weight = CW_SpecificReg;
12770     break;
12771   case 'f':
12772   case 't':
12773   case 'u':
12774       if (type->isFloatingPointTy())
12775         weight = CW_SpecificReg;
12776       break;
12777   case 'y':
12778       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12779         weight = CW_SpecificReg;
12780       break;
12781   case 'x':
12782   case 'Y':
12783     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12784       weight = CW_Register;
12785     break;
12786   case 'I':
12787     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12788       if (C->getZExtValue() <= 31)
12789         weight = CW_Constant;
12790     }
12791     break;
12792   case 'J':
12793     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12794       if (C->getZExtValue() <= 63)
12795         weight = CW_Constant;
12796     }
12797     break;
12798   case 'K':
12799     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12800       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12801         weight = CW_Constant;
12802     }
12803     break;
12804   case 'L':
12805     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12806       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12807         weight = CW_Constant;
12808     }
12809     break;
12810   case 'M':
12811     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12812       if (C->getZExtValue() <= 3)
12813         weight = CW_Constant;
12814     }
12815     break;
12816   case 'N':
12817     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12818       if (C->getZExtValue() <= 0xff)
12819         weight = CW_Constant;
12820     }
12821     break;
12822   case 'G':
12823   case 'C':
12824     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12825       weight = CW_Constant;
12826     }
12827     break;
12828   case 'e':
12829     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12830       if ((C->getSExtValue() >= -0x80000000LL) &&
12831           (C->getSExtValue() <= 0x7fffffffLL))
12832         weight = CW_Constant;
12833     }
12834     break;
12835   case 'Z':
12836     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12837       if (C->getZExtValue() <= 0xffffffff)
12838         weight = CW_Constant;
12839     }
12840     break;
12841   }
12842   return weight;
12843 }
12844
12845 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12846 /// with another that has more specific requirements based on the type of the
12847 /// corresponding operand.
12848 const char *X86TargetLowering::
12849 LowerXConstraint(EVT ConstraintVT) const {
12850   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12851   // 'f' like normal targets.
12852   if (ConstraintVT.isFloatingPoint()) {
12853     if (Subtarget->hasXMMInt())
12854       return "Y";
12855     if (Subtarget->hasXMM())
12856       return "x";
12857   }
12858
12859   return TargetLowering::LowerXConstraint(ConstraintVT);
12860 }
12861
12862 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12863 /// vector.  If it is invalid, don't add anything to Ops.
12864 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12865                                                      std::string &Constraint,
12866                                                      std::vector<SDValue>&Ops,
12867                                                      SelectionDAG &DAG) const {
12868   SDValue Result(0, 0);
12869
12870   // Only support length 1 constraints for now.
12871   if (Constraint.length() > 1) return;
12872
12873   char ConstraintLetter = Constraint[0];
12874   switch (ConstraintLetter) {
12875   default: break;
12876   case 'I':
12877     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12878       if (C->getZExtValue() <= 31) {
12879         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12880         break;
12881       }
12882     }
12883     return;
12884   case 'J':
12885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12886       if (C->getZExtValue() <= 63) {
12887         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12888         break;
12889       }
12890     }
12891     return;
12892   case 'K':
12893     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12894       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12895         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12896         break;
12897       }
12898     }
12899     return;
12900   case 'N':
12901     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12902       if (C->getZExtValue() <= 255) {
12903         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12904         break;
12905       }
12906     }
12907     return;
12908   case 'e': {
12909     // 32-bit signed value
12910     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12911       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12912                                            C->getSExtValue())) {
12913         // Widen to 64 bits here to get it sign extended.
12914         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12915         break;
12916       }
12917     // FIXME gcc accepts some relocatable values here too, but only in certain
12918     // memory models; it's complicated.
12919     }
12920     return;
12921   }
12922   case 'Z': {
12923     // 32-bit unsigned value
12924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12925       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12926                                            C->getZExtValue())) {
12927         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12928         break;
12929       }
12930     }
12931     // FIXME gcc accepts some relocatable values here too, but only in certain
12932     // memory models; it's complicated.
12933     return;
12934   }
12935   case 'i': {
12936     // Literal immediates are always ok.
12937     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12938       // Widen to 64 bits here to get it sign extended.
12939       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12940       break;
12941     }
12942
12943     // In any sort of PIC mode addresses need to be computed at runtime by
12944     // adding in a register or some sort of table lookup.  These can't
12945     // be used as immediates.
12946     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12947       return;
12948
12949     // If we are in non-pic codegen mode, we allow the address of a global (with
12950     // an optional displacement) to be used with 'i'.
12951     GlobalAddressSDNode *GA = 0;
12952     int64_t Offset = 0;
12953
12954     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12955     while (1) {
12956       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12957         Offset += GA->getOffset();
12958         break;
12959       } else if (Op.getOpcode() == ISD::ADD) {
12960         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12961           Offset += C->getZExtValue();
12962           Op = Op.getOperand(0);
12963           continue;
12964         }
12965       } else if (Op.getOpcode() == ISD::SUB) {
12966         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12967           Offset += -C->getZExtValue();
12968           Op = Op.getOperand(0);
12969           continue;
12970         }
12971       }
12972
12973       // Otherwise, this isn't something we can handle, reject it.
12974       return;
12975     }
12976
12977     const GlobalValue *GV = GA->getGlobal();
12978     // If we require an extra load to get this address, as in PIC mode, we
12979     // can't accept it.
12980     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12981                                                         getTargetMachine())))
12982       return;
12983
12984     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12985                                         GA->getValueType(0), Offset);
12986     break;
12987   }
12988   }
12989
12990   if (Result.getNode()) {
12991     Ops.push_back(Result);
12992     return;
12993   }
12994   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12995 }
12996
12997 std::pair<unsigned, const TargetRegisterClass*>
12998 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12999                                                 EVT VT) const {
13000   // First, see if this is a constraint that directly corresponds to an LLVM
13001   // register class.
13002   if (Constraint.size() == 1) {
13003     // GCC Constraint Letters
13004     switch (Constraint[0]) {
13005     default: break;
13006       // TODO: Slight differences here in allocation order and leaving
13007       // RIP in the class. Do they matter any more here than they do
13008       // in the normal allocation?
13009     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
13010       if (Subtarget->is64Bit()) {
13011         if (VT == MVT::i32 || VT == MVT::f32)
13012           return std::make_pair(0U, X86::GR32RegisterClass);
13013         else if (VT == MVT::i16)
13014           return std::make_pair(0U, X86::GR16RegisterClass);
13015         else if (VT == MVT::i8 || VT == MVT::i1)
13016           return std::make_pair(0U, X86::GR8RegisterClass);
13017         else if (VT == MVT::i64 || VT == MVT::f64)
13018           return std::make_pair(0U, X86::GR64RegisterClass);
13019         break;
13020       }
13021       // 32-bit fallthrough
13022     case 'Q':   // Q_REGS
13023       if (VT == MVT::i32 || VT == MVT::f32)
13024         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
13025       else if (VT == MVT::i16)
13026         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
13027       else if (VT == MVT::i8 || VT == MVT::i1)
13028         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
13029       else if (VT == MVT::i64)
13030         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
13031       break;
13032     case 'r':   // GENERAL_REGS
13033     case 'l':   // INDEX_REGS
13034       if (VT == MVT::i8 || VT == MVT::i1)
13035         return std::make_pair(0U, X86::GR8RegisterClass);
13036       if (VT == MVT::i16)
13037         return std::make_pair(0U, X86::GR16RegisterClass);
13038       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
13039         return std::make_pair(0U, X86::GR32RegisterClass);
13040       return std::make_pair(0U, X86::GR64RegisterClass);
13041     case 'R':   // LEGACY_REGS
13042       if (VT == MVT::i8 || VT == MVT::i1)
13043         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
13044       if (VT == MVT::i16)
13045         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
13046       if (VT == MVT::i32 || !Subtarget->is64Bit())
13047         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
13048       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
13049     case 'f':  // FP Stack registers.
13050       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
13051       // value to the correct fpstack register class.
13052       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
13053         return std::make_pair(0U, X86::RFP32RegisterClass);
13054       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
13055         return std::make_pair(0U, X86::RFP64RegisterClass);
13056       return std::make_pair(0U, X86::RFP80RegisterClass);
13057     case 'y':   // MMX_REGS if MMX allowed.
13058       if (!Subtarget->hasMMX()) break;
13059       return std::make_pair(0U, X86::VR64RegisterClass);
13060     case 'Y':   // SSE_REGS if SSE2 allowed
13061       if (!Subtarget->hasXMMInt()) break;
13062       // FALL THROUGH.
13063     case 'x':   // SSE_REGS if SSE1 allowed
13064       if (!Subtarget->hasXMM()) break;
13065
13066       switch (VT.getSimpleVT().SimpleTy) {
13067       default: break;
13068       // Scalar SSE types.
13069       case MVT::f32:
13070       case MVT::i32:
13071         return std::make_pair(0U, X86::FR32RegisterClass);
13072       case MVT::f64:
13073       case MVT::i64:
13074         return std::make_pair(0U, X86::FR64RegisterClass);
13075       // Vector types.
13076       case MVT::v16i8:
13077       case MVT::v8i16:
13078       case MVT::v4i32:
13079       case MVT::v2i64:
13080       case MVT::v4f32:
13081       case MVT::v2f64:
13082         return std::make_pair(0U, X86::VR128RegisterClass);
13083       }
13084       break;
13085     }
13086   }
13087
13088   // Use the default implementation in TargetLowering to convert the register
13089   // constraint into a member of a register class.
13090   std::pair<unsigned, const TargetRegisterClass*> Res;
13091   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
13092
13093   // Not found as a standard register?
13094   if (Res.second == 0) {
13095     // Map st(0) -> st(7) -> ST0
13096     if (Constraint.size() == 7 && Constraint[0] == '{' &&
13097         tolower(Constraint[1]) == 's' &&
13098         tolower(Constraint[2]) == 't' &&
13099         Constraint[3] == '(' &&
13100         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
13101         Constraint[5] == ')' &&
13102         Constraint[6] == '}') {
13103
13104       Res.first = X86::ST0+Constraint[4]-'0';
13105       Res.second = X86::RFP80RegisterClass;
13106       return Res;
13107     }
13108
13109     // GCC allows "st(0)" to be called just plain "st".
13110     if (StringRef("{st}").equals_lower(Constraint)) {
13111       Res.first = X86::ST0;
13112       Res.second = X86::RFP80RegisterClass;
13113       return Res;
13114     }
13115
13116     // flags -> EFLAGS
13117     if (StringRef("{flags}").equals_lower(Constraint)) {
13118       Res.first = X86::EFLAGS;
13119       Res.second = X86::CCRRegisterClass;
13120       return Res;
13121     }
13122
13123     // 'A' means EAX + EDX.
13124     if (Constraint == "A") {
13125       Res.first = X86::EAX;
13126       Res.second = X86::GR32_ADRegisterClass;
13127       return Res;
13128     }
13129     return Res;
13130   }
13131
13132   // Otherwise, check to see if this is a register class of the wrong value
13133   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
13134   // turn into {ax},{dx}.
13135   if (Res.second->hasType(VT))
13136     return Res;   // Correct type already, nothing to do.
13137
13138   // All of the single-register GCC register classes map their values onto
13139   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
13140   // really want an 8-bit or 32-bit register, map to the appropriate register
13141   // class and return the appropriate register.
13142   if (Res.second == X86::GR16RegisterClass) {
13143     if (VT == MVT::i8) {
13144       unsigned DestReg = 0;
13145       switch (Res.first) {
13146       default: break;
13147       case X86::AX: DestReg = X86::AL; break;
13148       case X86::DX: DestReg = X86::DL; break;
13149       case X86::CX: DestReg = X86::CL; break;
13150       case X86::BX: DestReg = X86::BL; break;
13151       }
13152       if (DestReg) {
13153         Res.first = DestReg;
13154         Res.second = X86::GR8RegisterClass;
13155       }
13156     } else if (VT == MVT::i32) {
13157       unsigned DestReg = 0;
13158       switch (Res.first) {
13159       default: break;
13160       case X86::AX: DestReg = X86::EAX; break;
13161       case X86::DX: DestReg = X86::EDX; break;
13162       case X86::CX: DestReg = X86::ECX; break;
13163       case X86::BX: DestReg = X86::EBX; break;
13164       case X86::SI: DestReg = X86::ESI; break;
13165       case X86::DI: DestReg = X86::EDI; break;
13166       case X86::BP: DestReg = X86::EBP; break;
13167       case X86::SP: DestReg = X86::ESP; break;
13168       }
13169       if (DestReg) {
13170         Res.first = DestReg;
13171         Res.second = X86::GR32RegisterClass;
13172       }
13173     } else if (VT == MVT::i64) {
13174       unsigned DestReg = 0;
13175       switch (Res.first) {
13176       default: break;
13177       case X86::AX: DestReg = X86::RAX; break;
13178       case X86::DX: DestReg = X86::RDX; break;
13179       case X86::CX: DestReg = X86::RCX; break;
13180       case X86::BX: DestReg = X86::RBX; break;
13181       case X86::SI: DestReg = X86::RSI; break;
13182       case X86::DI: DestReg = X86::RDI; break;
13183       case X86::BP: DestReg = X86::RBP; break;
13184       case X86::SP: DestReg = X86::RSP; break;
13185       }
13186       if (DestReg) {
13187         Res.first = DestReg;
13188         Res.second = X86::GR64RegisterClass;
13189       }
13190     }
13191   } else if (Res.second == X86::FR32RegisterClass ||
13192              Res.second == X86::FR64RegisterClass ||
13193              Res.second == X86::VR128RegisterClass) {
13194     // Handle references to XMM physical registers that got mapped into the
13195     // wrong class.  This can happen with constraints like {xmm0} where the
13196     // target independent register mapper will just pick the first match it can
13197     // find, ignoring the required type.
13198     if (VT == MVT::f32)
13199       Res.second = X86::FR32RegisterClass;
13200     else if (VT == MVT::f64)
13201       Res.second = X86::FR64RegisterClass;
13202     else if (X86::VR128RegisterClass->hasType(VT))
13203       Res.second = X86::VR128RegisterClass;
13204   }
13205
13206   return Res;
13207 }