[AVX] Implement BUILD_VECTOR lowering for 256-bit vectors. For
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 static cl::opt<bool>
60 Disable256Bit("disable-256bit", cl::Hidden,
61               cl::desc("Disable use of 256-bit vectors"));
62
63 // Forward declarations.
64 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65                        SDValue V2);
66
67 static SDValue Insert128BitVector(SDValue Result,
68                                   SDValue Vec,
69                                   SDValue Idx,
70                                   SelectionDAG &DAG,
71                                   DebugLoc dl);
72
73 static SDValue Extract128BitVector(SDValue Vec,
74                                    SDValue Idx,
75                                    SelectionDAG &DAG,
76                                    DebugLoc dl);
77
78 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
79
80
81 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
82 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
83 /// simple subregister reference.
84 static SDValue Extract128BitVector(SDValue Vec,
85                                    SDValue Idx,
86                                    SelectionDAG &DAG,
87                                    DebugLoc dl) {
88   EVT VT = Vec.getValueType();
89   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
90
91   EVT ElVT = VT.getVectorElementType();
92
93   int Factor = VT.getSizeInBits() / 128;
94
95   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
96                                   ElVT,
97                                   VT.getVectorNumElements() / Factor);
98
99   // Extract from UNDEF is UNDEF.
100   if (Vec.getOpcode() == ISD::UNDEF)
101     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
102
103   if (isa<ConstantSDNode>(Idx)) {
104     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
105
106     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
107     // we can match to VEXTRACTF128.
108     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
109
110     // This is the index of the first element of the 128-bit chunk
111     // we want.
112     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
113                                  * ElemsPerChunk);
114
115     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
116
117     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
118                                  VecIdx);
119
120     return Result;
121   }
122
123   return SDValue();
124 }
125
126 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
127 /// sets things up to match to an AVX VINSERTF128 instruction or a
128 /// simple superregister reference.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setShiftAmountType(MVT::i8);
225   setBooleanContents(ZeroOrOneBooleanContent);
226   setSchedulingPreference(Sched::RegPressure);
227   setStackPointerRegisterToSaveRestore(X86StackPtr);
228
229   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
230     // Setup Windows compiler runtime calls.
231     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
232     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
233     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
234     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
235     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
236     setLibcallCallingConv(RTLIB::UDIV_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   if (Subtarget->is64Bit())
549     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
550   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
551     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
552   else
553     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
554
555   if (!UseSoftFloat && X86ScalarSSEf64) {
556     // f32 and f64 use SSE.
557     // Set up the FP register classes.
558     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
559     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
560
561     // Use ANDPD to simulate FABS.
562     setOperationAction(ISD::FABS , MVT::f64, Custom);
563     setOperationAction(ISD::FABS , MVT::f32, Custom);
564
565     // Use XORP to simulate FNEG.
566     setOperationAction(ISD::FNEG , MVT::f64, Custom);
567     setOperationAction(ISD::FNEG , MVT::f32, Custom);
568
569     // Use ANDPD and ORPD to simulate FCOPYSIGN.
570     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
571     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
572
573     // We don't support sin/cos/fmod
574     setOperationAction(ISD::FSIN , MVT::f64, Expand);
575     setOperationAction(ISD::FCOS , MVT::f64, Expand);
576     setOperationAction(ISD::FSIN , MVT::f32, Expand);
577     setOperationAction(ISD::FCOS , MVT::f32, Expand);
578
579     // Expand FP immediates into loads from the stack, except for the special
580     // cases we handle.
581     addLegalFPImmediate(APFloat(+0.0)); // xorpd
582     addLegalFPImmediate(APFloat(+0.0f)); // xorps
583   } else if (!UseSoftFloat && X86ScalarSSEf32) {
584     // Use SSE for f32, x87 for f64.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
587     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
588
589     // Use ANDPS to simulate FABS.
590     setOperationAction(ISD::FABS , MVT::f32, Custom);
591
592     // Use XORP to simulate FNEG.
593     setOperationAction(ISD::FNEG , MVT::f32, Custom);
594
595     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
596
597     // Use ANDPS and ORPS to simulate FCOPYSIGN.
598     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
600
601     // We don't support sin/cos/fmod
602     setOperationAction(ISD::FSIN , MVT::f32, Expand);
603     setOperationAction(ISD::FCOS , MVT::f32, Expand);
604
605     // Special cases we handle for FP constants.
606     addLegalFPImmediate(APFloat(+0.0f)); // xorps
607     addLegalFPImmediate(APFloat(+0.0)); // FLD0
608     addLegalFPImmediate(APFloat(+1.0)); // FLD1
609     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611
612     if (!UnsafeFPMath) {
613       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
614       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
615     }
616   } else if (!UseSoftFloat) {
617     // f32 and f64 in x87.
618     // Set up the FP register classes.
619     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
620     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
621
622     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
623     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
624     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
626
627     if (!UnsafeFPMath) {
628       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
629       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
630     }
631     addLegalFPImmediate(APFloat(+0.0)); // FLD0
632     addLegalFPImmediate(APFloat(+1.0)); // FLD1
633     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
634     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
635     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
639   }
640
641   // Long double always uses X87.
642   if (!UseSoftFloat) {
643     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
645     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
646     {
647       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648       addLegalFPImmediate(TmpFlt);  // FLD0
649       TmpFlt.changeSign();
650       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
651
652       bool ignored;
653       APFloat TmpFlt2(+1.0);
654       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
655                       &ignored);
656       addLegalFPImmediate(TmpFlt2);  // FLD1
657       TmpFlt2.changeSign();
658       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
659     }
660
661     if (!UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
663       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
664     }
665   }
666
667   // Always use a library call for pow.
668   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
669   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
670   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
671
672   setOperationAction(ISD::FLOG, MVT::f80, Expand);
673   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
674   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
675   setOperationAction(ISD::FEXP, MVT::f80, Expand);
676   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
677
678   // First set operation action for all vector types to either promote
679   // (for widening) or expand (for scalarization). Then we will selectively
680   // turn on ones that can be effectively codegen'd.
681   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
682        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
683     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
698     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
700     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
701     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
733     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
737     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
738          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
739       setTruncStoreAction((MVT::SimpleValueType)VT,
740                           (MVT::SimpleValueType)InnerVT, Expand);
741     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
742     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
743     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
744   }
745
746   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
747   // with -msoft-float, disable use of MMX as well.
748   if (!UseSoftFloat && Subtarget->hasMMX()) {
749     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
750     // No operations on x86mmx supported, everything uses intrinsics.
751   }
752
753   // MMX-sized vectors (other than x86mmx) are expected to be expanded
754   // into smaller operations.
755   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
756   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
757   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
758   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
759   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
760   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
761   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
762   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
763   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
764   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
765   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
766   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
767   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
769   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
770   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
771   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
772   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
773   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
774   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
775   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
776   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
777   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
778   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
779   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
780   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
781   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
782   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
783   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
784
785   if (!UseSoftFloat && Subtarget->hasXMM()) {
786     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
787
788     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
789     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
790     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
791     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
792     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
793     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
794     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
795     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
796     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
797     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
798     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
799     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
800   }
801
802   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
803     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
804
805     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
806     // registers cannot be used even for integer operations.
807     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
808     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
809     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
810     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
811
812     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
813     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
814     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
815     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
816     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
817     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
818     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
819     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
820     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
821     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
822     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
825     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
827     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
828
829     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
830     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
831     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
832     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
841     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
842     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
843     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
845
846     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
847     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
848       EVT VT = (MVT::SimpleValueType)i;
849       // Do not attempt to custom lower non-power-of-2 vectors
850       if (!isPowerOf2_32(VT.getVectorNumElements()))
851         continue;
852       // Do not attempt to custom lower non-128-bit vectors
853       if (!VT.is128BitVector())
854         continue;
855       setOperationAction(ISD::BUILD_VECTOR,
856                          VT.getSimpleVT().SimpleTy, Custom);
857       setOperationAction(ISD::VECTOR_SHUFFLE,
858                          VT.getSimpleVT().SimpleTy, Custom);
859       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
860                          VT.getSimpleVT().SimpleTy, Custom);
861     }
862
863     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
864     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
865     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
866     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
867     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
868     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
869
870     if (Subtarget->is64Bit()) {
871       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
872       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
873     }
874
875     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
876     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
877       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
878       EVT VT = SVT;
879
880       // Do not attempt to promote non-128-bit vectors
881       if (!VT.is128BitVector())
882         continue;
883
884       setOperationAction(ISD::AND,    SVT, Promote);
885       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
886       setOperationAction(ISD::OR,     SVT, Promote);
887       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
888       setOperationAction(ISD::XOR,    SVT, Promote);
889       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
890       setOperationAction(ISD::LOAD,   SVT, Promote);
891       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
892       setOperationAction(ISD::SELECT, SVT, Promote);
893       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
894     }
895
896     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
897
898     // Custom lower v2i64 and v2f64 selects.
899     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
900     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
901     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
902     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
903
904     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
905     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
906   }
907
908   if (Subtarget->hasSSE41()) {
909     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
910     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
911     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
912     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
913     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
914     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
915     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
916     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
917     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
918     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
919
920     // FIXME: Do we need to handle scalar-to-vector here?
921     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
922
923     // Can turn SHL into an integer multiply.
924     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
925     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
926
927     // i8 and i16 vectors are custom , because the source register and source
928     // source memory operand types are not the same width.  f32 vectors are
929     // custom since the immediate controlling the insert encodes additional
930     // information.
931     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
932     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
933     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
934     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
935
936     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
937     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
938     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
939     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
940
941     if (Subtarget->is64Bit()) {
942       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
944     }
945   }
946
947   if (Subtarget->hasSSE42())
948     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
949
950   if (!UseSoftFloat && Subtarget->hasAVX()) {
951     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
952     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
953     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
954     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
955     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
956
957     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
958     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
959     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
960     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
961
962     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
963     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
964     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
965     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
966     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
967     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
968
969     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
970     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
971     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
972     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
973     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
974     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
975
976     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
977     // insert_vector_elt extract_subvector and extract_vector_elt for
978     // 256-bit types.
979     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
980          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
981          ++i) {
982       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
983       // Do not attempt to custom lower non-256-bit vectors
984       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
985           || (MVT(VT).getSizeInBits() < 256))
986         continue;
987       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
988       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
992     }
993     // Custom-lower insert_subvector and extract_subvector based on
994     // the result type.
995     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
996          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
997          ++i) {
998       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
999       // Do not attempt to custom lower non-256-bit vectors
1000       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1001         continue;
1002
1003       if (MVT(VT).getSizeInBits() == 128) {
1004         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1005       }
1006       else if (MVT(VT).getSizeInBits() == 256) {
1007         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1008       }
1009     }
1010
1011     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1012     // Don't promote loads because we need them for VPERM vector index versions.
1013
1014     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1015          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1016          VT++) {
1017       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1018           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1019         continue;
1020       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1021       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1022       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1023       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1024       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1025       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1026       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1027       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1028       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1029       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1030     }
1031   }
1032
1033   // We want to custom lower some of our intrinsics.
1034   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1035
1036
1037   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1038   // handle type legalization for these operations here.
1039   //
1040   // FIXME: We really should do custom legalization for addition and
1041   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1042   // than generic legalization for 64-bit multiplication-with-overflow, though.
1043   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1044     // Add/Sub/Mul with overflow operations are custom lowered.
1045     MVT VT = IntVTs[i];
1046     setOperationAction(ISD::SADDO, VT, Custom);
1047     setOperationAction(ISD::UADDO, VT, Custom);
1048     setOperationAction(ISD::SSUBO, VT, Custom);
1049     setOperationAction(ISD::USUBO, VT, Custom);
1050     setOperationAction(ISD::SMULO, VT, Custom);
1051     setOperationAction(ISD::UMULO, VT, Custom);
1052   }
1053
1054   // There are no 8-bit 3-address imul/mul instructions
1055   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1056   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1057
1058   if (!Subtarget->is64Bit()) {
1059     // These libcalls are not available in 32-bit.
1060     setLibcallName(RTLIB::SHL_I128, 0);
1061     setLibcallName(RTLIB::SRL_I128, 0);
1062     setLibcallName(RTLIB::SRA_I128, 0);
1063   }
1064
1065   // We have target-specific dag combine patterns for the following nodes:
1066   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1067   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1068   setTargetDAGCombine(ISD::BUILD_VECTOR);
1069   setTargetDAGCombine(ISD::SELECT);
1070   setTargetDAGCombine(ISD::SHL);
1071   setTargetDAGCombine(ISD::SRA);
1072   setTargetDAGCombine(ISD::SRL);
1073   setTargetDAGCombine(ISD::OR);
1074   setTargetDAGCombine(ISD::AND);
1075   setTargetDAGCombine(ISD::ADD);
1076   setTargetDAGCombine(ISD::SUB);
1077   setTargetDAGCombine(ISD::STORE);
1078   setTargetDAGCombine(ISD::ZERO_EXTEND);
1079   if (Subtarget->is64Bit())
1080     setTargetDAGCombine(ISD::MUL);
1081
1082   computeRegisterProperties();
1083
1084   // On Darwin, -Os means optimize for size without hurting performance,
1085   // do not reduce the limit.
1086   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1087   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1088   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1089   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1090   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1091   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1092   setPrefLoopAlignment(16);
1093   benefitFromCodePlacementOpt = true;
1094 }
1095
1096
1097 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1098   return MVT::i8;
1099 }
1100
1101
1102 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1103 /// the desired ByVal argument alignment.
1104 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1105   if (MaxAlign == 16)
1106     return;
1107   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1108     if (VTy->getBitWidth() == 128)
1109       MaxAlign = 16;
1110   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1111     unsigned EltAlign = 0;
1112     getMaxByValAlign(ATy->getElementType(), EltAlign);
1113     if (EltAlign > MaxAlign)
1114       MaxAlign = EltAlign;
1115   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1116     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1117       unsigned EltAlign = 0;
1118       getMaxByValAlign(STy->getElementType(i), EltAlign);
1119       if (EltAlign > MaxAlign)
1120         MaxAlign = EltAlign;
1121       if (MaxAlign == 16)
1122         break;
1123     }
1124   }
1125   return;
1126 }
1127
1128 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1129 /// function arguments in the caller parameter area. For X86, aggregates
1130 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1131 /// are at 4-byte boundaries.
1132 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1133   if (Subtarget->is64Bit()) {
1134     // Max of 8 and alignment of type.
1135     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1136     if (TyAlign > 8)
1137       return TyAlign;
1138     return 8;
1139   }
1140
1141   unsigned Align = 4;
1142   if (Subtarget->hasXMM())
1143     getMaxByValAlign(Ty, Align);
1144   return Align;
1145 }
1146
1147 /// getOptimalMemOpType - Returns the target specific optimal type for load
1148 /// and store operations as a result of memset, memcpy, and memmove
1149 /// lowering. If DstAlign is zero that means it's safe to destination
1150 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1151 /// means there isn't a need to check it against alignment requirement,
1152 /// probably because the source does not need to be loaded. If
1153 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1154 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1155 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1156 /// constant so it does not need to be loaded.
1157 /// It returns EVT::Other if the type should be determined using generic
1158 /// target-independent logic.
1159 EVT
1160 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1161                                        unsigned DstAlign, unsigned SrcAlign,
1162                                        bool NonScalarIntSafe,
1163                                        bool MemcpyStrSrc,
1164                                        MachineFunction &MF) const {
1165   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1166   // linux.  This is because the stack realignment code can't handle certain
1167   // cases like PR2962.  This should be removed when PR2962 is fixed.
1168   const Function *F = MF.getFunction();
1169   if (NonScalarIntSafe &&
1170       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1171     if (Size >= 16 &&
1172         (Subtarget->isUnalignedMemAccessFast() ||
1173          ((DstAlign == 0 || DstAlign >= 16) &&
1174           (SrcAlign == 0 || SrcAlign >= 16))) &&
1175         Subtarget->getStackAlignment() >= 16) {
1176       if (Subtarget->hasSSE2())
1177         return MVT::v4i32;
1178       if (Subtarget->hasSSE1())
1179         return MVT::v4f32;
1180     } else if (!MemcpyStrSrc && Size >= 8 &&
1181                !Subtarget->is64Bit() &&
1182                Subtarget->getStackAlignment() >= 8 &&
1183                Subtarget->hasXMMInt()) {
1184       // Do not use f64 to lower memcpy if source is string constant. It's
1185       // better to use i32 to avoid the loads.
1186       return MVT::f64;
1187     }
1188   }
1189   if (Subtarget->is64Bit() && Size >= 8)
1190     return MVT::i64;
1191   return MVT::i32;
1192 }
1193
1194 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1195 /// current function.  The returned value is a member of the
1196 /// MachineJumpTableInfo::JTEntryKind enum.
1197 unsigned X86TargetLowering::getJumpTableEncoding() const {
1198   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1199   // symbol.
1200   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1201       Subtarget->isPICStyleGOT())
1202     return MachineJumpTableInfo::EK_Custom32;
1203
1204   // Otherwise, use the normal jump table encoding heuristics.
1205   return TargetLowering::getJumpTableEncoding();
1206 }
1207
1208 const MCExpr *
1209 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1210                                              const MachineBasicBlock *MBB,
1211                                              unsigned uid,MCContext &Ctx) const{
1212   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1213          Subtarget->isPICStyleGOT());
1214   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1215   // entries.
1216   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1217                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1218 }
1219
1220 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1221 /// jumptable.
1222 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1223                                                     SelectionDAG &DAG) const {
1224   if (!Subtarget->is64Bit())
1225     // This doesn't have DebugLoc associated with it, but is not really the
1226     // same as a Register.
1227     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1228   return Table;
1229 }
1230
1231 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1232 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1233 /// MCExpr.
1234 const MCExpr *X86TargetLowering::
1235 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1236                              MCContext &Ctx) const {
1237   // X86-64 uses RIP relative addressing based on the jump table label.
1238   if (Subtarget->isPICStyleRIPRel())
1239     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1240
1241   // Otherwise, the reference is relative to the PIC base.
1242   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1243 }
1244
1245 /// getFunctionAlignment - Return the Log2 alignment of this function.
1246 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1247   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1248 }
1249
1250 // FIXME: Why this routine is here? Move to RegInfo!
1251 std::pair<const TargetRegisterClass*, uint8_t>
1252 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1253   const TargetRegisterClass *RRC = 0;
1254   uint8_t Cost = 1;
1255   switch (VT.getSimpleVT().SimpleTy) {
1256   default:
1257     return TargetLowering::findRepresentativeClass(VT);
1258   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1259     RRC = (Subtarget->is64Bit()
1260            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1261     break;
1262   case MVT::x86mmx:
1263     RRC = X86::VR64RegisterClass;
1264     break;
1265   case MVT::f32: case MVT::f64:
1266   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1267   case MVT::v4f32: case MVT::v2f64:
1268   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1269   case MVT::v4f64:
1270     RRC = X86::VR128RegisterClass;
1271     break;
1272   }
1273   return std::make_pair(RRC, Cost);
1274 }
1275
1276 // FIXME: Why this routine is here? Move to RegInfo!
1277 unsigned
1278 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1279                                        MachineFunction &MF) const {
1280   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1281
1282   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1283   switch (RC->getID()) {
1284   default:
1285     return 0;
1286   case X86::GR32RegClassID:
1287     return 4 - FPDiff;
1288   case X86::GR64RegClassID:
1289     return 8 - FPDiff;
1290   case X86::VR128RegClassID:
1291     return Subtarget->is64Bit() ? 10 : 4;
1292   case X86::VR64RegClassID:
1293     return 4;
1294   }
1295 }
1296
1297 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1298                                                unsigned &Offset) const {
1299   if (!Subtarget->isTargetLinux())
1300     return false;
1301
1302   if (Subtarget->is64Bit()) {
1303     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1304     Offset = 0x28;
1305     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1306       AddressSpace = 256;
1307     else
1308       AddressSpace = 257;
1309   } else {
1310     // %gs:0x14 on i386
1311     Offset = 0x14;
1312     AddressSpace = 256;
1313   }
1314   return true;
1315 }
1316
1317
1318 //===----------------------------------------------------------------------===//
1319 //               Return Value Calling Convention Implementation
1320 //===----------------------------------------------------------------------===//
1321
1322 #include "X86GenCallingConv.inc"
1323
1324 bool
1325 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1326                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1327                         LLVMContext &Context) const {
1328   SmallVector<CCValAssign, 16> RVLocs;
1329   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1330                  RVLocs, Context);
1331   return CCInfo.CheckReturn(Outs, RetCC_X86);
1332 }
1333
1334 SDValue
1335 X86TargetLowering::LowerReturn(SDValue Chain,
1336                                CallingConv::ID CallConv, bool isVarArg,
1337                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1338                                const SmallVectorImpl<SDValue> &OutVals,
1339                                DebugLoc dl, SelectionDAG &DAG) const {
1340   MachineFunction &MF = DAG.getMachineFunction();
1341   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1342
1343   SmallVector<CCValAssign, 16> RVLocs;
1344   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1345                  RVLocs, *DAG.getContext());
1346   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1347
1348   // Add the regs to the liveout set for the function.
1349   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1350   for (unsigned i = 0; i != RVLocs.size(); ++i)
1351     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1352       MRI.addLiveOut(RVLocs[i].getLocReg());
1353
1354   SDValue Flag;
1355
1356   SmallVector<SDValue, 6> RetOps;
1357   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1358   // Operand #1 = Bytes To Pop
1359   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1360                    MVT::i16));
1361
1362   // Copy the result values into the output registers.
1363   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1364     CCValAssign &VA = RVLocs[i];
1365     assert(VA.isRegLoc() && "Can only return in registers!");
1366     SDValue ValToCopy = OutVals[i];
1367     EVT ValVT = ValToCopy.getValueType();
1368
1369     // If this is x86-64, and we disabled SSE, we can't return FP values,
1370     // or SSE or MMX vectors.
1371     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1372          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1373           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1374       report_fatal_error("SSE register return with SSE disabled");
1375     }
1376     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1377     // llvm-gcc has never done it right and no one has noticed, so this
1378     // should be OK for now.
1379     if (ValVT == MVT::f64 &&
1380         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1381       report_fatal_error("SSE2 register return with SSE2 disabled");
1382
1383     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1384     // the RET instruction and handled by the FP Stackifier.
1385     if (VA.getLocReg() == X86::ST0 ||
1386         VA.getLocReg() == X86::ST1) {
1387       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1388       // change the value to the FP stack register class.
1389       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1390         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1391       RetOps.push_back(ValToCopy);
1392       // Don't emit a copytoreg.
1393       continue;
1394     }
1395
1396     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1397     // which is returned in RAX / RDX.
1398     if (Subtarget->is64Bit()) {
1399       if (ValVT == MVT::x86mmx) {
1400         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1401           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1402           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1403                                   ValToCopy);
1404           // If we don't have SSE2 available, convert to v4f32 so the generated
1405           // register is legal.
1406           if (!Subtarget->hasSSE2())
1407             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1408         }
1409       }
1410     }
1411
1412     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1413     Flag = Chain.getValue(1);
1414   }
1415
1416   // The x86-64 ABI for returning structs by value requires that we copy
1417   // the sret argument into %rax for the return. We saved the argument into
1418   // a virtual register in the entry block, so now we copy the value out
1419   // and into %rax.
1420   if (Subtarget->is64Bit() &&
1421       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1422     MachineFunction &MF = DAG.getMachineFunction();
1423     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1424     unsigned Reg = FuncInfo->getSRetReturnReg();
1425     assert(Reg &&
1426            "SRetReturnReg should have been set in LowerFormalArguments().");
1427     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1428
1429     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1430     Flag = Chain.getValue(1);
1431
1432     // RAX now acts like a return value.
1433     MRI.addLiveOut(X86::RAX);
1434   }
1435
1436   RetOps[0] = Chain;  // Update chain.
1437
1438   // Add the flag if we have it.
1439   if (Flag.getNode())
1440     RetOps.push_back(Flag);
1441
1442   return DAG.getNode(X86ISD::RET_FLAG, dl,
1443                      MVT::Other, &RetOps[0], RetOps.size());
1444 }
1445
1446 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1447   if (N->getNumValues() != 1)
1448     return false;
1449   if (!N->hasNUsesOfValue(1, 0))
1450     return false;
1451
1452   SDNode *Copy = *N->use_begin();
1453   if (Copy->getOpcode() != ISD::CopyToReg &&
1454       Copy->getOpcode() != ISD::FP_EXTEND)
1455     return false;
1456
1457   bool HasRet = false;
1458   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1459        UI != UE; ++UI) {
1460     if (UI->getOpcode() != X86ISD::RET_FLAG)
1461       return false;
1462     HasRet = true;
1463   }
1464
1465   return HasRet;
1466 }
1467
1468 /// LowerCallResult - Lower the result values of a call into the
1469 /// appropriate copies out of appropriate physical registers.
1470 ///
1471 SDValue
1472 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1473                                    CallingConv::ID CallConv, bool isVarArg,
1474                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1475                                    DebugLoc dl, SelectionDAG &DAG,
1476                                    SmallVectorImpl<SDValue> &InVals) const {
1477
1478   // Assign locations to each value returned by this call.
1479   SmallVector<CCValAssign, 16> RVLocs;
1480   bool Is64Bit = Subtarget->is64Bit();
1481   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1482                  RVLocs, *DAG.getContext());
1483   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1484
1485   // Copy all of the result registers out of their specified physreg.
1486   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1487     CCValAssign &VA = RVLocs[i];
1488     EVT CopyVT = VA.getValVT();
1489
1490     // If this is x86-64, and we disabled SSE, we can't return FP values
1491     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1492         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1493       report_fatal_error("SSE register return with SSE disabled");
1494     }
1495
1496     SDValue Val;
1497
1498     // If this is a call to a function that returns an fp value on the floating
1499     // point stack, we must guarantee the the value is popped from the stack, so
1500     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1501     // if the return value is not used. We use the FpGET_ST0 instructions
1502     // instead.
1503     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1504       // If we prefer to use the value in xmm registers, copy it out as f80 and
1505       // use a truncate to move it from fp stack reg to xmm reg.
1506       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1507       bool isST0 = VA.getLocReg() == X86::ST0;
1508       unsigned Opc = 0;
1509       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1510       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1511       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1512       SDValue Ops[] = { Chain, InFlag };
1513       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1514                                          Ops, 2), 1);
1515       Val = Chain.getValue(0);
1516
1517       // Round the f80 to the right size, which also moves it to the appropriate
1518       // xmm register.
1519       if (CopyVT != VA.getValVT())
1520         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1521                           // This truncation won't change the value.
1522                           DAG.getIntPtrConstant(1));
1523     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1524       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1525       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1526         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1527                                    MVT::v2i64, InFlag).getValue(1);
1528         Val = Chain.getValue(0);
1529         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1530                           Val, DAG.getConstant(0, MVT::i64));
1531       } else {
1532         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1533                                    MVT::i64, InFlag).getValue(1);
1534         Val = Chain.getValue(0);
1535       }
1536       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1537     } else {
1538       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1539                                  CopyVT, InFlag).getValue(1);
1540       Val = Chain.getValue(0);
1541     }
1542     InFlag = Chain.getValue(2);
1543     InVals.push_back(Val);
1544   }
1545
1546   return Chain;
1547 }
1548
1549
1550 //===----------------------------------------------------------------------===//
1551 //                C & StdCall & Fast Calling Convention implementation
1552 //===----------------------------------------------------------------------===//
1553 //  StdCall calling convention seems to be standard for many Windows' API
1554 //  routines and around. It differs from C calling convention just a little:
1555 //  callee should clean up the stack, not caller. Symbols should be also
1556 //  decorated in some fancy way :) It doesn't support any vector arguments.
1557 //  For info on fast calling convention see Fast Calling Convention (tail call)
1558 //  implementation LowerX86_32FastCCCallTo.
1559
1560 /// CallIsStructReturn - Determines whether a call uses struct return
1561 /// semantics.
1562 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1563   if (Outs.empty())
1564     return false;
1565
1566   return Outs[0].Flags.isSRet();
1567 }
1568
1569 /// ArgsAreStructReturn - Determines whether a function uses struct
1570 /// return semantics.
1571 static bool
1572 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1573   if (Ins.empty())
1574     return false;
1575
1576   return Ins[0].Flags.isSRet();
1577 }
1578
1579 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1580 /// by "Src" to address "Dst" with size and alignment information specified by
1581 /// the specific parameter attribute. The copy will be passed as a byval
1582 /// function parameter.
1583 static SDValue
1584 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1585                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1586                           DebugLoc dl) {
1587   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1588
1589   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1590                        /*isVolatile*/false, /*AlwaysInline=*/true,
1591                        MachinePointerInfo(), MachinePointerInfo());
1592 }
1593
1594 /// IsTailCallConvention - Return true if the calling convention is one that
1595 /// supports tail call optimization.
1596 static bool IsTailCallConvention(CallingConv::ID CC) {
1597   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1598 }
1599
1600 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1601 /// a tailcall target by changing its ABI.
1602 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1603   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1604 }
1605
1606 SDValue
1607 X86TargetLowering::LowerMemArgument(SDValue Chain,
1608                                     CallingConv::ID CallConv,
1609                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1610                                     DebugLoc dl, SelectionDAG &DAG,
1611                                     const CCValAssign &VA,
1612                                     MachineFrameInfo *MFI,
1613                                     unsigned i) const {
1614   // Create the nodes corresponding to a load from this parameter slot.
1615   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1616   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1617   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1618   EVT ValVT;
1619
1620   // If value is passed by pointer we have address passed instead of the value
1621   // itself.
1622   if (VA.getLocInfo() == CCValAssign::Indirect)
1623     ValVT = VA.getLocVT();
1624   else
1625     ValVT = VA.getValVT();
1626
1627   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1628   // changed with more analysis.
1629   // In case of tail call optimization mark all arguments mutable. Since they
1630   // could be overwritten by lowering of arguments in case of a tail call.
1631   if (Flags.isByVal()) {
1632     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1633                                     VA.getLocMemOffset(), isImmutable);
1634     return DAG.getFrameIndex(FI, getPointerTy());
1635   } else {
1636     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1637                                     VA.getLocMemOffset(), isImmutable);
1638     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1639     return DAG.getLoad(ValVT, dl, Chain, FIN,
1640                        MachinePointerInfo::getFixedStack(FI),
1641                        false, false, 0);
1642   }
1643 }
1644
1645 SDValue
1646 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1647                                         CallingConv::ID CallConv,
1648                                         bool isVarArg,
1649                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1650                                         DebugLoc dl,
1651                                         SelectionDAG &DAG,
1652                                         SmallVectorImpl<SDValue> &InVals)
1653                                           const {
1654   MachineFunction &MF = DAG.getMachineFunction();
1655   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1656
1657   const Function* Fn = MF.getFunction();
1658   if (Fn->hasExternalLinkage() &&
1659       Subtarget->isTargetCygMing() &&
1660       Fn->getName() == "main")
1661     FuncInfo->setForceFramePointer(true);
1662
1663   MachineFrameInfo *MFI = MF.getFrameInfo();
1664   bool Is64Bit = Subtarget->is64Bit();
1665   bool IsWin64 = Subtarget->isTargetWin64();
1666
1667   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1668          "Var args not supported with calling convention fastcc or ghc");
1669
1670   // Assign locations to all of the incoming arguments.
1671   SmallVector<CCValAssign, 16> ArgLocs;
1672   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1673                  ArgLocs, *DAG.getContext());
1674
1675   // Allocate shadow area for Win64
1676   if (IsWin64) {
1677     CCInfo.AllocateStack(32, 8);
1678   }
1679
1680   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1681
1682   unsigned LastVal = ~0U;
1683   SDValue ArgValue;
1684   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1685     CCValAssign &VA = ArgLocs[i];
1686     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1687     // places.
1688     assert(VA.getValNo() != LastVal &&
1689            "Don't support value assigned to multiple locs yet");
1690     LastVal = VA.getValNo();
1691
1692     if (VA.isRegLoc()) {
1693       EVT RegVT = VA.getLocVT();
1694       TargetRegisterClass *RC = NULL;
1695       if (RegVT == MVT::i32)
1696         RC = X86::GR32RegisterClass;
1697       else if (Is64Bit && RegVT == MVT::i64)
1698         RC = X86::GR64RegisterClass;
1699       else if (RegVT == MVT::f32)
1700         RC = X86::FR32RegisterClass;
1701       else if (RegVT == MVT::f64)
1702         RC = X86::FR64RegisterClass;
1703       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1704         RC = X86::VR256RegisterClass;
1705       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1706         RC = X86::VR128RegisterClass;
1707       else if (RegVT == MVT::x86mmx)
1708         RC = X86::VR64RegisterClass;
1709       else
1710         llvm_unreachable("Unknown argument type!");
1711
1712       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC, dl);
1713       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1714
1715       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1716       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1717       // right size.
1718       if (VA.getLocInfo() == CCValAssign::SExt)
1719         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1720                                DAG.getValueType(VA.getValVT()));
1721       else if (VA.getLocInfo() == CCValAssign::ZExt)
1722         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1723                                DAG.getValueType(VA.getValVT()));
1724       else if (VA.getLocInfo() == CCValAssign::BCvt)
1725         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1726
1727       if (VA.isExtInLoc()) {
1728         // Handle MMX values passed in XMM regs.
1729         if (RegVT.isVector()) {
1730           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1731                                  ArgValue);
1732         } else
1733           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1734       }
1735     } else {
1736       assert(VA.isMemLoc());
1737       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1738     }
1739
1740     // If value is passed via pointer - do a load.
1741     if (VA.getLocInfo() == CCValAssign::Indirect)
1742       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1743                              MachinePointerInfo(), false, false, 0);
1744
1745     InVals.push_back(ArgValue);
1746   }
1747
1748   // The x86-64 ABI for returning structs by value requires that we copy
1749   // the sret argument into %rax for the return. Save the argument into
1750   // a virtual register so that we can access it from the return points.
1751   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1752     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1753     unsigned Reg = FuncInfo->getSRetReturnReg();
1754     if (!Reg) {
1755       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1756       FuncInfo->setSRetReturnReg(Reg);
1757     }
1758     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1759     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1760   }
1761
1762   unsigned StackSize = CCInfo.getNextStackOffset();
1763   // Align stack specially for tail calls.
1764   if (FuncIsMadeTailCallSafe(CallConv))
1765     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1766
1767   // If the function takes variable number of arguments, make a frame index for
1768   // the start of the first vararg value... for expansion of llvm.va_start.
1769   if (isVarArg) {
1770     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1771                     CallConv != CallingConv::X86_ThisCall))) {
1772       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1773     }
1774     if (Is64Bit) {
1775       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1776
1777       // FIXME: We should really autogenerate these arrays
1778       static const unsigned GPR64ArgRegsWin64[] = {
1779         X86::RCX, X86::RDX, X86::R8,  X86::R9
1780       };
1781       static const unsigned GPR64ArgRegs64Bit[] = {
1782         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1783       };
1784       static const unsigned XMMArgRegs64Bit[] = {
1785         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1786         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1787       };
1788       const unsigned *GPR64ArgRegs;
1789       unsigned NumXMMRegs = 0;
1790
1791       if (IsWin64) {
1792         // The XMM registers which might contain var arg parameters are shadowed
1793         // in their paired GPR.  So we only need to save the GPR to their home
1794         // slots.
1795         TotalNumIntRegs = 4;
1796         GPR64ArgRegs = GPR64ArgRegsWin64;
1797       } else {
1798         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1799         GPR64ArgRegs = GPR64ArgRegs64Bit;
1800
1801         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1802       }
1803       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1804                                                        TotalNumIntRegs);
1805
1806       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1807       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1808              "SSE register cannot be used when SSE is disabled!");
1809       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1810              "SSE register cannot be used when SSE is disabled!");
1811       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1812         // Kernel mode asks for SSE to be disabled, so don't push them
1813         // on the stack.
1814         TotalNumXMMRegs = 0;
1815
1816       if (IsWin64) {
1817         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1818         // Get to the caller-allocated home save location.  Add 8 to account
1819         // for the return address.
1820         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1821         FuncInfo->setRegSaveFrameIndex(
1822           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1823         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1824       } else {
1825         // For X86-64, if there are vararg parameters that are passed via
1826         // registers, then we must store them to their spots on the stack so they
1827         // may be loaded by deferencing the result of va_next.
1828         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1829         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1830         FuncInfo->setRegSaveFrameIndex(
1831           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1832                                false));
1833       }
1834
1835       // Store the integer parameter registers.
1836       SmallVector<SDValue, 8> MemOps;
1837       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1838                                         getPointerTy());
1839       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1840       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1841         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1842                                   DAG.getIntPtrConstant(Offset));
1843         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1844                                      X86::GR64RegisterClass, dl);
1845         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1846         SDValue Store =
1847           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1848                        MachinePointerInfo::getFixedStack(
1849                          FuncInfo->getRegSaveFrameIndex(), Offset),
1850                        false, false, 0);
1851         MemOps.push_back(Store);
1852         Offset += 8;
1853       }
1854
1855       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1856         // Now store the XMM (fp + vector) parameter registers.
1857         SmallVector<SDValue, 11> SaveXMMOps;
1858         SaveXMMOps.push_back(Chain);
1859
1860         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass, dl);
1861         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1862         SaveXMMOps.push_back(ALVal);
1863
1864         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1865                                FuncInfo->getRegSaveFrameIndex()));
1866         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1867                                FuncInfo->getVarArgsFPOffset()));
1868
1869         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1870           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1871                                        X86::VR128RegisterClass, dl);
1872           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1873           SaveXMMOps.push_back(Val);
1874         }
1875         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1876                                      MVT::Other,
1877                                      &SaveXMMOps[0], SaveXMMOps.size()));
1878       }
1879
1880       if (!MemOps.empty())
1881         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1882                             &MemOps[0], MemOps.size());
1883     }
1884   }
1885
1886   // Some CCs need callee pop.
1887   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1888     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1889   } else {
1890     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1891     // If this is an sret function, the return should pop the hidden pointer.
1892     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1893       FuncInfo->setBytesToPopOnReturn(4);
1894   }
1895
1896   if (!Is64Bit) {
1897     // RegSaveFrameIndex is X86-64 only.
1898     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1899     if (CallConv == CallingConv::X86_FastCall ||
1900         CallConv == CallingConv::X86_ThisCall)
1901       // fastcc functions can't have varargs.
1902       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1903   }
1904
1905   return Chain;
1906 }
1907
1908 SDValue
1909 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1910                                     SDValue StackPtr, SDValue Arg,
1911                                     DebugLoc dl, SelectionDAG &DAG,
1912                                     const CCValAssign &VA,
1913                                     ISD::ArgFlagsTy Flags) const {
1914   unsigned LocMemOffset = VA.getLocMemOffset();
1915   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1916   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1917   if (Flags.isByVal())
1918     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1919
1920   return DAG.getStore(Chain, dl, Arg, PtrOff,
1921                       MachinePointerInfo::getStack(LocMemOffset),
1922                       false, false, 0);
1923 }
1924
1925 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1926 /// optimization is performed and it is required.
1927 SDValue
1928 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1929                                            SDValue &OutRetAddr, SDValue Chain,
1930                                            bool IsTailCall, bool Is64Bit,
1931                                            int FPDiff, DebugLoc dl) const {
1932   // Adjust the Return address stack slot.
1933   EVT VT = getPointerTy();
1934   OutRetAddr = getReturnAddressFrameIndex(DAG);
1935
1936   // Load the "old" Return address.
1937   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1938                            false, false, 0);
1939   return SDValue(OutRetAddr.getNode(), 1);
1940 }
1941
1942 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1943 /// optimization is performed and it is required (FPDiff!=0).
1944 static SDValue
1945 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1946                          SDValue Chain, SDValue RetAddrFrIdx,
1947                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1948   // Store the return address to the appropriate stack slot.
1949   if (!FPDiff) return Chain;
1950   // Calculate the new stack slot for the return address.
1951   int SlotSize = Is64Bit ? 8 : 4;
1952   int NewReturnAddrFI =
1953     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1954   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1955   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1956   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1957                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1958                        false, false, 0);
1959   return Chain;
1960 }
1961
1962 SDValue
1963 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1964                              CallingConv::ID CallConv, bool isVarArg,
1965                              bool &isTailCall,
1966                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1967                              const SmallVectorImpl<SDValue> &OutVals,
1968                              const SmallVectorImpl<ISD::InputArg> &Ins,
1969                              DebugLoc dl, SelectionDAG &DAG,
1970                              SmallVectorImpl<SDValue> &InVals) const {
1971   MachineFunction &MF = DAG.getMachineFunction();
1972   bool Is64Bit        = Subtarget->is64Bit();
1973   bool IsWin64        = Subtarget->isTargetWin64();
1974   bool IsStructRet    = CallIsStructReturn(Outs);
1975   bool IsSibcall      = false;
1976
1977   if (isTailCall) {
1978     // Check if it's really possible to do a tail call.
1979     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1980                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1981                                                    Outs, OutVals, Ins, DAG);
1982
1983     // Sibcalls are automatically detected tailcalls which do not require
1984     // ABI changes.
1985     if (!GuaranteedTailCallOpt && isTailCall)
1986       IsSibcall = true;
1987
1988     if (isTailCall)
1989       ++NumTailCalls;
1990   }
1991
1992   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1993          "Var args not supported with calling convention fastcc or ghc");
1994
1995   // Analyze operands of the call, assigning locations to each operand.
1996   SmallVector<CCValAssign, 16> ArgLocs;
1997   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1998                  ArgLocs, *DAG.getContext());
1999
2000   // Allocate shadow area for Win64
2001   if (IsWin64) {
2002     CCInfo.AllocateStack(32, 8);
2003   }
2004
2005   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2006
2007   // Get a count of how many bytes are to be pushed on the stack.
2008   unsigned NumBytes = CCInfo.getNextStackOffset();
2009   if (IsSibcall)
2010     // This is a sibcall. The memory operands are available in caller's
2011     // own caller's stack.
2012     NumBytes = 0;
2013   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2014     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2015
2016   int FPDiff = 0;
2017   if (isTailCall && !IsSibcall) {
2018     // Lower arguments at fp - stackoffset + fpdiff.
2019     unsigned NumBytesCallerPushed =
2020       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2021     FPDiff = NumBytesCallerPushed - NumBytes;
2022
2023     // Set the delta of movement of the returnaddr stackslot.
2024     // But only set if delta is greater than previous delta.
2025     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2026       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2027   }
2028
2029   if (!IsSibcall)
2030     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2031
2032   SDValue RetAddrFrIdx;
2033   // Load return adress for tail calls.
2034   if (isTailCall && FPDiff)
2035     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2036                                     Is64Bit, FPDiff, dl);
2037
2038   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2039   SmallVector<SDValue, 8> MemOpChains;
2040   SDValue StackPtr;
2041
2042   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2043   // of tail call optimization arguments are handle later.
2044   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2045     CCValAssign &VA = ArgLocs[i];
2046     EVT RegVT = VA.getLocVT();
2047     SDValue Arg = OutVals[i];
2048     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2049     bool isByVal = Flags.isByVal();
2050
2051     // Promote the value if needed.
2052     switch (VA.getLocInfo()) {
2053     default: llvm_unreachable("Unknown loc info!");
2054     case CCValAssign::Full: break;
2055     case CCValAssign::SExt:
2056       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2057       break;
2058     case CCValAssign::ZExt:
2059       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2060       break;
2061     case CCValAssign::AExt:
2062       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2063         // Special case: passing MMX values in XMM registers.
2064         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2065         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2066         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2067       } else
2068         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2069       break;
2070     case CCValAssign::BCvt:
2071       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2072       break;
2073     case CCValAssign::Indirect: {
2074       // Store the argument.
2075       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2076       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2077       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2078                            MachinePointerInfo::getFixedStack(FI),
2079                            false, false, 0);
2080       Arg = SpillSlot;
2081       break;
2082     }
2083     }
2084
2085     if (VA.isRegLoc()) {
2086       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2087       if (isVarArg && IsWin64) {
2088         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2089         // shadow reg if callee is a varargs function.
2090         unsigned ShadowReg = 0;
2091         switch (VA.getLocReg()) {
2092         case X86::XMM0: ShadowReg = X86::RCX; break;
2093         case X86::XMM1: ShadowReg = X86::RDX; break;
2094         case X86::XMM2: ShadowReg = X86::R8; break;
2095         case X86::XMM3: ShadowReg = X86::R9; break;
2096         }
2097         if (ShadowReg)
2098           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2099       }
2100     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2101       assert(VA.isMemLoc());
2102       if (StackPtr.getNode() == 0)
2103         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2104       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2105                                              dl, DAG, VA, Flags));
2106     }
2107   }
2108
2109   if (!MemOpChains.empty())
2110     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2111                         &MemOpChains[0], MemOpChains.size());
2112
2113   // Build a sequence of copy-to-reg nodes chained together with token chain
2114   // and flag operands which copy the outgoing args into registers.
2115   SDValue InFlag;
2116   // Tail call byval lowering might overwrite argument registers so in case of
2117   // tail call optimization the copies to registers are lowered later.
2118   if (!isTailCall)
2119     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2120       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2121                                RegsToPass[i].second, InFlag);
2122       InFlag = Chain.getValue(1);
2123     }
2124
2125   if (Subtarget->isPICStyleGOT()) {
2126     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2127     // GOT pointer.
2128     if (!isTailCall) {
2129       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2130                                DAG.getNode(X86ISD::GlobalBaseReg,
2131                                            DebugLoc(), getPointerTy()),
2132                                InFlag);
2133       InFlag = Chain.getValue(1);
2134     } else {
2135       // If we are tail calling and generating PIC/GOT style code load the
2136       // address of the callee into ECX. The value in ecx is used as target of
2137       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2138       // for tail calls on PIC/GOT architectures. Normally we would just put the
2139       // address of GOT into ebx and then call target@PLT. But for tail calls
2140       // ebx would be restored (since ebx is callee saved) before jumping to the
2141       // target@PLT.
2142
2143       // Note: The actual moving to ECX is done further down.
2144       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2145       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2146           !G->getGlobal()->hasProtectedVisibility())
2147         Callee = LowerGlobalAddress(Callee, DAG);
2148       else if (isa<ExternalSymbolSDNode>(Callee))
2149         Callee = LowerExternalSymbol(Callee, DAG);
2150     }
2151   }
2152
2153   if (Is64Bit && isVarArg && !IsWin64) {
2154     // From AMD64 ABI document:
2155     // For calls that may call functions that use varargs or stdargs
2156     // (prototype-less calls or calls to functions containing ellipsis (...) in
2157     // the declaration) %al is used as hidden argument to specify the number
2158     // of SSE registers used. The contents of %al do not need to match exactly
2159     // the number of registers, but must be an ubound on the number of SSE
2160     // registers used and is in the range 0 - 8 inclusive.
2161
2162     // Count the number of XMM registers allocated.
2163     static const unsigned XMMArgRegs[] = {
2164       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2165       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2166     };
2167     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2168     assert((Subtarget->hasXMM() || !NumXMMRegs)
2169            && "SSE registers cannot be used when SSE is disabled");
2170
2171     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2172                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2173     InFlag = Chain.getValue(1);
2174   }
2175
2176
2177   // For tail calls lower the arguments to the 'real' stack slot.
2178   if (isTailCall) {
2179     // Force all the incoming stack arguments to be loaded from the stack
2180     // before any new outgoing arguments are stored to the stack, because the
2181     // outgoing stack slots may alias the incoming argument stack slots, and
2182     // the alias isn't otherwise explicit. This is slightly more conservative
2183     // than necessary, because it means that each store effectively depends
2184     // on every argument instead of just those arguments it would clobber.
2185     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2186
2187     SmallVector<SDValue, 8> MemOpChains2;
2188     SDValue FIN;
2189     int FI = 0;
2190     // Do not flag preceeding copytoreg stuff together with the following stuff.
2191     InFlag = SDValue();
2192     if (GuaranteedTailCallOpt) {
2193       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2194         CCValAssign &VA = ArgLocs[i];
2195         if (VA.isRegLoc())
2196           continue;
2197         assert(VA.isMemLoc());
2198         SDValue Arg = OutVals[i];
2199         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2200         // Create frame index.
2201         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2202         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2203         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2204         FIN = DAG.getFrameIndex(FI, getPointerTy());
2205
2206         if (Flags.isByVal()) {
2207           // Copy relative to framepointer.
2208           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2209           if (StackPtr.getNode() == 0)
2210             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2211                                           getPointerTy());
2212           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2213
2214           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2215                                                            ArgChain,
2216                                                            Flags, DAG, dl));
2217         } else {
2218           // Store relative to framepointer.
2219           MemOpChains2.push_back(
2220             DAG.getStore(ArgChain, dl, Arg, FIN,
2221                          MachinePointerInfo::getFixedStack(FI),
2222                          false, false, 0));
2223         }
2224       }
2225     }
2226
2227     if (!MemOpChains2.empty())
2228       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2229                           &MemOpChains2[0], MemOpChains2.size());
2230
2231     // Copy arguments to their registers.
2232     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2233       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2234                                RegsToPass[i].second, InFlag);
2235       InFlag = Chain.getValue(1);
2236     }
2237     InFlag =SDValue();
2238
2239     // Store the return address to the appropriate stack slot.
2240     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2241                                      FPDiff, dl);
2242   }
2243
2244   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2245     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2246     // In the 64-bit large code model, we have to make all calls
2247     // through a register, since the call instruction's 32-bit
2248     // pc-relative offset may not be large enough to hold the whole
2249     // address.
2250   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2251     // If the callee is a GlobalAddress node (quite common, every direct call
2252     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2253     // it.
2254
2255     // We should use extra load for direct calls to dllimported functions in
2256     // non-JIT mode.
2257     const GlobalValue *GV = G->getGlobal();
2258     if (!GV->hasDLLImportLinkage()) {
2259       unsigned char OpFlags = 0;
2260
2261       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2262       // external symbols most go through the PLT in PIC mode.  If the symbol
2263       // has hidden or protected visibility, or if it is static or local, then
2264       // we don't need to use the PLT - we can directly call it.
2265       if (Subtarget->isTargetELF() &&
2266           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2267           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2268         OpFlags = X86II::MO_PLT;
2269       } else if (Subtarget->isPICStyleStubAny() &&
2270                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2271                  Subtarget->getDarwinVers() < 9) {
2272         // PC-relative references to external symbols should go through $stub,
2273         // unless we're building with the leopard linker or later, which
2274         // automatically synthesizes these stubs.
2275         OpFlags = X86II::MO_DARWIN_STUB;
2276       }
2277
2278       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2279                                           G->getOffset(), OpFlags);
2280     }
2281   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2282     unsigned char OpFlags = 0;
2283
2284     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2285     // external symbols should go through the PLT.
2286     if (Subtarget->isTargetELF() &&
2287         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2288       OpFlags = X86II::MO_PLT;
2289     } else if (Subtarget->isPICStyleStubAny() &&
2290                Subtarget->getDarwinVers() < 9) {
2291       // PC-relative references to external symbols should go through $stub,
2292       // unless we're building with the leopard linker or later, which
2293       // automatically synthesizes these stubs.
2294       OpFlags = X86II::MO_DARWIN_STUB;
2295     }
2296
2297     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2298                                          OpFlags);
2299   }
2300
2301   // Returns a chain & a flag for retval copy to use.
2302   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2303   SmallVector<SDValue, 8> Ops;
2304
2305   if (!IsSibcall && isTailCall) {
2306     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2307                            DAG.getIntPtrConstant(0, true), InFlag);
2308     InFlag = Chain.getValue(1);
2309   }
2310
2311   Ops.push_back(Chain);
2312   Ops.push_back(Callee);
2313
2314   if (isTailCall)
2315     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2316
2317   // Add argument registers to the end of the list so that they are known live
2318   // into the call.
2319   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2320     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2321                                   RegsToPass[i].second.getValueType()));
2322
2323   // Add an implicit use GOT pointer in EBX.
2324   if (!isTailCall && Subtarget->isPICStyleGOT())
2325     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2326
2327   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2328   if (Is64Bit && isVarArg && !IsWin64)
2329     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2330
2331   if (InFlag.getNode())
2332     Ops.push_back(InFlag);
2333
2334   if (isTailCall) {
2335     // We used to do:
2336     //// If this is the first return lowered for this function, add the regs
2337     //// to the liveout set for the function.
2338     // This isn't right, although it's probably harmless on x86; liveouts
2339     // should be computed from returns not tail calls.  Consider a void
2340     // function making a tail call to a function returning int.
2341     return DAG.getNode(X86ISD::TC_RETURN, dl,
2342                        NodeTys, &Ops[0], Ops.size());
2343   }
2344
2345   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2346   InFlag = Chain.getValue(1);
2347
2348   // Create the CALLSEQ_END node.
2349   unsigned NumBytesForCalleeToPush;
2350   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2351     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2352   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2353     // If this is a call to a struct-return function, the callee
2354     // pops the hidden struct pointer, so we have to push it back.
2355     // This is common for Darwin/X86, Linux & Mingw32 targets.
2356     NumBytesForCalleeToPush = 4;
2357   else
2358     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2359
2360   // Returns a flag for retval copy to use.
2361   if (!IsSibcall) {
2362     Chain = DAG.getCALLSEQ_END(Chain,
2363                                DAG.getIntPtrConstant(NumBytes, true),
2364                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2365                                                      true),
2366                                InFlag);
2367     InFlag = Chain.getValue(1);
2368   }
2369
2370   // Handle result values, copying them out of physregs into vregs that we
2371   // return.
2372   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2373                          Ins, dl, DAG, InVals);
2374 }
2375
2376
2377 //===----------------------------------------------------------------------===//
2378 //                Fast Calling Convention (tail call) implementation
2379 //===----------------------------------------------------------------------===//
2380
2381 //  Like std call, callee cleans arguments, convention except that ECX is
2382 //  reserved for storing the tail called function address. Only 2 registers are
2383 //  free for argument passing (inreg). Tail call optimization is performed
2384 //  provided:
2385 //                * tailcallopt is enabled
2386 //                * caller/callee are fastcc
2387 //  On X86_64 architecture with GOT-style position independent code only local
2388 //  (within module) calls are supported at the moment.
2389 //  To keep the stack aligned according to platform abi the function
2390 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2391 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2392 //  If a tail called function callee has more arguments than the caller the
2393 //  caller needs to make sure that there is room to move the RETADDR to. This is
2394 //  achieved by reserving an area the size of the argument delta right after the
2395 //  original REtADDR, but before the saved framepointer or the spilled registers
2396 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2397 //  stack layout:
2398 //    arg1
2399 //    arg2
2400 //    RETADDR
2401 //    [ new RETADDR
2402 //      move area ]
2403 //    (possible EBP)
2404 //    ESI
2405 //    EDI
2406 //    local1 ..
2407
2408 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2409 /// for a 16 byte align requirement.
2410 unsigned
2411 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2412                                                SelectionDAG& DAG) const {
2413   MachineFunction &MF = DAG.getMachineFunction();
2414   const TargetMachine &TM = MF.getTarget();
2415   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2416   unsigned StackAlignment = TFI.getStackAlignment();
2417   uint64_t AlignMask = StackAlignment - 1;
2418   int64_t Offset = StackSize;
2419   uint64_t SlotSize = TD->getPointerSize();
2420   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2421     // Number smaller than 12 so just add the difference.
2422     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2423   } else {
2424     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2425     Offset = ((~AlignMask) & Offset) + StackAlignment +
2426       (StackAlignment-SlotSize);
2427   }
2428   return Offset;
2429 }
2430
2431 /// MatchingStackOffset - Return true if the given stack call argument is
2432 /// already available in the same position (relatively) of the caller's
2433 /// incoming argument stack.
2434 static
2435 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2436                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2437                          const X86InstrInfo *TII) {
2438   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2439   int FI = INT_MAX;
2440   if (Arg.getOpcode() == ISD::CopyFromReg) {
2441     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2442     if (!TargetRegisterInfo::isVirtualRegister(VR))
2443       return false;
2444     MachineInstr *Def = MRI->getVRegDef(VR);
2445     if (!Def)
2446       return false;
2447     if (!Flags.isByVal()) {
2448       if (!TII->isLoadFromStackSlot(Def, FI))
2449         return false;
2450     } else {
2451       unsigned Opcode = Def->getOpcode();
2452       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2453           Def->getOperand(1).isFI()) {
2454         FI = Def->getOperand(1).getIndex();
2455         Bytes = Flags.getByValSize();
2456       } else
2457         return false;
2458     }
2459   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2460     if (Flags.isByVal())
2461       // ByVal argument is passed in as a pointer but it's now being
2462       // dereferenced. e.g.
2463       // define @foo(%struct.X* %A) {
2464       //   tail call @bar(%struct.X* byval %A)
2465       // }
2466       return false;
2467     SDValue Ptr = Ld->getBasePtr();
2468     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2469     if (!FINode)
2470       return false;
2471     FI = FINode->getIndex();
2472   } else
2473     return false;
2474
2475   assert(FI != INT_MAX);
2476   if (!MFI->isFixedObjectIndex(FI))
2477     return false;
2478   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2479 }
2480
2481 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2482 /// for tail call optimization. Targets which want to do tail call
2483 /// optimization should implement this function.
2484 bool
2485 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2486                                                      CallingConv::ID CalleeCC,
2487                                                      bool isVarArg,
2488                                                      bool isCalleeStructRet,
2489                                                      bool isCallerStructRet,
2490                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2491                                     const SmallVectorImpl<SDValue> &OutVals,
2492                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2493                                                      SelectionDAG& DAG) const {
2494   if (!IsTailCallConvention(CalleeCC) &&
2495       CalleeCC != CallingConv::C)
2496     return false;
2497
2498   // If -tailcallopt is specified, make fastcc functions tail-callable.
2499   const MachineFunction &MF = DAG.getMachineFunction();
2500   const Function *CallerF = DAG.getMachineFunction().getFunction();
2501   CallingConv::ID CallerCC = CallerF->getCallingConv();
2502   bool CCMatch = CallerCC == CalleeCC;
2503
2504   if (GuaranteedTailCallOpt) {
2505     if (IsTailCallConvention(CalleeCC) && CCMatch)
2506       return true;
2507     return false;
2508   }
2509
2510   // Look for obvious safe cases to perform tail call optimization that do not
2511   // require ABI changes. This is what gcc calls sibcall.
2512
2513   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2514   // emit a special epilogue.
2515   if (RegInfo->needsStackRealignment(MF))
2516     return false;
2517
2518   // Do not sibcall optimize vararg calls unless the call site is not passing
2519   // any arguments.
2520   if (isVarArg && !Outs.empty())
2521     return false;
2522
2523   // Also avoid sibcall optimization if either caller or callee uses struct
2524   // return semantics.
2525   if (isCalleeStructRet || isCallerStructRet)
2526     return false;
2527
2528   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2529   // Therefore if it's not used by the call it is not safe to optimize this into
2530   // a sibcall.
2531   bool Unused = false;
2532   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2533     if (!Ins[i].Used) {
2534       Unused = true;
2535       break;
2536     }
2537   }
2538   if (Unused) {
2539     SmallVector<CCValAssign, 16> RVLocs;
2540     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2541                    RVLocs, *DAG.getContext());
2542     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2543     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2544       CCValAssign &VA = RVLocs[i];
2545       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2546         return false;
2547     }
2548   }
2549
2550   // If the calling conventions do not match, then we'd better make sure the
2551   // results are returned in the same way as what the caller expects.
2552   if (!CCMatch) {
2553     SmallVector<CCValAssign, 16> RVLocs1;
2554     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2555                     RVLocs1, *DAG.getContext());
2556     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2557
2558     SmallVector<CCValAssign, 16> RVLocs2;
2559     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2560                     RVLocs2, *DAG.getContext());
2561     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2562
2563     if (RVLocs1.size() != RVLocs2.size())
2564       return false;
2565     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2566       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2567         return false;
2568       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2569         return false;
2570       if (RVLocs1[i].isRegLoc()) {
2571         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2572           return false;
2573       } else {
2574         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2575           return false;
2576       }
2577     }
2578   }
2579
2580   // If the callee takes no arguments then go on to check the results of the
2581   // call.
2582   if (!Outs.empty()) {
2583     // Check if stack adjustment is needed. For now, do not do this if any
2584     // argument is passed on the stack.
2585     SmallVector<CCValAssign, 16> ArgLocs;
2586     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2587                    ArgLocs, *DAG.getContext());
2588
2589     // Allocate shadow area for Win64
2590     if (Subtarget->isTargetWin64()) {
2591       CCInfo.AllocateStack(32, 8);
2592     }
2593
2594     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2595     if (CCInfo.getNextStackOffset()) {
2596       MachineFunction &MF = DAG.getMachineFunction();
2597       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2598         return false;
2599
2600       // Check if the arguments are already laid out in the right way as
2601       // the caller's fixed stack objects.
2602       MachineFrameInfo *MFI = MF.getFrameInfo();
2603       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2604       const X86InstrInfo *TII =
2605         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2606       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2607         CCValAssign &VA = ArgLocs[i];
2608         SDValue Arg = OutVals[i];
2609         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2610         if (VA.getLocInfo() == CCValAssign::Indirect)
2611           return false;
2612         if (!VA.isRegLoc()) {
2613           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2614                                    MFI, MRI, TII))
2615             return false;
2616         }
2617       }
2618     }
2619
2620     // If the tailcall address may be in a register, then make sure it's
2621     // possible to register allocate for it. In 32-bit, the call address can
2622     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2623     // callee-saved registers are restored. These happen to be the same
2624     // registers used to pass 'inreg' arguments so watch out for those.
2625     if (!Subtarget->is64Bit() &&
2626         !isa<GlobalAddressSDNode>(Callee) &&
2627         !isa<ExternalSymbolSDNode>(Callee)) {
2628       unsigned NumInRegs = 0;
2629       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630         CCValAssign &VA = ArgLocs[i];
2631         if (!VA.isRegLoc())
2632           continue;
2633         unsigned Reg = VA.getLocReg();
2634         switch (Reg) {
2635         default: break;
2636         case X86::EAX: case X86::EDX: case X86::ECX:
2637           if (++NumInRegs == 3)
2638             return false;
2639           break;
2640         }
2641       }
2642     }
2643   }
2644
2645   // An stdcall caller is expected to clean up its arguments; the callee
2646   // isn't going to do that.
2647   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2648     return false;
2649
2650   return true;
2651 }
2652
2653 FastISel *
2654 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2655   return X86::createFastISel(funcInfo);
2656 }
2657
2658
2659 //===----------------------------------------------------------------------===//
2660 //                           Other Lowering Hooks
2661 //===----------------------------------------------------------------------===//
2662
2663 static bool MayFoldLoad(SDValue Op) {
2664   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2665 }
2666
2667 static bool MayFoldIntoStore(SDValue Op) {
2668   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2669 }
2670
2671 static bool isTargetShuffle(unsigned Opcode) {
2672   switch(Opcode) {
2673   default: return false;
2674   case X86ISD::PSHUFD:
2675   case X86ISD::PSHUFHW:
2676   case X86ISD::PSHUFLW:
2677   case X86ISD::SHUFPD:
2678   case X86ISD::PALIGN:
2679   case X86ISD::SHUFPS:
2680   case X86ISD::MOVLHPS:
2681   case X86ISD::MOVLHPD:
2682   case X86ISD::MOVHLPS:
2683   case X86ISD::MOVLPS:
2684   case X86ISD::MOVLPD:
2685   case X86ISD::MOVSHDUP:
2686   case X86ISD::MOVSLDUP:
2687   case X86ISD::MOVDDUP:
2688   case X86ISD::MOVSS:
2689   case X86ISD::MOVSD:
2690   case X86ISD::UNPCKLPS:
2691   case X86ISD::UNPCKLPD:
2692   case X86ISD::PUNPCKLWD:
2693   case X86ISD::PUNPCKLBW:
2694   case X86ISD::PUNPCKLDQ:
2695   case X86ISD::PUNPCKLQDQ:
2696   case X86ISD::UNPCKHPS:
2697   case X86ISD::UNPCKHPD:
2698   case X86ISD::PUNPCKHWD:
2699   case X86ISD::PUNPCKHBW:
2700   case X86ISD::PUNPCKHDQ:
2701   case X86ISD::PUNPCKHQDQ:
2702     return true;
2703   }
2704   return false;
2705 }
2706
2707 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2708                                                SDValue V1, SelectionDAG &DAG) {
2709   switch(Opc) {
2710   default: llvm_unreachable("Unknown x86 shuffle node");
2711   case X86ISD::MOVSHDUP:
2712   case X86ISD::MOVSLDUP:
2713   case X86ISD::MOVDDUP:
2714     return DAG.getNode(Opc, dl, VT, V1);
2715   }
2716
2717   return SDValue();
2718 }
2719
2720 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2721                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2722   switch(Opc) {
2723   default: llvm_unreachable("Unknown x86 shuffle node");
2724   case X86ISD::PSHUFD:
2725   case X86ISD::PSHUFHW:
2726   case X86ISD::PSHUFLW:
2727     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2728   }
2729
2730   return SDValue();
2731 }
2732
2733 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2734                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2735   switch(Opc) {
2736   default: llvm_unreachable("Unknown x86 shuffle node");
2737   case X86ISD::PALIGN:
2738   case X86ISD::SHUFPD:
2739   case X86ISD::SHUFPS:
2740     return DAG.getNode(Opc, dl, VT, V1, V2,
2741                        DAG.getConstant(TargetMask, MVT::i8));
2742   }
2743   return SDValue();
2744 }
2745
2746 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2747                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2748   switch(Opc) {
2749   default: llvm_unreachable("Unknown x86 shuffle node");
2750   case X86ISD::MOVLHPS:
2751   case X86ISD::MOVLHPD:
2752   case X86ISD::MOVHLPS:
2753   case X86ISD::MOVLPS:
2754   case X86ISD::MOVLPD:
2755   case X86ISD::MOVSS:
2756   case X86ISD::MOVSD:
2757   case X86ISD::UNPCKLPS:
2758   case X86ISD::UNPCKLPD:
2759   case X86ISD::PUNPCKLWD:
2760   case X86ISD::PUNPCKLBW:
2761   case X86ISD::PUNPCKLDQ:
2762   case X86ISD::PUNPCKLQDQ:
2763   case X86ISD::UNPCKHPS:
2764   case X86ISD::UNPCKHPD:
2765   case X86ISD::PUNPCKHWD:
2766   case X86ISD::PUNPCKHBW:
2767   case X86ISD::PUNPCKHDQ:
2768   case X86ISD::PUNPCKHQDQ:
2769     return DAG.getNode(Opc, dl, VT, V1, V2);
2770   }
2771   return SDValue();
2772 }
2773
2774 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2775   MachineFunction &MF = DAG.getMachineFunction();
2776   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2777   int ReturnAddrIndex = FuncInfo->getRAIndex();
2778
2779   if (ReturnAddrIndex == 0) {
2780     // Set up a frame object for the return address.
2781     uint64_t SlotSize = TD->getPointerSize();
2782     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2783                                                            false);
2784     FuncInfo->setRAIndex(ReturnAddrIndex);
2785   }
2786
2787   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2788 }
2789
2790
2791 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2792                                        bool hasSymbolicDisplacement) {
2793   // Offset should fit into 32 bit immediate field.
2794   if (!isInt<32>(Offset))
2795     return false;
2796
2797   // If we don't have a symbolic displacement - we don't have any extra
2798   // restrictions.
2799   if (!hasSymbolicDisplacement)
2800     return true;
2801
2802   // FIXME: Some tweaks might be needed for medium code model.
2803   if (M != CodeModel::Small && M != CodeModel::Kernel)
2804     return false;
2805
2806   // For small code model we assume that latest object is 16MB before end of 31
2807   // bits boundary. We may also accept pretty large negative constants knowing
2808   // that all objects are in the positive half of address space.
2809   if (M == CodeModel::Small && Offset < 16*1024*1024)
2810     return true;
2811
2812   // For kernel code model we know that all object resist in the negative half
2813   // of 32bits address space. We may not accept negative offsets, since they may
2814   // be just off and we may accept pretty large positive ones.
2815   if (M == CodeModel::Kernel && Offset > 0)
2816     return true;
2817
2818   return false;
2819 }
2820
2821 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2822 /// specific condition code, returning the condition code and the LHS/RHS of the
2823 /// comparison to make.
2824 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2825                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2826   if (!isFP) {
2827     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2828       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2829         // X > -1   -> X == 0, jump !sign.
2830         RHS = DAG.getConstant(0, RHS.getValueType());
2831         return X86::COND_NS;
2832       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2833         // X < 0   -> X == 0, jump on sign.
2834         return X86::COND_S;
2835       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2836         // X < 1   -> X <= 0
2837         RHS = DAG.getConstant(0, RHS.getValueType());
2838         return X86::COND_LE;
2839       }
2840     }
2841
2842     switch (SetCCOpcode) {
2843     default: llvm_unreachable("Invalid integer condition!");
2844     case ISD::SETEQ:  return X86::COND_E;
2845     case ISD::SETGT:  return X86::COND_G;
2846     case ISD::SETGE:  return X86::COND_GE;
2847     case ISD::SETLT:  return X86::COND_L;
2848     case ISD::SETLE:  return X86::COND_LE;
2849     case ISD::SETNE:  return X86::COND_NE;
2850     case ISD::SETULT: return X86::COND_B;
2851     case ISD::SETUGT: return X86::COND_A;
2852     case ISD::SETULE: return X86::COND_BE;
2853     case ISD::SETUGE: return X86::COND_AE;
2854     }
2855   }
2856
2857   // First determine if it is required or is profitable to flip the operands.
2858
2859   // If LHS is a foldable load, but RHS is not, flip the condition.
2860   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2861       !ISD::isNON_EXTLoad(RHS.getNode())) {
2862     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2863     std::swap(LHS, RHS);
2864   }
2865
2866   switch (SetCCOpcode) {
2867   default: break;
2868   case ISD::SETOLT:
2869   case ISD::SETOLE:
2870   case ISD::SETUGT:
2871   case ISD::SETUGE:
2872     std::swap(LHS, RHS);
2873     break;
2874   }
2875
2876   // On a floating point condition, the flags are set as follows:
2877   // ZF  PF  CF   op
2878   //  0 | 0 | 0 | X > Y
2879   //  0 | 0 | 1 | X < Y
2880   //  1 | 0 | 0 | X == Y
2881   //  1 | 1 | 1 | unordered
2882   switch (SetCCOpcode) {
2883   default: llvm_unreachable("Condcode should be pre-legalized away");
2884   case ISD::SETUEQ:
2885   case ISD::SETEQ:   return X86::COND_E;
2886   case ISD::SETOLT:              // flipped
2887   case ISD::SETOGT:
2888   case ISD::SETGT:   return X86::COND_A;
2889   case ISD::SETOLE:              // flipped
2890   case ISD::SETOGE:
2891   case ISD::SETGE:   return X86::COND_AE;
2892   case ISD::SETUGT:              // flipped
2893   case ISD::SETULT:
2894   case ISD::SETLT:   return X86::COND_B;
2895   case ISD::SETUGE:              // flipped
2896   case ISD::SETULE:
2897   case ISD::SETLE:   return X86::COND_BE;
2898   case ISD::SETONE:
2899   case ISD::SETNE:   return X86::COND_NE;
2900   case ISD::SETUO:   return X86::COND_P;
2901   case ISD::SETO:    return X86::COND_NP;
2902   case ISD::SETOEQ:
2903   case ISD::SETUNE:  return X86::COND_INVALID;
2904   }
2905 }
2906
2907 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2908 /// code. Current x86 isa includes the following FP cmov instructions:
2909 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2910 static bool hasFPCMov(unsigned X86CC) {
2911   switch (X86CC) {
2912   default:
2913     return false;
2914   case X86::COND_B:
2915   case X86::COND_BE:
2916   case X86::COND_E:
2917   case X86::COND_P:
2918   case X86::COND_A:
2919   case X86::COND_AE:
2920   case X86::COND_NE:
2921   case X86::COND_NP:
2922     return true;
2923   }
2924 }
2925
2926 /// isFPImmLegal - Returns true if the target can instruction select the
2927 /// specified FP immediate natively. If false, the legalizer will
2928 /// materialize the FP immediate as a load from a constant pool.
2929 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2930   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2931     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2932       return true;
2933   }
2934   return false;
2935 }
2936
2937 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2938 /// the specified range (L, H].
2939 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2940   return (Val < 0) || (Val >= Low && Val < Hi);
2941 }
2942
2943 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2944 /// specified value.
2945 static bool isUndefOrEqual(int Val, int CmpVal) {
2946   if (Val < 0 || Val == CmpVal)
2947     return true;
2948   return false;
2949 }
2950
2951 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2952 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2953 /// the second operand.
2954 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2955   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2956     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2957   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2958     return (Mask[0] < 2 && Mask[1] < 2);
2959   return false;
2960 }
2961
2962 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2963   SmallVector<int, 8> M;
2964   N->getMask(M);
2965   return ::isPSHUFDMask(M, N->getValueType(0));
2966 }
2967
2968 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2969 /// is suitable for input to PSHUFHW.
2970 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2971   if (VT != MVT::v8i16)
2972     return false;
2973
2974   // Lower quadword copied in order or undef.
2975   for (int i = 0; i != 4; ++i)
2976     if (Mask[i] >= 0 && Mask[i] != i)
2977       return false;
2978
2979   // Upper quadword shuffled.
2980   for (int i = 4; i != 8; ++i)
2981     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2982       return false;
2983
2984   return true;
2985 }
2986
2987 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2988   SmallVector<int, 8> M;
2989   N->getMask(M);
2990   return ::isPSHUFHWMask(M, N->getValueType(0));
2991 }
2992
2993 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2994 /// is suitable for input to PSHUFLW.
2995 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2996   if (VT != MVT::v8i16)
2997     return false;
2998
2999   // Upper quadword copied in order.
3000   for (int i = 4; i != 8; ++i)
3001     if (Mask[i] >= 0 && Mask[i] != i)
3002       return false;
3003
3004   // Lower quadword shuffled.
3005   for (int i = 0; i != 4; ++i)
3006     if (Mask[i] >= 4)
3007       return false;
3008
3009   return true;
3010 }
3011
3012 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3013   SmallVector<int, 8> M;
3014   N->getMask(M);
3015   return ::isPSHUFLWMask(M, N->getValueType(0));
3016 }
3017
3018 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3019 /// is suitable for input to PALIGNR.
3020 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3021                           bool hasSSSE3) {
3022   int i, e = VT.getVectorNumElements();
3023
3024   // Do not handle v2i64 / v2f64 shuffles with palignr.
3025   if (e < 4 || !hasSSSE3)
3026     return false;
3027
3028   for (i = 0; i != e; ++i)
3029     if (Mask[i] >= 0)
3030       break;
3031
3032   // All undef, not a palignr.
3033   if (i == e)
3034     return false;
3035
3036   // Determine if it's ok to perform a palignr with only the LHS, since we
3037   // don't have access to the actual shuffle elements to see if RHS is undef.
3038   bool Unary = Mask[i] < (int)e;
3039   bool NeedsUnary = false;
3040
3041   int s = Mask[i] - i;
3042
3043   // Check the rest of the elements to see if they are consecutive.
3044   for (++i; i != e; ++i) {
3045     int m = Mask[i];
3046     if (m < 0)
3047       continue;
3048
3049     Unary = Unary && (m < (int)e);
3050     NeedsUnary = NeedsUnary || (m < s);
3051
3052     if (NeedsUnary && !Unary)
3053       return false;
3054     if (Unary && m != ((s+i) & (e-1)))
3055       return false;
3056     if (!Unary && m != (s+i))
3057       return false;
3058   }
3059   return true;
3060 }
3061
3062 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3063   SmallVector<int, 8> M;
3064   N->getMask(M);
3065   return ::isPALIGNRMask(M, N->getValueType(0), true);
3066 }
3067
3068 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3069 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3070 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3071   int NumElems = VT.getVectorNumElements();
3072   if (NumElems != 2 && NumElems != 4)
3073     return false;
3074
3075   int Half = NumElems / 2;
3076   for (int i = 0; i < Half; ++i)
3077     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3078       return false;
3079   for (int i = Half; i < NumElems; ++i)
3080     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3081       return false;
3082
3083   return true;
3084 }
3085
3086 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3087   SmallVector<int, 8> M;
3088   N->getMask(M);
3089   return ::isSHUFPMask(M, N->getValueType(0));
3090 }
3091
3092 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3093 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3094 /// half elements to come from vector 1 (which would equal the dest.) and
3095 /// the upper half to come from vector 2.
3096 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3097   int NumElems = VT.getVectorNumElements();
3098
3099   if (NumElems != 2 && NumElems != 4)
3100     return false;
3101
3102   int Half = NumElems / 2;
3103   for (int i = 0; i < Half; ++i)
3104     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3105       return false;
3106   for (int i = Half; i < NumElems; ++i)
3107     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3108       return false;
3109   return true;
3110 }
3111
3112 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3113   SmallVector<int, 8> M;
3114   N->getMask(M);
3115   return isCommutedSHUFPMask(M, N->getValueType(0));
3116 }
3117
3118 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3119 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3120 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3121   if (N->getValueType(0).getVectorNumElements() != 4)
3122     return false;
3123
3124   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3125   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3126          isUndefOrEqual(N->getMaskElt(1), 7) &&
3127          isUndefOrEqual(N->getMaskElt(2), 2) &&
3128          isUndefOrEqual(N->getMaskElt(3), 3);
3129 }
3130
3131 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3132 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3133 /// <2, 3, 2, 3>
3134 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3135   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3136
3137   if (NumElems != 4)
3138     return false;
3139
3140   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3141   isUndefOrEqual(N->getMaskElt(1), 3) &&
3142   isUndefOrEqual(N->getMaskElt(2), 2) &&
3143   isUndefOrEqual(N->getMaskElt(3), 3);
3144 }
3145
3146 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3147 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3148 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3149   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3150
3151   if (NumElems != 2 && NumElems != 4)
3152     return false;
3153
3154   for (unsigned i = 0; i < NumElems/2; ++i)
3155     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3156       return false;
3157
3158   for (unsigned i = NumElems/2; i < NumElems; ++i)
3159     if (!isUndefOrEqual(N->getMaskElt(i), i))
3160       return false;
3161
3162   return true;
3163 }
3164
3165 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3166 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3167 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3168   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3169
3170   if (NumElems != 2 && NumElems != 4)
3171     return false;
3172
3173   for (unsigned i = 0; i < NumElems/2; ++i)
3174     if (!isUndefOrEqual(N->getMaskElt(i), i))
3175       return false;
3176
3177   for (unsigned i = 0; i < NumElems/2; ++i)
3178     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3179       return false;
3180
3181   return true;
3182 }
3183
3184 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3185 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3186 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3187                          bool V2IsSplat = false) {
3188   int NumElts = VT.getVectorNumElements();
3189   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3190     return false;
3191
3192   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3193     int BitI  = Mask[i];
3194     int BitI1 = Mask[i+1];
3195     if (!isUndefOrEqual(BitI, j))
3196       return false;
3197     if (V2IsSplat) {
3198       if (!isUndefOrEqual(BitI1, NumElts))
3199         return false;
3200     } else {
3201       if (!isUndefOrEqual(BitI1, j + NumElts))
3202         return false;
3203     }
3204   }
3205   return true;
3206 }
3207
3208 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3209   SmallVector<int, 8> M;
3210   N->getMask(M);
3211   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3212 }
3213
3214 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3215 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3216 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3217                          bool V2IsSplat = false) {
3218   int NumElts = VT.getVectorNumElements();
3219   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3220     return false;
3221
3222   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3223     int BitI  = Mask[i];
3224     int BitI1 = Mask[i+1];
3225     if (!isUndefOrEqual(BitI, j + NumElts/2))
3226       return false;
3227     if (V2IsSplat) {
3228       if (isUndefOrEqual(BitI1, NumElts))
3229         return false;
3230     } else {
3231       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3232         return false;
3233     }
3234   }
3235   return true;
3236 }
3237
3238 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3239   SmallVector<int, 8> M;
3240   N->getMask(M);
3241   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3242 }
3243
3244 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3245 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3246 /// <0, 0, 1, 1>
3247 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3248   int NumElems = VT.getVectorNumElements();
3249   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3250     return false;
3251
3252   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3253     int BitI  = Mask[i];
3254     int BitI1 = Mask[i+1];
3255     if (!isUndefOrEqual(BitI, j))
3256       return false;
3257     if (!isUndefOrEqual(BitI1, j))
3258       return false;
3259   }
3260   return true;
3261 }
3262
3263 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3264   SmallVector<int, 8> M;
3265   N->getMask(M);
3266   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3267 }
3268
3269 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3270 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3271 /// <2, 2, 3, 3>
3272 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3273   int NumElems = VT.getVectorNumElements();
3274   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3275     return false;
3276
3277   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3278     int BitI  = Mask[i];
3279     int BitI1 = Mask[i+1];
3280     if (!isUndefOrEqual(BitI, j))
3281       return false;
3282     if (!isUndefOrEqual(BitI1, j))
3283       return false;
3284   }
3285   return true;
3286 }
3287
3288 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3289   SmallVector<int, 8> M;
3290   N->getMask(M);
3291   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3292 }
3293
3294 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3295 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3296 /// MOVSD, and MOVD, i.e. setting the lowest element.
3297 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3298   if (VT.getVectorElementType().getSizeInBits() < 32)
3299     return false;
3300
3301   int NumElts = VT.getVectorNumElements();
3302
3303   if (!isUndefOrEqual(Mask[0], NumElts))
3304     return false;
3305
3306   for (int i = 1; i < NumElts; ++i)
3307     if (!isUndefOrEqual(Mask[i], i))
3308       return false;
3309
3310   return true;
3311 }
3312
3313 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3314   SmallVector<int, 8> M;
3315   N->getMask(M);
3316   return ::isMOVLMask(M, N->getValueType(0));
3317 }
3318
3319 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3320 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3321 /// element of vector 2 and the other elements to come from vector 1 in order.
3322 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3323                                bool V2IsSplat = false, bool V2IsUndef = false) {
3324   int NumOps = VT.getVectorNumElements();
3325   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3326     return false;
3327
3328   if (!isUndefOrEqual(Mask[0], 0))
3329     return false;
3330
3331   for (int i = 1; i < NumOps; ++i)
3332     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3333           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3334           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3335       return false;
3336
3337   return true;
3338 }
3339
3340 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3341                            bool V2IsUndef = false) {
3342   SmallVector<int, 8> M;
3343   N->getMask(M);
3344   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3345 }
3346
3347 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3348 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3349 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3350   if (N->getValueType(0).getVectorNumElements() != 4)
3351     return false;
3352
3353   // Expect 1, 1, 3, 3
3354   for (unsigned i = 0; i < 2; ++i) {
3355     int Elt = N->getMaskElt(i);
3356     if (Elt >= 0 && Elt != 1)
3357       return false;
3358   }
3359
3360   bool HasHi = false;
3361   for (unsigned i = 2; i < 4; ++i) {
3362     int Elt = N->getMaskElt(i);
3363     if (Elt >= 0 && Elt != 3)
3364       return false;
3365     if (Elt == 3)
3366       HasHi = true;
3367   }
3368   // Don't use movshdup if it can be done with a shufps.
3369   // FIXME: verify that matching u, u, 3, 3 is what we want.
3370   return HasHi;
3371 }
3372
3373 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3374 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3375 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3376   if (N->getValueType(0).getVectorNumElements() != 4)
3377     return false;
3378
3379   // Expect 0, 0, 2, 2
3380   for (unsigned i = 0; i < 2; ++i)
3381     if (N->getMaskElt(i) > 0)
3382       return false;
3383
3384   bool HasHi = false;
3385   for (unsigned i = 2; i < 4; ++i) {
3386     int Elt = N->getMaskElt(i);
3387     if (Elt >= 0 && Elt != 2)
3388       return false;
3389     if (Elt == 2)
3390       HasHi = true;
3391   }
3392   // Don't use movsldup if it can be done with a shufps.
3393   return HasHi;
3394 }
3395
3396 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3397 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3398 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3399   int e = N->getValueType(0).getVectorNumElements() / 2;
3400
3401   for (int i = 0; i < e; ++i)
3402     if (!isUndefOrEqual(N->getMaskElt(i), i))
3403       return false;
3404   for (int i = 0; i < e; ++i)
3405     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3406       return false;
3407   return true;
3408 }
3409
3410 /// isVEXTRACTF128Index - Return true if the specified
3411 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3412 /// suitable for input to VEXTRACTF128.
3413 bool X86::isVEXTRACTF128Index(SDNode *N) {
3414   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3415     return false;
3416
3417   // The index should be aligned on a 128-bit boundary.
3418   uint64_t Index =
3419     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3420
3421   unsigned VL = N->getValueType(0).getVectorNumElements();
3422   unsigned VBits = N->getValueType(0).getSizeInBits();
3423   unsigned ElSize = VBits / VL;
3424   bool Result = (Index * ElSize) % 128 == 0;
3425
3426   return Result;
3427 }
3428
3429 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3430 /// operand specifies a subvector insert that is suitable for input to
3431 /// VINSERTF128.
3432 bool X86::isVINSERTF128Index(SDNode *N) {
3433   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3434     return false;
3435
3436   // The index should be aligned on a 128-bit boundary.
3437   uint64_t Index =
3438     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3439
3440   unsigned VL = N->getValueType(0).getVectorNumElements();
3441   unsigned VBits = N->getValueType(0).getSizeInBits();
3442   unsigned ElSize = VBits / VL;
3443   bool Result = (Index * ElSize) % 128 == 0;
3444
3445   return Result;
3446 }
3447
3448 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3449 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3450 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3451   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3452   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3453
3454   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3455   unsigned Mask = 0;
3456   for (int i = 0; i < NumOperands; ++i) {
3457     int Val = SVOp->getMaskElt(NumOperands-i-1);
3458     if (Val < 0) Val = 0;
3459     if (Val >= NumOperands) Val -= NumOperands;
3460     Mask |= Val;
3461     if (i != NumOperands - 1)
3462       Mask <<= Shift;
3463   }
3464   return Mask;
3465 }
3466
3467 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3468 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3469 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3470   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3471   unsigned Mask = 0;
3472   // 8 nodes, but we only care about the last 4.
3473   for (unsigned i = 7; i >= 4; --i) {
3474     int Val = SVOp->getMaskElt(i);
3475     if (Val >= 0)
3476       Mask |= (Val - 4);
3477     if (i != 4)
3478       Mask <<= 2;
3479   }
3480   return Mask;
3481 }
3482
3483 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3484 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3485 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3486   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3487   unsigned Mask = 0;
3488   // 8 nodes, but we only care about the first 4.
3489   for (int i = 3; i >= 0; --i) {
3490     int Val = SVOp->getMaskElt(i);
3491     if (Val >= 0)
3492       Mask |= Val;
3493     if (i != 0)
3494       Mask <<= 2;
3495   }
3496   return Mask;
3497 }
3498
3499 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3500 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3501 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3502   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3503   EVT VVT = N->getValueType(0);
3504   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3505   int Val = 0;
3506
3507   unsigned i, e;
3508   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3509     Val = SVOp->getMaskElt(i);
3510     if (Val >= 0)
3511       break;
3512   }
3513   return (Val - i) * EltSize;
3514 }
3515
3516 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3517 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3518 /// instructions.
3519 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3520   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3521     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3522
3523   uint64_t Index =
3524     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3525
3526   EVT VecVT = N->getOperand(0).getValueType();
3527   EVT ElVT = VecVT.getVectorElementType();
3528
3529   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3530
3531   return Index / NumElemsPerChunk;
3532 }
3533
3534 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3535 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3536 /// instructions.
3537 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3538   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3539     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3540
3541   uint64_t Index =
3542     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3543
3544   EVT VecVT = N->getValueType(0);
3545   EVT ElVT = VecVT.getVectorElementType();
3546
3547   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3548
3549   return Index / NumElemsPerChunk;
3550 }
3551
3552 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3553 /// constant +0.0.
3554 bool X86::isZeroNode(SDValue Elt) {
3555   return ((isa<ConstantSDNode>(Elt) &&
3556            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3557           (isa<ConstantFPSDNode>(Elt) &&
3558            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3559 }
3560
3561 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3562 /// their permute mask.
3563 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3564                                     SelectionDAG &DAG) {
3565   EVT VT = SVOp->getValueType(0);
3566   unsigned NumElems = VT.getVectorNumElements();
3567   SmallVector<int, 8> MaskVec;
3568
3569   for (unsigned i = 0; i != NumElems; ++i) {
3570     int idx = SVOp->getMaskElt(i);
3571     if (idx < 0)
3572       MaskVec.push_back(idx);
3573     else if (idx < (int)NumElems)
3574       MaskVec.push_back(idx + NumElems);
3575     else
3576       MaskVec.push_back(idx - NumElems);
3577   }
3578   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3579                               SVOp->getOperand(0), &MaskVec[0]);
3580 }
3581
3582 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3583 /// the two vector operands have swapped position.
3584 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3585   unsigned NumElems = VT.getVectorNumElements();
3586   for (unsigned i = 0; i != NumElems; ++i) {
3587     int idx = Mask[i];
3588     if (idx < 0)
3589       continue;
3590     else if (idx < (int)NumElems)
3591       Mask[i] = idx + NumElems;
3592     else
3593       Mask[i] = idx - NumElems;
3594   }
3595 }
3596
3597 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3598 /// match movhlps. The lower half elements should come from upper half of
3599 /// V1 (and in order), and the upper half elements should come from the upper
3600 /// half of V2 (and in order).
3601 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3602   if (Op->getValueType(0).getVectorNumElements() != 4)
3603     return false;
3604   for (unsigned i = 0, e = 2; i != e; ++i)
3605     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3606       return false;
3607   for (unsigned i = 2; i != 4; ++i)
3608     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3609       return false;
3610   return true;
3611 }
3612
3613 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3614 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3615 /// required.
3616 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3617   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3618     return false;
3619   N = N->getOperand(0).getNode();
3620   if (!ISD::isNON_EXTLoad(N))
3621     return false;
3622   if (LD)
3623     *LD = cast<LoadSDNode>(N);
3624   return true;
3625 }
3626
3627 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3628 /// match movlp{s|d}. The lower half elements should come from lower half of
3629 /// V1 (and in order), and the upper half elements should come from the upper
3630 /// half of V2 (and in order). And since V1 will become the source of the
3631 /// MOVLP, it must be either a vector load or a scalar load to vector.
3632 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3633                                ShuffleVectorSDNode *Op) {
3634   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3635     return false;
3636   // Is V2 is a vector load, don't do this transformation. We will try to use
3637   // load folding shufps op.
3638   if (ISD::isNON_EXTLoad(V2))
3639     return false;
3640
3641   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3642
3643   if (NumElems != 2 && NumElems != 4)
3644     return false;
3645   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3646     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3647       return false;
3648   for (unsigned i = NumElems/2; i != NumElems; ++i)
3649     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3650       return false;
3651   return true;
3652 }
3653
3654 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3655 /// all the same.
3656 static bool isSplatVector(SDNode *N) {
3657   if (N->getOpcode() != ISD::BUILD_VECTOR)
3658     return false;
3659
3660   SDValue SplatValue = N->getOperand(0);
3661   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3662     if (N->getOperand(i) != SplatValue)
3663       return false;
3664   return true;
3665 }
3666
3667 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3668 /// to an zero vector.
3669 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3670 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3671   SDValue V1 = N->getOperand(0);
3672   SDValue V2 = N->getOperand(1);
3673   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3674   for (unsigned i = 0; i != NumElems; ++i) {
3675     int Idx = N->getMaskElt(i);
3676     if (Idx >= (int)NumElems) {
3677       unsigned Opc = V2.getOpcode();
3678       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3679         continue;
3680       if (Opc != ISD::BUILD_VECTOR ||
3681           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3682         return false;
3683     } else if (Idx >= 0) {
3684       unsigned Opc = V1.getOpcode();
3685       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3686         continue;
3687       if (Opc != ISD::BUILD_VECTOR ||
3688           !X86::isZeroNode(V1.getOperand(Idx)))
3689         return false;
3690     }
3691   }
3692   return true;
3693 }
3694
3695 /// getZeroVector - Returns a vector of specified type with all zero elements.
3696 ///
3697 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3698                              DebugLoc dl) {
3699   assert(VT.isVector() && "Expected a vector type");
3700
3701   // Always build SSE zero vectors as <4 x i32> bitcasted
3702   // to their dest type. This ensures they get CSE'd.
3703   SDValue Vec;
3704   if (VT.getSizeInBits() == 128) {  // SSE
3705     if (HasSSE2) {  // SSE2
3706       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3707       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3708     } else { // SSE1
3709       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3710       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3711     }
3712   } else if (VT.getSizeInBits() == 256) { // AVX
3713     // 256-bit logic and arithmetic instructions in AVX are
3714     // all floating-point, no support for integer ops. Default
3715     // to emitting fp zeroed vectors then.
3716     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3717     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3718     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3719   }
3720   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3721 }
3722
3723 /// getOnesVector - Returns a vector of specified type with all bits set.
3724 ///
3725 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3726   assert(VT.isVector() && "Expected a vector type");
3727
3728   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3729   // type.  This ensures they get CSE'd.
3730   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3731   SDValue Vec;
3732   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3733   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3734 }
3735
3736
3737 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3738 /// that point to V2 points to its first element.
3739 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3740   EVT VT = SVOp->getValueType(0);
3741   unsigned NumElems = VT.getVectorNumElements();
3742
3743   bool Changed = false;
3744   SmallVector<int, 8> MaskVec;
3745   SVOp->getMask(MaskVec);
3746
3747   for (unsigned i = 0; i != NumElems; ++i) {
3748     if (MaskVec[i] > (int)NumElems) {
3749       MaskVec[i] = NumElems;
3750       Changed = true;
3751     }
3752   }
3753   if (Changed)
3754     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3755                                 SVOp->getOperand(1), &MaskVec[0]);
3756   return SDValue(SVOp, 0);
3757 }
3758
3759 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3760 /// operation of specified width.
3761 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3762                        SDValue V2) {
3763   unsigned NumElems = VT.getVectorNumElements();
3764   SmallVector<int, 8> Mask;
3765   Mask.push_back(NumElems);
3766   for (unsigned i = 1; i != NumElems; ++i)
3767     Mask.push_back(i);
3768   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3769 }
3770
3771 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3772 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3773                           SDValue V2) {
3774   unsigned NumElems = VT.getVectorNumElements();
3775   SmallVector<int, 8> Mask;
3776   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3777     Mask.push_back(i);
3778     Mask.push_back(i + NumElems);
3779   }
3780   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3781 }
3782
3783 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3784 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3785                           SDValue V2) {
3786   unsigned NumElems = VT.getVectorNumElements();
3787   unsigned Half = NumElems/2;
3788   SmallVector<int, 8> Mask;
3789   for (unsigned i = 0; i != Half; ++i) {
3790     Mask.push_back(i + Half);
3791     Mask.push_back(i + NumElems + Half);
3792   }
3793   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3794 }
3795
3796 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3797 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3798   EVT PVT = MVT::v4f32;
3799   EVT VT = SV->getValueType(0);
3800   DebugLoc dl = SV->getDebugLoc();
3801   SDValue V1 = SV->getOperand(0);
3802   int NumElems = VT.getVectorNumElements();
3803   int EltNo = SV->getSplatIndex();
3804
3805   // unpack elements to the correct location
3806   while (NumElems > 4) {
3807     if (EltNo < NumElems/2) {
3808       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3809     } else {
3810       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3811       EltNo -= NumElems/2;
3812     }
3813     NumElems >>= 1;
3814   }
3815
3816   // Perform the splat.
3817   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3818   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3819   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3820   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3821 }
3822
3823 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3824 /// vector of zero or undef vector.  This produces a shuffle where the low
3825 /// element of V2 is swizzled into the zero/undef vector, landing at element
3826 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3827 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3828                                              bool isZero, bool HasSSE2,
3829                                              SelectionDAG &DAG) {
3830   EVT VT = V2.getValueType();
3831   SDValue V1 = isZero
3832     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3833   unsigned NumElems = VT.getVectorNumElements();
3834   SmallVector<int, 16> MaskVec;
3835   for (unsigned i = 0; i != NumElems; ++i)
3836     // If this is the insertion idx, put the low elt of V2 here.
3837     MaskVec.push_back(i == Idx ? NumElems : i);
3838   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3839 }
3840
3841 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3842 /// element of the result of the vector shuffle.
3843 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3844                             unsigned Depth) {
3845   if (Depth == 6)
3846     return SDValue();  // Limit search depth.
3847
3848   SDValue V = SDValue(N, 0);
3849   EVT VT = V.getValueType();
3850   unsigned Opcode = V.getOpcode();
3851
3852   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3853   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3854     Index = SV->getMaskElt(Index);
3855
3856     if (Index < 0)
3857       return DAG.getUNDEF(VT.getVectorElementType());
3858
3859     int NumElems = VT.getVectorNumElements();
3860     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3861     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3862   }
3863
3864   // Recurse into target specific vector shuffles to find scalars.
3865   if (isTargetShuffle(Opcode)) {
3866     int NumElems = VT.getVectorNumElements();
3867     SmallVector<unsigned, 16> ShuffleMask;
3868     SDValue ImmN;
3869
3870     switch(Opcode) {
3871     case X86ISD::SHUFPS:
3872     case X86ISD::SHUFPD:
3873       ImmN = N->getOperand(N->getNumOperands()-1);
3874       DecodeSHUFPSMask(NumElems,
3875                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3876                        ShuffleMask);
3877       break;
3878     case X86ISD::PUNPCKHBW:
3879     case X86ISD::PUNPCKHWD:
3880     case X86ISD::PUNPCKHDQ:
3881     case X86ISD::PUNPCKHQDQ:
3882       DecodePUNPCKHMask(NumElems, ShuffleMask);
3883       break;
3884     case X86ISD::UNPCKHPS:
3885     case X86ISD::UNPCKHPD:
3886       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3887       break;
3888     case X86ISD::PUNPCKLBW:
3889     case X86ISD::PUNPCKLWD:
3890     case X86ISD::PUNPCKLDQ:
3891     case X86ISD::PUNPCKLQDQ:
3892       DecodePUNPCKLMask(NumElems, ShuffleMask);
3893       break;
3894     case X86ISD::UNPCKLPS:
3895     case X86ISD::UNPCKLPD:
3896       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3897       break;
3898     case X86ISD::MOVHLPS:
3899       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3900       break;
3901     case X86ISD::MOVLHPS:
3902       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3903       break;
3904     case X86ISD::PSHUFD:
3905       ImmN = N->getOperand(N->getNumOperands()-1);
3906       DecodePSHUFMask(NumElems,
3907                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3908                       ShuffleMask);
3909       break;
3910     case X86ISD::PSHUFHW:
3911       ImmN = N->getOperand(N->getNumOperands()-1);
3912       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3913                         ShuffleMask);
3914       break;
3915     case X86ISD::PSHUFLW:
3916       ImmN = N->getOperand(N->getNumOperands()-1);
3917       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3918                         ShuffleMask);
3919       break;
3920     case X86ISD::MOVSS:
3921     case X86ISD::MOVSD: {
3922       // The index 0 always comes from the first element of the second source,
3923       // this is why MOVSS and MOVSD are used in the first place. The other
3924       // elements come from the other positions of the first source vector.
3925       unsigned OpNum = (Index == 0) ? 1 : 0;
3926       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3927                                  Depth+1);
3928     }
3929     default:
3930       assert("not implemented for target shuffle node");
3931       return SDValue();
3932     }
3933
3934     Index = ShuffleMask[Index];
3935     if (Index < 0)
3936       return DAG.getUNDEF(VT.getVectorElementType());
3937
3938     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3939     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3940                                Depth+1);
3941   }
3942
3943   // Actual nodes that may contain scalar elements
3944   if (Opcode == ISD::BITCAST) {
3945     V = V.getOperand(0);
3946     EVT SrcVT = V.getValueType();
3947     unsigned NumElems = VT.getVectorNumElements();
3948
3949     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3950       return SDValue();
3951   }
3952
3953   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3954     return (Index == 0) ? V.getOperand(0)
3955                           : DAG.getUNDEF(VT.getVectorElementType());
3956
3957   if (V.getOpcode() == ISD::BUILD_VECTOR)
3958     return V.getOperand(Index);
3959
3960   return SDValue();
3961 }
3962
3963 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3964 /// shuffle operation which come from a consecutively from a zero. The
3965 /// search can start in two diferent directions, from left or right.
3966 static
3967 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3968                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3969   int i = 0;
3970
3971   while (i < NumElems) {
3972     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3973     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3974     if (!(Elt.getNode() &&
3975          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3976       break;
3977     ++i;
3978   }
3979
3980   return i;
3981 }
3982
3983 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3984 /// MaskE correspond consecutively to elements from one of the vector operands,
3985 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3986 static
3987 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3988                               int OpIdx, int NumElems, unsigned &OpNum) {
3989   bool SeenV1 = false;
3990   bool SeenV2 = false;
3991
3992   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3993     int Idx = SVOp->getMaskElt(i);
3994     // Ignore undef indicies
3995     if (Idx < 0)
3996       continue;
3997
3998     if (Idx < NumElems)
3999       SeenV1 = true;
4000     else
4001       SeenV2 = true;
4002
4003     // Only accept consecutive elements from the same vector
4004     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4005       return false;
4006   }
4007
4008   OpNum = SeenV1 ? 0 : 1;
4009   return true;
4010 }
4011
4012 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4013 /// logical left shift of a vector.
4014 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4015                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4016   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4017   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4018               false /* check zeros from right */, DAG);
4019   unsigned OpSrc;
4020
4021   if (!NumZeros)
4022     return false;
4023
4024   // Considering the elements in the mask that are not consecutive zeros,
4025   // check if they consecutively come from only one of the source vectors.
4026   //
4027   //               V1 = {X, A, B, C}     0
4028   //                         \  \  \    /
4029   //   vector_shuffle V1, V2 <1, 2, 3, X>
4030   //
4031   if (!isShuffleMaskConsecutive(SVOp,
4032             0,                   // Mask Start Index
4033             NumElems-NumZeros-1, // Mask End Index
4034             NumZeros,            // Where to start looking in the src vector
4035             NumElems,            // Number of elements in vector
4036             OpSrc))              // Which source operand ?
4037     return false;
4038
4039   isLeft = false;
4040   ShAmt = NumZeros;
4041   ShVal = SVOp->getOperand(OpSrc);
4042   return true;
4043 }
4044
4045 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4046 /// logical left shift of a vector.
4047 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4048                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4049   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4050   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4051               true /* check zeros from left */, DAG);
4052   unsigned OpSrc;
4053
4054   if (!NumZeros)
4055     return false;
4056
4057   // Considering the elements in the mask that are not consecutive zeros,
4058   // check if they consecutively come from only one of the source vectors.
4059   //
4060   //                           0    { A, B, X, X } = V2
4061   //                          / \    /  /
4062   //   vector_shuffle V1, V2 <X, X, 4, 5>
4063   //
4064   if (!isShuffleMaskConsecutive(SVOp,
4065             NumZeros,     // Mask Start Index
4066             NumElems-1,   // Mask End Index
4067             0,            // Where to start looking in the src vector
4068             NumElems,     // Number of elements in vector
4069             OpSrc))       // Which source operand ?
4070     return false;
4071
4072   isLeft = true;
4073   ShAmt = NumZeros;
4074   ShVal = SVOp->getOperand(OpSrc);
4075   return true;
4076 }
4077
4078 /// isVectorShift - Returns true if the shuffle can be implemented as a
4079 /// logical left or right shift of a vector.
4080 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4081                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4082   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4083       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4084     return true;
4085
4086   return false;
4087 }
4088
4089 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4090 ///
4091 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4092                                        unsigned NumNonZero, unsigned NumZero,
4093                                        SelectionDAG &DAG,
4094                                        const TargetLowering &TLI) {
4095   if (NumNonZero > 8)
4096     return SDValue();
4097
4098   DebugLoc dl = Op.getDebugLoc();
4099   SDValue V(0, 0);
4100   bool First = true;
4101   for (unsigned i = 0; i < 16; ++i) {
4102     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4103     if (ThisIsNonZero && First) {
4104       if (NumZero)
4105         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4106       else
4107         V = DAG.getUNDEF(MVT::v8i16);
4108       First = false;
4109     }
4110
4111     if ((i & 1) != 0) {
4112       SDValue ThisElt(0, 0), LastElt(0, 0);
4113       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4114       if (LastIsNonZero) {
4115         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4116                               MVT::i16, Op.getOperand(i-1));
4117       }
4118       if (ThisIsNonZero) {
4119         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4120         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4121                               ThisElt, DAG.getConstant(8, MVT::i8));
4122         if (LastIsNonZero)
4123           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4124       } else
4125         ThisElt = LastElt;
4126
4127       if (ThisElt.getNode())
4128         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4129                         DAG.getIntPtrConstant(i/2));
4130     }
4131   }
4132
4133   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4134 }
4135
4136 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4137 ///
4138 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4139                                      unsigned NumNonZero, unsigned NumZero,
4140                                      SelectionDAG &DAG,
4141                                      const TargetLowering &TLI) {
4142   if (NumNonZero > 4)
4143     return SDValue();
4144
4145   DebugLoc dl = Op.getDebugLoc();
4146   SDValue V(0, 0);
4147   bool First = true;
4148   for (unsigned i = 0; i < 8; ++i) {
4149     bool isNonZero = (NonZeros & (1 << i)) != 0;
4150     if (isNonZero) {
4151       if (First) {
4152         if (NumZero)
4153           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4154         else
4155           V = DAG.getUNDEF(MVT::v8i16);
4156         First = false;
4157       }
4158       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4159                       MVT::v8i16, V, Op.getOperand(i),
4160                       DAG.getIntPtrConstant(i));
4161     }
4162   }
4163
4164   return V;
4165 }
4166
4167 /// getVShift - Return a vector logical shift node.
4168 ///
4169 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4170                          unsigned NumBits, SelectionDAG &DAG,
4171                          const TargetLowering &TLI, DebugLoc dl) {
4172   EVT ShVT = MVT::v2i64;
4173   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4174   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4175   return DAG.getNode(ISD::BITCAST, dl, VT,
4176                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4177                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4178 }
4179
4180 SDValue
4181 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4182                                           SelectionDAG &DAG) const {
4183
4184   // Check if the scalar load can be widened into a vector load. And if
4185   // the address is "base + cst" see if the cst can be "absorbed" into
4186   // the shuffle mask.
4187   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4188     SDValue Ptr = LD->getBasePtr();
4189     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4190       return SDValue();
4191     EVT PVT = LD->getValueType(0);
4192     if (PVT != MVT::i32 && PVT != MVT::f32)
4193       return SDValue();
4194
4195     int FI = -1;
4196     int64_t Offset = 0;
4197     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4198       FI = FINode->getIndex();
4199       Offset = 0;
4200     } else if (Ptr.getOpcode() == ISD::ADD &&
4201                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4202                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4203       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4204       Offset = Ptr.getConstantOperandVal(1);
4205       Ptr = Ptr.getOperand(0);
4206     } else {
4207       return SDValue();
4208     }
4209
4210     SDValue Chain = LD->getChain();
4211     // Make sure the stack object alignment is at least 16.
4212     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4213     if (DAG.InferPtrAlignment(Ptr) < 16) {
4214       if (MFI->isFixedObjectIndex(FI)) {
4215         // Can't change the alignment. FIXME: It's possible to compute
4216         // the exact stack offset and reference FI + adjust offset instead.
4217         // If someone *really* cares about this. That's the way to implement it.
4218         return SDValue();
4219       } else {
4220         MFI->setObjectAlignment(FI, 16);
4221       }
4222     }
4223
4224     // (Offset % 16) must be multiple of 4. Then address is then
4225     // Ptr + (Offset & ~15).
4226     if (Offset < 0)
4227       return SDValue();
4228     if ((Offset % 16) & 3)
4229       return SDValue();
4230     int64_t StartOffset = Offset & ~15;
4231     if (StartOffset)
4232       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4233                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4234
4235     int EltNo = (Offset - StartOffset) >> 2;
4236     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4237     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4238     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4239                              LD->getPointerInfo().getWithOffset(StartOffset),
4240                              false, false, 0);
4241     // Canonicalize it to a v4i32 shuffle.
4242     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4243     return DAG.getNode(ISD::BITCAST, dl, VT,
4244                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4245                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4246   }
4247
4248   return SDValue();
4249 }
4250
4251 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4252 /// vector of type 'VT', see if the elements can be replaced by a single large
4253 /// load which has the same value as a build_vector whose operands are 'elts'.
4254 ///
4255 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4256 ///
4257 /// FIXME: we'd also like to handle the case where the last elements are zero
4258 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4259 /// There's even a handy isZeroNode for that purpose.
4260 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4261                                         DebugLoc &DL, SelectionDAG &DAG) {
4262   EVT EltVT = VT.getVectorElementType();
4263   unsigned NumElems = Elts.size();
4264
4265   LoadSDNode *LDBase = NULL;
4266   unsigned LastLoadedElt = -1U;
4267
4268   // For each element in the initializer, see if we've found a load or an undef.
4269   // If we don't find an initial load element, or later load elements are
4270   // non-consecutive, bail out.
4271   for (unsigned i = 0; i < NumElems; ++i) {
4272     SDValue Elt = Elts[i];
4273
4274     if (!Elt.getNode() ||
4275         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4276       return SDValue();
4277     if (!LDBase) {
4278       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4279         return SDValue();
4280       LDBase = cast<LoadSDNode>(Elt.getNode());
4281       LastLoadedElt = i;
4282       continue;
4283     }
4284     if (Elt.getOpcode() == ISD::UNDEF)
4285       continue;
4286
4287     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4288     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4289       return SDValue();
4290     LastLoadedElt = i;
4291   }
4292
4293   // If we have found an entire vector of loads and undefs, then return a large
4294   // load of the entire vector width starting at the base pointer.  If we found
4295   // consecutive loads for the low half, generate a vzext_load node.
4296   if (LastLoadedElt == NumElems - 1) {
4297     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4298       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4299                          LDBase->getPointerInfo(),
4300                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4301     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4302                        LDBase->getPointerInfo(),
4303                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4304                        LDBase->getAlignment());
4305   } else if (NumElems == 4 && LastLoadedElt == 1) {
4306     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4307     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4308     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4309                                               Ops, 2, MVT::i32,
4310                                               LDBase->getMemOperand());
4311     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4312   }
4313   return SDValue();
4314 }
4315
4316 SDValue
4317 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4318   DebugLoc dl = Op.getDebugLoc();
4319
4320   EVT VT = Op.getValueType();
4321   EVT ExtVT = VT.getVectorElementType();
4322
4323   unsigned NumElems = Op.getNumOperands();
4324
4325   // For AVX-length vectors, build the individual 128-bit pieces and
4326   // use shuffles to put them in place.
4327   if (VT.getSizeInBits() > 256 && 
4328       Subtarget->hasAVX() && 
4329       !Disable256Bit &&
4330       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4331     SmallVector<SDValue, 8> V;
4332     V.resize(NumElems);
4333     for (unsigned i = 0; i < NumElems; ++i) {
4334       V[i] = Op.getOperand(i);
4335     }
4336  
4337     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4338
4339     // Build the lower subvector.
4340     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4341     // Build the upper subvector.
4342     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4343                                 NumElems/2);
4344
4345     return ConcatVectors(Lower, Upper, DAG);
4346   }
4347
4348   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4349   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4350   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4351   // is present, so AllOnes is ignored.
4352   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4353       (Op.getValueType().getSizeInBits() != 256 &&
4354        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4355     // Canonicalize this to <4 x i32> (SSE) to
4356     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4357     // eliminated on x86-32 hosts.
4358     if (Op.getValueType() == MVT::v4i32)
4359       return Op;
4360
4361     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4362       return getOnesVector(Op.getValueType(), DAG, dl);
4363     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4364   }
4365
4366   unsigned EVTBits = ExtVT.getSizeInBits();
4367
4368   unsigned NumZero  = 0;
4369   unsigned NumNonZero = 0;
4370   unsigned NonZeros = 0;
4371   bool IsAllConstants = true;
4372   SmallSet<SDValue, 8> Values;
4373   for (unsigned i = 0; i < NumElems; ++i) {
4374     SDValue Elt = Op.getOperand(i);
4375     if (Elt.getOpcode() == ISD::UNDEF)
4376       continue;
4377     Values.insert(Elt);
4378     if (Elt.getOpcode() != ISD::Constant &&
4379         Elt.getOpcode() != ISD::ConstantFP)
4380       IsAllConstants = false;
4381     if (X86::isZeroNode(Elt))
4382       NumZero++;
4383     else {
4384       NonZeros |= (1 << i);
4385       NumNonZero++;
4386     }
4387   }
4388
4389   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4390   if (NumNonZero == 0)
4391     return DAG.getUNDEF(VT);
4392
4393   // Special case for single non-zero, non-undef, element.
4394   if (NumNonZero == 1) {
4395     unsigned Idx = CountTrailingZeros_32(NonZeros);
4396     SDValue Item = Op.getOperand(Idx);
4397
4398     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4399     // the value are obviously zero, truncate the value to i32 and do the
4400     // insertion that way.  Only do this if the value is non-constant or if the
4401     // value is a constant being inserted into element 0.  It is cheaper to do
4402     // a constant pool load than it is to do a movd + shuffle.
4403     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4404         (!IsAllConstants || Idx == 0)) {
4405       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4406         // Handle SSE only.
4407         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4408         EVT VecVT = MVT::v4i32;
4409         unsigned VecElts = 4;
4410
4411         // Truncate the value (which may itself be a constant) to i32, and
4412         // convert it to a vector with movd (S2V+shuffle to zero extend).
4413         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4414         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4415         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4416                                            Subtarget->hasSSE2(), DAG);
4417
4418         // Now we have our 32-bit value zero extended in the low element of
4419         // a vector.  If Idx != 0, swizzle it into place.
4420         if (Idx != 0) {
4421           SmallVector<int, 4> Mask;
4422           Mask.push_back(Idx);
4423           for (unsigned i = 1; i != VecElts; ++i)
4424             Mask.push_back(i);
4425           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4426                                       DAG.getUNDEF(Item.getValueType()),
4427                                       &Mask[0]);
4428         }
4429         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4430       }
4431     }
4432
4433     // If we have a constant or non-constant insertion into the low element of
4434     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4435     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4436     // depending on what the source datatype is.
4437     if (Idx == 0) {
4438       if (NumZero == 0) {
4439         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4440       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4441           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4442         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4443         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4444         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4445                                            DAG);
4446       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4447         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4448         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4449         EVT MiddleVT = MVT::v4i32;
4450         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4451         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4452                                            Subtarget->hasSSE2(), DAG);
4453         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4454       }
4455     }
4456
4457     // Is it a vector logical left shift?
4458     if (NumElems == 2 && Idx == 1 &&
4459         X86::isZeroNode(Op.getOperand(0)) &&
4460         !X86::isZeroNode(Op.getOperand(1))) {
4461       unsigned NumBits = VT.getSizeInBits();
4462       return getVShift(true, VT,
4463                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4464                                    VT, Op.getOperand(1)),
4465                        NumBits/2, DAG, *this, dl);
4466     }
4467
4468     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4469       return SDValue();
4470
4471     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4472     // is a non-constant being inserted into an element other than the low one,
4473     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4474     // movd/movss) to move this into the low element, then shuffle it into
4475     // place.
4476     if (EVTBits == 32) {
4477       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4478
4479       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4480       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4481                                          Subtarget->hasSSE2(), DAG);
4482       SmallVector<int, 8> MaskVec;
4483       for (unsigned i = 0; i < NumElems; i++)
4484         MaskVec.push_back(i == Idx ? 0 : 1);
4485       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4486     }
4487   }
4488
4489   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4490   if (Values.size() == 1) {
4491     if (EVTBits == 32) {
4492       // Instead of a shuffle like this:
4493       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4494       // Check if it's possible to issue this instead.
4495       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4496       unsigned Idx = CountTrailingZeros_32(NonZeros);
4497       SDValue Item = Op.getOperand(Idx);
4498       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4499         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4500     }
4501     return SDValue();
4502   }
4503
4504   // A vector full of immediates; various special cases are already
4505   // handled, so this is best done with a single constant-pool load.
4506   if (IsAllConstants)
4507     return SDValue();
4508
4509   // Let legalizer expand 2-wide build_vectors.
4510   if (EVTBits == 64) {
4511     if (NumNonZero == 1) {
4512       // One half is zero or undef.
4513       unsigned Idx = CountTrailingZeros_32(NonZeros);
4514       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4515                                  Op.getOperand(Idx));
4516       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4517                                          Subtarget->hasSSE2(), DAG);
4518     }
4519     return SDValue();
4520   }
4521
4522   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4523   if (EVTBits == 8 && NumElems == 16) {
4524     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4525                                         *this);
4526     if (V.getNode()) return V;
4527   }
4528
4529   if (EVTBits == 16 && NumElems == 8) {
4530     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4531                                       *this);
4532     if (V.getNode()) return V;
4533   }
4534
4535   // If element VT is == 32 bits, turn it into a number of shuffles.
4536   SmallVector<SDValue, 8> V;
4537   V.resize(NumElems);
4538   if (NumElems == 4 && NumZero > 0) {
4539     for (unsigned i = 0; i < 4; ++i) {
4540       bool isZero = !(NonZeros & (1 << i));
4541       if (isZero)
4542         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4543       else
4544         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4545     }
4546
4547     for (unsigned i = 0; i < 2; ++i) {
4548       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4549         default: break;
4550         case 0:
4551           V[i] = V[i*2];  // Must be a zero vector.
4552           break;
4553         case 1:
4554           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4555           break;
4556         case 2:
4557           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4558           break;
4559         case 3:
4560           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4561           break;
4562       }
4563     }
4564
4565     SmallVector<int, 8> MaskVec;
4566     bool Reverse = (NonZeros & 0x3) == 2;
4567     for (unsigned i = 0; i < 2; ++i)
4568       MaskVec.push_back(Reverse ? 1-i : i);
4569     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4570     for (unsigned i = 0; i < 2; ++i)
4571       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4572     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4573   }
4574
4575   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4576     // Check for a build vector of consecutive loads.
4577     for (unsigned i = 0; i < NumElems; ++i)
4578       V[i] = Op.getOperand(i);
4579
4580     // Check for elements which are consecutive loads.
4581     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4582     if (LD.getNode())
4583       return LD;
4584
4585     // For SSE 4.1, use insertps to put the high elements into the low element.
4586     if (getSubtarget()->hasSSE41()) {
4587       SDValue Result;
4588       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4589         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4590       else
4591         Result = DAG.getUNDEF(VT);
4592
4593       for (unsigned i = 1; i < NumElems; ++i) {
4594         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4595         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4596                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4597       }
4598       return Result;
4599     }
4600
4601     // Otherwise, expand into a number of unpckl*, start by extending each of
4602     // our (non-undef) elements to the full vector width with the element in the
4603     // bottom slot of the vector (which generates no code for SSE).
4604     for (unsigned i = 0; i < NumElems; ++i) {
4605       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4606         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4607       else
4608         V[i] = DAG.getUNDEF(VT);
4609     }
4610
4611     // Next, we iteratively mix elements, e.g. for v4f32:
4612     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4613     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4614     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4615     unsigned EltStride = NumElems >> 1;
4616     while (EltStride != 0) {
4617       for (unsigned i = 0; i < EltStride; ++i) {
4618         // If V[i+EltStride] is undef and this is the first round of mixing,
4619         // then it is safe to just drop this shuffle: V[i] is already in the
4620         // right place, the one element (since it's the first round) being
4621         // inserted as undef can be dropped.  This isn't safe for successive
4622         // rounds because they will permute elements within both vectors.
4623         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4624             EltStride == NumElems/2)
4625           continue;
4626
4627         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4628       }
4629       EltStride >>= 1;
4630     }
4631     return V[0];
4632   }
4633   return SDValue();
4634 }
4635
4636 SDValue
4637 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4638   // We support concatenate two MMX registers and place them in a MMX
4639   // register.  This is better than doing a stack convert.
4640   DebugLoc dl = Op.getDebugLoc();
4641   EVT ResVT = Op.getValueType();
4642   assert(Op.getNumOperands() == 2);
4643   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4644          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4645   int Mask[2];
4646   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4647   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4648   InVec = Op.getOperand(1);
4649   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4650     unsigned NumElts = ResVT.getVectorNumElements();
4651     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4652     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4653                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4654   } else {
4655     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4656     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4657     Mask[0] = 0; Mask[1] = 2;
4658     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4659   }
4660   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4661 }
4662
4663 // v8i16 shuffles - Prefer shuffles in the following order:
4664 // 1. [all]   pshuflw, pshufhw, optional move
4665 // 2. [ssse3] 1 x pshufb
4666 // 3. [ssse3] 2 x pshufb + 1 x por
4667 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4668 SDValue
4669 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4670                                             SelectionDAG &DAG) const {
4671   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4672   SDValue V1 = SVOp->getOperand(0);
4673   SDValue V2 = SVOp->getOperand(1);
4674   DebugLoc dl = SVOp->getDebugLoc();
4675   SmallVector<int, 8> MaskVals;
4676
4677   // Determine if more than 1 of the words in each of the low and high quadwords
4678   // of the result come from the same quadword of one of the two inputs.  Undef
4679   // mask values count as coming from any quadword, for better codegen.
4680   SmallVector<unsigned, 4> LoQuad(4);
4681   SmallVector<unsigned, 4> HiQuad(4);
4682   BitVector InputQuads(4);
4683   for (unsigned i = 0; i < 8; ++i) {
4684     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4685     int EltIdx = SVOp->getMaskElt(i);
4686     MaskVals.push_back(EltIdx);
4687     if (EltIdx < 0) {
4688       ++Quad[0];
4689       ++Quad[1];
4690       ++Quad[2];
4691       ++Quad[3];
4692       continue;
4693     }
4694     ++Quad[EltIdx / 4];
4695     InputQuads.set(EltIdx / 4);
4696   }
4697
4698   int BestLoQuad = -1;
4699   unsigned MaxQuad = 1;
4700   for (unsigned i = 0; i < 4; ++i) {
4701     if (LoQuad[i] > MaxQuad) {
4702       BestLoQuad = i;
4703       MaxQuad = LoQuad[i];
4704     }
4705   }
4706
4707   int BestHiQuad = -1;
4708   MaxQuad = 1;
4709   for (unsigned i = 0; i < 4; ++i) {
4710     if (HiQuad[i] > MaxQuad) {
4711       BestHiQuad = i;
4712       MaxQuad = HiQuad[i];
4713     }
4714   }
4715
4716   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4717   // of the two input vectors, shuffle them into one input vector so only a
4718   // single pshufb instruction is necessary. If There are more than 2 input
4719   // quads, disable the next transformation since it does not help SSSE3.
4720   bool V1Used = InputQuads[0] || InputQuads[1];
4721   bool V2Used = InputQuads[2] || InputQuads[3];
4722   if (Subtarget->hasSSSE3()) {
4723     if (InputQuads.count() == 2 && V1Used && V2Used) {
4724       BestLoQuad = InputQuads.find_first();
4725       BestHiQuad = InputQuads.find_next(BestLoQuad);
4726     }
4727     if (InputQuads.count() > 2) {
4728       BestLoQuad = -1;
4729       BestHiQuad = -1;
4730     }
4731   }
4732
4733   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4734   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4735   // words from all 4 input quadwords.
4736   SDValue NewV;
4737   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4738     SmallVector<int, 8> MaskV;
4739     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4740     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4741     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4742                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4743                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4744     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4745
4746     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4747     // source words for the shuffle, to aid later transformations.
4748     bool AllWordsInNewV = true;
4749     bool InOrder[2] = { true, true };
4750     for (unsigned i = 0; i != 8; ++i) {
4751       int idx = MaskVals[i];
4752       if (idx != (int)i)
4753         InOrder[i/4] = false;
4754       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4755         continue;
4756       AllWordsInNewV = false;
4757       break;
4758     }
4759
4760     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4761     if (AllWordsInNewV) {
4762       for (int i = 0; i != 8; ++i) {
4763         int idx = MaskVals[i];
4764         if (idx < 0)
4765           continue;
4766         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4767         if ((idx != i) && idx < 4)
4768           pshufhw = false;
4769         if ((idx != i) && idx > 3)
4770           pshuflw = false;
4771       }
4772       V1 = NewV;
4773       V2Used = false;
4774       BestLoQuad = 0;
4775       BestHiQuad = 1;
4776     }
4777
4778     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4779     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4780     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4781       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4782       unsigned TargetMask = 0;
4783       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4784                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4785       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4786                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4787       V1 = NewV.getOperand(0);
4788       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4789     }
4790   }
4791
4792   // If we have SSSE3, and all words of the result are from 1 input vector,
4793   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4794   // is present, fall back to case 4.
4795   if (Subtarget->hasSSSE3()) {
4796     SmallVector<SDValue,16> pshufbMask;
4797
4798     // If we have elements from both input vectors, set the high bit of the
4799     // shuffle mask element to zero out elements that come from V2 in the V1
4800     // mask, and elements that come from V1 in the V2 mask, so that the two
4801     // results can be OR'd together.
4802     bool TwoInputs = V1Used && V2Used;
4803     for (unsigned i = 0; i != 8; ++i) {
4804       int EltIdx = MaskVals[i] * 2;
4805       if (TwoInputs && (EltIdx >= 16)) {
4806         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4807         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4808         continue;
4809       }
4810       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4811       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4812     }
4813     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4814     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4815                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4816                                  MVT::v16i8, &pshufbMask[0], 16));
4817     if (!TwoInputs)
4818       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4819
4820     // Calculate the shuffle mask for the second input, shuffle it, and
4821     // OR it with the first shuffled input.
4822     pshufbMask.clear();
4823     for (unsigned i = 0; i != 8; ++i) {
4824       int EltIdx = MaskVals[i] * 2;
4825       if (EltIdx < 16) {
4826         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4827         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4828         continue;
4829       }
4830       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4831       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4832     }
4833     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4834     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4835                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4836                                  MVT::v16i8, &pshufbMask[0], 16));
4837     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4838     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4839   }
4840
4841   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4842   // and update MaskVals with new element order.
4843   BitVector InOrder(8);
4844   if (BestLoQuad >= 0) {
4845     SmallVector<int, 8> MaskV;
4846     for (int i = 0; i != 4; ++i) {
4847       int idx = MaskVals[i];
4848       if (idx < 0) {
4849         MaskV.push_back(-1);
4850         InOrder.set(i);
4851       } else if ((idx / 4) == BestLoQuad) {
4852         MaskV.push_back(idx & 3);
4853         InOrder.set(i);
4854       } else {
4855         MaskV.push_back(-1);
4856       }
4857     }
4858     for (unsigned i = 4; i != 8; ++i)
4859       MaskV.push_back(i);
4860     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4861                                 &MaskV[0]);
4862
4863     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4864       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4865                                NewV.getOperand(0),
4866                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4867                                DAG);
4868   }
4869
4870   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4871   // and update MaskVals with the new element order.
4872   if (BestHiQuad >= 0) {
4873     SmallVector<int, 8> MaskV;
4874     for (unsigned i = 0; i != 4; ++i)
4875       MaskV.push_back(i);
4876     for (unsigned i = 4; i != 8; ++i) {
4877       int idx = MaskVals[i];
4878       if (idx < 0) {
4879         MaskV.push_back(-1);
4880         InOrder.set(i);
4881       } else if ((idx / 4) == BestHiQuad) {
4882         MaskV.push_back((idx & 3) + 4);
4883         InOrder.set(i);
4884       } else {
4885         MaskV.push_back(-1);
4886       }
4887     }
4888     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4889                                 &MaskV[0]);
4890
4891     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4892       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4893                               NewV.getOperand(0),
4894                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4895                               DAG);
4896   }
4897
4898   // In case BestHi & BestLo were both -1, which means each quadword has a word
4899   // from each of the four input quadwords, calculate the InOrder bitvector now
4900   // before falling through to the insert/extract cleanup.
4901   if (BestLoQuad == -1 && BestHiQuad == -1) {
4902     NewV = V1;
4903     for (int i = 0; i != 8; ++i)
4904       if (MaskVals[i] < 0 || MaskVals[i] == i)
4905         InOrder.set(i);
4906   }
4907
4908   // The other elements are put in the right place using pextrw and pinsrw.
4909   for (unsigned i = 0; i != 8; ++i) {
4910     if (InOrder[i])
4911       continue;
4912     int EltIdx = MaskVals[i];
4913     if (EltIdx < 0)
4914       continue;
4915     SDValue ExtOp = (EltIdx < 8)
4916     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4917                   DAG.getIntPtrConstant(EltIdx))
4918     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4919                   DAG.getIntPtrConstant(EltIdx - 8));
4920     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4921                        DAG.getIntPtrConstant(i));
4922   }
4923   return NewV;
4924 }
4925
4926 // v16i8 shuffles - Prefer shuffles in the following order:
4927 // 1. [ssse3] 1 x pshufb
4928 // 2. [ssse3] 2 x pshufb + 1 x por
4929 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4930 static
4931 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4932                                  SelectionDAG &DAG,
4933                                  const X86TargetLowering &TLI) {
4934   SDValue V1 = SVOp->getOperand(0);
4935   SDValue V2 = SVOp->getOperand(1);
4936   DebugLoc dl = SVOp->getDebugLoc();
4937   SmallVector<int, 16> MaskVals;
4938   SVOp->getMask(MaskVals);
4939
4940   // If we have SSSE3, case 1 is generated when all result bytes come from
4941   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4942   // present, fall back to case 3.
4943   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4944   bool V1Only = true;
4945   bool V2Only = true;
4946   for (unsigned i = 0; i < 16; ++i) {
4947     int EltIdx = MaskVals[i];
4948     if (EltIdx < 0)
4949       continue;
4950     if (EltIdx < 16)
4951       V2Only = false;
4952     else
4953       V1Only = false;
4954   }
4955
4956   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4957   if (TLI.getSubtarget()->hasSSSE3()) {
4958     SmallVector<SDValue,16> pshufbMask;
4959
4960     // If all result elements are from one input vector, then only translate
4961     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4962     //
4963     // Otherwise, we have elements from both input vectors, and must zero out
4964     // elements that come from V2 in the first mask, and V1 in the second mask
4965     // so that we can OR them together.
4966     bool TwoInputs = !(V1Only || V2Only);
4967     for (unsigned i = 0; i != 16; ++i) {
4968       int EltIdx = MaskVals[i];
4969       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4970         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4971         continue;
4972       }
4973       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4974     }
4975     // If all the elements are from V2, assign it to V1 and return after
4976     // building the first pshufb.
4977     if (V2Only)
4978       V1 = V2;
4979     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4980                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4981                                  MVT::v16i8, &pshufbMask[0], 16));
4982     if (!TwoInputs)
4983       return V1;
4984
4985     // Calculate the shuffle mask for the second input, shuffle it, and
4986     // OR it with the first shuffled input.
4987     pshufbMask.clear();
4988     for (unsigned i = 0; i != 16; ++i) {
4989       int EltIdx = MaskVals[i];
4990       if (EltIdx < 16) {
4991         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4992         continue;
4993       }
4994       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4995     }
4996     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4997                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4998                                  MVT::v16i8, &pshufbMask[0], 16));
4999     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5000   }
5001
5002   // No SSSE3 - Calculate in place words and then fix all out of place words
5003   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5004   // the 16 different words that comprise the two doublequadword input vectors.
5005   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5006   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5007   SDValue NewV = V2Only ? V2 : V1;
5008   for (int i = 0; i != 8; ++i) {
5009     int Elt0 = MaskVals[i*2];
5010     int Elt1 = MaskVals[i*2+1];
5011
5012     // This word of the result is all undef, skip it.
5013     if (Elt0 < 0 && Elt1 < 0)
5014       continue;
5015
5016     // This word of the result is already in the correct place, skip it.
5017     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5018       continue;
5019     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5020       continue;
5021
5022     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5023     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5024     SDValue InsElt;
5025
5026     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5027     // using a single extract together, load it and store it.
5028     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5029       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5030                            DAG.getIntPtrConstant(Elt1 / 2));
5031       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5032                         DAG.getIntPtrConstant(i));
5033       continue;
5034     }
5035
5036     // If Elt1 is defined, extract it from the appropriate source.  If the
5037     // source byte is not also odd, shift the extracted word left 8 bits
5038     // otherwise clear the bottom 8 bits if we need to do an or.
5039     if (Elt1 >= 0) {
5040       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5041                            DAG.getIntPtrConstant(Elt1 / 2));
5042       if ((Elt1 & 1) == 0)
5043         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5044                              DAG.getConstant(8, TLI.getShiftAmountTy()));
5045       else if (Elt0 >= 0)
5046         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5047                              DAG.getConstant(0xFF00, MVT::i16));
5048     }
5049     // If Elt0 is defined, extract it from the appropriate source.  If the
5050     // source byte is not also even, shift the extracted word right 8 bits. If
5051     // Elt1 was also defined, OR the extracted values together before
5052     // inserting them in the result.
5053     if (Elt0 >= 0) {
5054       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5055                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5056       if ((Elt0 & 1) != 0)
5057         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5058                               DAG.getConstant(8, TLI.getShiftAmountTy()));
5059       else if (Elt1 >= 0)
5060         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5061                              DAG.getConstant(0x00FF, MVT::i16));
5062       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5063                          : InsElt0;
5064     }
5065     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5066                        DAG.getIntPtrConstant(i));
5067   }
5068   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5069 }
5070
5071 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5072 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5073 /// done when every pair / quad of shuffle mask elements point to elements in
5074 /// the right sequence. e.g.
5075 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5076 static
5077 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5078                                  SelectionDAG &DAG, DebugLoc dl) {
5079   EVT VT = SVOp->getValueType(0);
5080   SDValue V1 = SVOp->getOperand(0);
5081   SDValue V2 = SVOp->getOperand(1);
5082   unsigned NumElems = VT.getVectorNumElements();
5083   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5084   EVT NewVT;
5085   switch (VT.getSimpleVT().SimpleTy) {
5086   default: assert(false && "Unexpected!");
5087   case MVT::v4f32: NewVT = MVT::v2f64; break;
5088   case MVT::v4i32: NewVT = MVT::v2i64; break;
5089   case MVT::v8i16: NewVT = MVT::v4i32; break;
5090   case MVT::v16i8: NewVT = MVT::v4i32; break;
5091   }
5092
5093   int Scale = NumElems / NewWidth;
5094   SmallVector<int, 8> MaskVec;
5095   for (unsigned i = 0; i < NumElems; i += Scale) {
5096     int StartIdx = -1;
5097     for (int j = 0; j < Scale; ++j) {
5098       int EltIdx = SVOp->getMaskElt(i+j);
5099       if (EltIdx < 0)
5100         continue;
5101       if (StartIdx == -1)
5102         StartIdx = EltIdx - (EltIdx % Scale);
5103       if (EltIdx != StartIdx + j)
5104         return SDValue();
5105     }
5106     if (StartIdx == -1)
5107       MaskVec.push_back(-1);
5108     else
5109       MaskVec.push_back(StartIdx / Scale);
5110   }
5111
5112   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5113   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5114   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5115 }
5116
5117 /// getVZextMovL - Return a zero-extending vector move low node.
5118 ///
5119 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5120                             SDValue SrcOp, SelectionDAG &DAG,
5121                             const X86Subtarget *Subtarget, DebugLoc dl) {
5122   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5123     LoadSDNode *LD = NULL;
5124     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5125       LD = dyn_cast<LoadSDNode>(SrcOp);
5126     if (!LD) {
5127       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5128       // instead.
5129       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5130       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5131           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5132           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5133           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5134         // PR2108
5135         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5136         return DAG.getNode(ISD::BITCAST, dl, VT,
5137                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5138                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5139                                                    OpVT,
5140                                                    SrcOp.getOperand(0)
5141                                                           .getOperand(0))));
5142       }
5143     }
5144   }
5145
5146   return DAG.getNode(ISD::BITCAST, dl, VT,
5147                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5148                                  DAG.getNode(ISD::BITCAST, dl,
5149                                              OpVT, SrcOp)));
5150 }
5151
5152 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5153 /// shuffles.
5154 static SDValue
5155 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5156   SDValue V1 = SVOp->getOperand(0);
5157   SDValue V2 = SVOp->getOperand(1);
5158   DebugLoc dl = SVOp->getDebugLoc();
5159   EVT VT = SVOp->getValueType(0);
5160
5161   SmallVector<std::pair<int, int>, 8> Locs;
5162   Locs.resize(4);
5163   SmallVector<int, 8> Mask1(4U, -1);
5164   SmallVector<int, 8> PermMask;
5165   SVOp->getMask(PermMask);
5166
5167   unsigned NumHi = 0;
5168   unsigned NumLo = 0;
5169   for (unsigned i = 0; i != 4; ++i) {
5170     int Idx = PermMask[i];
5171     if (Idx < 0) {
5172       Locs[i] = std::make_pair(-1, -1);
5173     } else {
5174       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5175       if (Idx < 4) {
5176         Locs[i] = std::make_pair(0, NumLo);
5177         Mask1[NumLo] = Idx;
5178         NumLo++;
5179       } else {
5180         Locs[i] = std::make_pair(1, NumHi);
5181         if (2+NumHi < 4)
5182           Mask1[2+NumHi] = Idx;
5183         NumHi++;
5184       }
5185     }
5186   }
5187
5188   if (NumLo <= 2 && NumHi <= 2) {
5189     // If no more than two elements come from either vector. This can be
5190     // implemented with two shuffles. First shuffle gather the elements.
5191     // The second shuffle, which takes the first shuffle as both of its
5192     // vector operands, put the elements into the right order.
5193     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5194
5195     SmallVector<int, 8> Mask2(4U, -1);
5196
5197     for (unsigned i = 0; i != 4; ++i) {
5198       if (Locs[i].first == -1)
5199         continue;
5200       else {
5201         unsigned Idx = (i < 2) ? 0 : 4;
5202         Idx += Locs[i].first * 2 + Locs[i].second;
5203         Mask2[i] = Idx;
5204       }
5205     }
5206
5207     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5208   } else if (NumLo == 3 || NumHi == 3) {
5209     // Otherwise, we must have three elements from one vector, call it X, and
5210     // one element from the other, call it Y.  First, use a shufps to build an
5211     // intermediate vector with the one element from Y and the element from X
5212     // that will be in the same half in the final destination (the indexes don't
5213     // matter). Then, use a shufps to build the final vector, taking the half
5214     // containing the element from Y from the intermediate, and the other half
5215     // from X.
5216     if (NumHi == 3) {
5217       // Normalize it so the 3 elements come from V1.
5218       CommuteVectorShuffleMask(PermMask, VT);
5219       std::swap(V1, V2);
5220     }
5221
5222     // Find the element from V2.
5223     unsigned HiIndex;
5224     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5225       int Val = PermMask[HiIndex];
5226       if (Val < 0)
5227         continue;
5228       if (Val >= 4)
5229         break;
5230     }
5231
5232     Mask1[0] = PermMask[HiIndex];
5233     Mask1[1] = -1;
5234     Mask1[2] = PermMask[HiIndex^1];
5235     Mask1[3] = -1;
5236     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5237
5238     if (HiIndex >= 2) {
5239       Mask1[0] = PermMask[0];
5240       Mask1[1] = PermMask[1];
5241       Mask1[2] = HiIndex & 1 ? 6 : 4;
5242       Mask1[3] = HiIndex & 1 ? 4 : 6;
5243       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5244     } else {
5245       Mask1[0] = HiIndex & 1 ? 2 : 0;
5246       Mask1[1] = HiIndex & 1 ? 0 : 2;
5247       Mask1[2] = PermMask[2];
5248       Mask1[3] = PermMask[3];
5249       if (Mask1[2] >= 0)
5250         Mask1[2] += 4;
5251       if (Mask1[3] >= 0)
5252         Mask1[3] += 4;
5253       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5254     }
5255   }
5256
5257   // Break it into (shuffle shuffle_hi, shuffle_lo).
5258   Locs.clear();
5259   SmallVector<int,8> LoMask(4U, -1);
5260   SmallVector<int,8> HiMask(4U, -1);
5261
5262   SmallVector<int,8> *MaskPtr = &LoMask;
5263   unsigned MaskIdx = 0;
5264   unsigned LoIdx = 0;
5265   unsigned HiIdx = 2;
5266   for (unsigned i = 0; i != 4; ++i) {
5267     if (i == 2) {
5268       MaskPtr = &HiMask;
5269       MaskIdx = 1;
5270       LoIdx = 0;
5271       HiIdx = 2;
5272     }
5273     int Idx = PermMask[i];
5274     if (Idx < 0) {
5275       Locs[i] = std::make_pair(-1, -1);
5276     } else if (Idx < 4) {
5277       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5278       (*MaskPtr)[LoIdx] = Idx;
5279       LoIdx++;
5280     } else {
5281       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5282       (*MaskPtr)[HiIdx] = Idx;
5283       HiIdx++;
5284     }
5285   }
5286
5287   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5288   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5289   SmallVector<int, 8> MaskOps;
5290   for (unsigned i = 0; i != 4; ++i) {
5291     if (Locs[i].first == -1) {
5292       MaskOps.push_back(-1);
5293     } else {
5294       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5295       MaskOps.push_back(Idx);
5296     }
5297   }
5298   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5299 }
5300
5301 static bool MayFoldVectorLoad(SDValue V) {
5302   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5303     V = V.getOperand(0);
5304   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5305     V = V.getOperand(0);
5306   if (MayFoldLoad(V))
5307     return true;
5308   return false;
5309 }
5310
5311 // FIXME: the version above should always be used. Since there's
5312 // a bug where several vector shuffles can't be folded because the
5313 // DAG is not updated during lowering and a node claims to have two
5314 // uses while it only has one, use this version, and let isel match
5315 // another instruction if the load really happens to have more than
5316 // one use. Remove this version after this bug get fixed.
5317 // rdar://8434668, PR8156
5318 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5319   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5320     V = V.getOperand(0);
5321   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5322     V = V.getOperand(0);
5323   if (ISD::isNormalLoad(V.getNode()))
5324     return true;
5325   return false;
5326 }
5327
5328 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5329 /// a vector extract, and if both can be later optimized into a single load.
5330 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5331 /// here because otherwise a target specific shuffle node is going to be
5332 /// emitted for this shuffle, and the optimization not done.
5333 /// FIXME: This is probably not the best approach, but fix the problem
5334 /// until the right path is decided.
5335 static
5336 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5337                                          const TargetLowering &TLI) {
5338   EVT VT = V.getValueType();
5339   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5340
5341   // Be sure that the vector shuffle is present in a pattern like this:
5342   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5343   if (!V.hasOneUse())
5344     return false;
5345
5346   SDNode *N = *V.getNode()->use_begin();
5347   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5348     return false;
5349
5350   SDValue EltNo = N->getOperand(1);
5351   if (!isa<ConstantSDNode>(EltNo))
5352     return false;
5353
5354   // If the bit convert changed the number of elements, it is unsafe
5355   // to examine the mask.
5356   bool HasShuffleIntoBitcast = false;
5357   if (V.getOpcode() == ISD::BITCAST) {
5358     EVT SrcVT = V.getOperand(0).getValueType();
5359     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5360       return false;
5361     V = V.getOperand(0);
5362     HasShuffleIntoBitcast = true;
5363   }
5364
5365   // Select the input vector, guarding against out of range extract vector.
5366   unsigned NumElems = VT.getVectorNumElements();
5367   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5368   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5369   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5370
5371   // Skip one more bit_convert if necessary
5372   if (V.getOpcode() == ISD::BITCAST)
5373     V = V.getOperand(0);
5374
5375   if (ISD::isNormalLoad(V.getNode())) {
5376     // Is the original load suitable?
5377     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5378
5379     // FIXME: avoid the multi-use bug that is preventing lots of
5380     // of foldings to be detected, this is still wrong of course, but
5381     // give the temporary desired behavior, and if it happens that
5382     // the load has real more uses, during isel it will not fold, and
5383     // will generate poor code.
5384     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5385       return false;
5386
5387     if (!HasShuffleIntoBitcast)
5388       return true;
5389
5390     // If there's a bitcast before the shuffle, check if the load type and
5391     // alignment is valid.
5392     unsigned Align = LN0->getAlignment();
5393     unsigned NewAlign =
5394       TLI.getTargetData()->getABITypeAlignment(
5395                                     VT.getTypeForEVT(*DAG.getContext()));
5396
5397     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5398       return false;
5399   }
5400
5401   return true;
5402 }
5403
5404 static
5405 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5406   EVT VT = Op.getValueType();
5407
5408   // Canonizalize to v2f64.
5409   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5410   return DAG.getNode(ISD::BITCAST, dl, VT,
5411                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5412                                           V1, DAG));
5413 }
5414
5415 static
5416 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5417                         bool HasSSE2) {
5418   SDValue V1 = Op.getOperand(0);
5419   SDValue V2 = Op.getOperand(1);
5420   EVT VT = Op.getValueType();
5421
5422   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5423
5424   if (HasSSE2 && VT == MVT::v2f64)
5425     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5426
5427   // v4f32 or v4i32
5428   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5429 }
5430
5431 static
5432 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5433   SDValue V1 = Op.getOperand(0);
5434   SDValue V2 = Op.getOperand(1);
5435   EVT VT = Op.getValueType();
5436
5437   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5438          "unsupported shuffle type");
5439
5440   if (V2.getOpcode() == ISD::UNDEF)
5441     V2 = V1;
5442
5443   // v4i32 or v4f32
5444   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5445 }
5446
5447 static
5448 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5449   SDValue V1 = Op.getOperand(0);
5450   SDValue V2 = Op.getOperand(1);
5451   EVT VT = Op.getValueType();
5452   unsigned NumElems = VT.getVectorNumElements();
5453
5454   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5455   // operand of these instructions is only memory, so check if there's a
5456   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5457   // same masks.
5458   bool CanFoldLoad = false;
5459
5460   // Trivial case, when V2 comes from a load.
5461   if (MayFoldVectorLoad(V2))
5462     CanFoldLoad = true;
5463
5464   // When V1 is a load, it can be folded later into a store in isel, example:
5465   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5466   //    turns into:
5467   //  (MOVLPSmr addr:$src1, VR128:$src2)
5468   // So, recognize this potential and also use MOVLPS or MOVLPD
5469   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5470     CanFoldLoad = true;
5471
5472   if (CanFoldLoad) {
5473     if (HasSSE2 && NumElems == 2)
5474       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5475
5476     if (NumElems == 4)
5477       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5478   }
5479
5480   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5481   // movl and movlp will both match v2i64, but v2i64 is never matched by
5482   // movl earlier because we make it strict to avoid messing with the movlp load
5483   // folding logic (see the code above getMOVLP call). Match it here then,
5484   // this is horrible, but will stay like this until we move all shuffle
5485   // matching to x86 specific nodes. Note that for the 1st condition all
5486   // types are matched with movsd.
5487   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5488     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5489   else if (HasSSE2)
5490     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5491
5492
5493   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5494
5495   // Invert the operand order and use SHUFPS to match it.
5496   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5497                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5498 }
5499
5500 static inline unsigned getUNPCKLOpcode(EVT VT) {
5501   switch(VT.getSimpleVT().SimpleTy) {
5502   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5503   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5504   case MVT::v4f32: return X86ISD::UNPCKLPS;
5505   case MVT::v2f64: return X86ISD::UNPCKLPD;
5506   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5507   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5508   default:
5509     llvm_unreachable("Unknow type for unpckl");
5510   }
5511   return 0;
5512 }
5513
5514 static inline unsigned getUNPCKHOpcode(EVT VT) {
5515   switch(VT.getSimpleVT().SimpleTy) {
5516   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5517   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5518   case MVT::v4f32: return X86ISD::UNPCKHPS;
5519   case MVT::v2f64: return X86ISD::UNPCKHPD;
5520   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5521   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5522   default:
5523     llvm_unreachable("Unknow type for unpckh");
5524   }
5525   return 0;
5526 }
5527
5528 static
5529 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5530                                const TargetLowering &TLI,
5531                                const X86Subtarget *Subtarget) {
5532   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5533   EVT VT = Op.getValueType();
5534   DebugLoc dl = Op.getDebugLoc();
5535   SDValue V1 = Op.getOperand(0);
5536   SDValue V2 = Op.getOperand(1);
5537
5538   if (isZeroShuffle(SVOp))
5539     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5540
5541   // Handle splat operations
5542   if (SVOp->isSplat()) {
5543     // Special case, this is the only place now where it's
5544     // allowed to return a vector_shuffle operation without
5545     // using a target specific node, because *hopefully* it
5546     // will be optimized away by the dag combiner.
5547     if (VT.getVectorNumElements() <= 4 &&
5548         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5549       return Op;
5550
5551     // Handle splats by matching through known masks
5552     if (VT.getVectorNumElements() <= 4)
5553       return SDValue();
5554
5555     // Canonicalize all of the remaining to v4f32.
5556     return PromoteSplat(SVOp, DAG);
5557   }
5558
5559   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5560   // do it!
5561   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5562     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5563     if (NewOp.getNode())
5564       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5565   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5566     // FIXME: Figure out a cleaner way to do this.
5567     // Try to make use of movq to zero out the top part.
5568     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5569       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5570       if (NewOp.getNode()) {
5571         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5572           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5573                               DAG, Subtarget, dl);
5574       }
5575     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5576       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5577       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5578         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5579                             DAG, Subtarget, dl);
5580     }
5581   }
5582   return SDValue();
5583 }
5584
5585 SDValue
5586 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5587   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5588   SDValue V1 = Op.getOperand(0);
5589   SDValue V2 = Op.getOperand(1);
5590   EVT VT = Op.getValueType();
5591   DebugLoc dl = Op.getDebugLoc();
5592   unsigned NumElems = VT.getVectorNumElements();
5593   bool isMMX = VT.getSizeInBits() == 64;
5594   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5595   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5596   bool V1IsSplat = false;
5597   bool V2IsSplat = false;
5598   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5599   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5600   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5601   MachineFunction &MF = DAG.getMachineFunction();
5602   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5603
5604   // Shuffle operations on MMX not supported.
5605   if (isMMX)
5606     return Op;
5607
5608   // Vector shuffle lowering takes 3 steps:
5609   //
5610   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5611   //    narrowing and commutation of operands should be handled.
5612   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5613   //    shuffle nodes.
5614   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5615   //    so the shuffle can be broken into other shuffles and the legalizer can
5616   //    try the lowering again.
5617   //
5618   // The general ideia is that no vector_shuffle operation should be left to
5619   // be matched during isel, all of them must be converted to a target specific
5620   // node here.
5621
5622   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5623   // narrowing and commutation of operands should be handled. The actual code
5624   // doesn't include all of those, work in progress...
5625   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5626   if (NewOp.getNode())
5627     return NewOp;
5628
5629   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5630   // unpckh_undef). Only use pshufd if speed is more important than size.
5631   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5632     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5633       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5634   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5635     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5636       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5637
5638   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5639       RelaxedMayFoldVectorLoad(V1))
5640     return getMOVDDup(Op, dl, V1, DAG);
5641
5642   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5643     return getMOVHighToLow(Op, dl, DAG);
5644
5645   // Use to match splats
5646   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5647       (VT == MVT::v2f64 || VT == MVT::v2i64))
5648     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5649
5650   if (X86::isPSHUFDMask(SVOp)) {
5651     // The actual implementation will match the mask in the if above and then
5652     // during isel it can match several different instructions, not only pshufd
5653     // as its name says, sad but true, emulate the behavior for now...
5654     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5655         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5656
5657     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5658
5659     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5660       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5661
5662     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5663       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5664                                   TargetMask, DAG);
5665
5666     if (VT == MVT::v4f32)
5667       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5668                                   TargetMask, DAG);
5669   }
5670
5671   // Check if this can be converted into a logical shift.
5672   bool isLeft = false;
5673   unsigned ShAmt = 0;
5674   SDValue ShVal;
5675   bool isShift = getSubtarget()->hasSSE2() &&
5676     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5677   if (isShift && ShVal.hasOneUse()) {
5678     // If the shifted value has multiple uses, it may be cheaper to use
5679     // v_set0 + movlhps or movhlps, etc.
5680     EVT EltVT = VT.getVectorElementType();
5681     ShAmt *= EltVT.getSizeInBits();
5682     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5683   }
5684
5685   if (X86::isMOVLMask(SVOp)) {
5686     if (V1IsUndef)
5687       return V2;
5688     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5689       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5690     if (!X86::isMOVLPMask(SVOp)) {
5691       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5692         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5693
5694       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5695         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5696     }
5697   }
5698
5699   // FIXME: fold these into legal mask.
5700   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5701     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5702
5703   if (X86::isMOVHLPSMask(SVOp))
5704     return getMOVHighToLow(Op, dl, DAG);
5705
5706   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5707     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5708
5709   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5710     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5711
5712   if (X86::isMOVLPMask(SVOp))
5713     return getMOVLP(Op, dl, DAG, HasSSE2);
5714
5715   if (ShouldXformToMOVHLPS(SVOp) ||
5716       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5717     return CommuteVectorShuffle(SVOp, DAG);
5718
5719   if (isShift) {
5720     // No better options. Use a vshl / vsrl.
5721     EVT EltVT = VT.getVectorElementType();
5722     ShAmt *= EltVT.getSizeInBits();
5723     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5724   }
5725
5726   bool Commuted = false;
5727   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5728   // 1,1,1,1 -> v8i16 though.
5729   V1IsSplat = isSplatVector(V1.getNode());
5730   V2IsSplat = isSplatVector(V2.getNode());
5731
5732   // Canonicalize the splat or undef, if present, to be on the RHS.
5733   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5734     Op = CommuteVectorShuffle(SVOp, DAG);
5735     SVOp = cast<ShuffleVectorSDNode>(Op);
5736     V1 = SVOp->getOperand(0);
5737     V2 = SVOp->getOperand(1);
5738     std::swap(V1IsSplat, V2IsSplat);
5739     std::swap(V1IsUndef, V2IsUndef);
5740     Commuted = true;
5741   }
5742
5743   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5744     // Shuffling low element of v1 into undef, just return v1.
5745     if (V2IsUndef)
5746       return V1;
5747     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5748     // the instruction selector will not match, so get a canonical MOVL with
5749     // swapped operands to undo the commute.
5750     return getMOVL(DAG, dl, VT, V2, V1);
5751   }
5752
5753   if (X86::isUNPCKLMask(SVOp))
5754     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5755
5756   if (X86::isUNPCKHMask(SVOp))
5757     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5758
5759   if (V2IsSplat) {
5760     // Normalize mask so all entries that point to V2 points to its first
5761     // element then try to match unpck{h|l} again. If match, return a
5762     // new vector_shuffle with the corrected mask.
5763     SDValue NewMask = NormalizeMask(SVOp, DAG);
5764     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5765     if (NSVOp != SVOp) {
5766       if (X86::isUNPCKLMask(NSVOp, true)) {
5767         return NewMask;
5768       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5769         return NewMask;
5770       }
5771     }
5772   }
5773
5774   if (Commuted) {
5775     // Commute is back and try unpck* again.
5776     // FIXME: this seems wrong.
5777     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5778     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5779
5780     if (X86::isUNPCKLMask(NewSVOp))
5781       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5782
5783     if (X86::isUNPCKHMask(NewSVOp))
5784       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5785   }
5786
5787   // Normalize the node to match x86 shuffle ops if needed
5788   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5789     return CommuteVectorShuffle(SVOp, DAG);
5790
5791   // The checks below are all present in isShuffleMaskLegal, but they are
5792   // inlined here right now to enable us to directly emit target specific
5793   // nodes, and remove one by one until they don't return Op anymore.
5794   SmallVector<int, 16> M;
5795   SVOp->getMask(M);
5796
5797   if (isPALIGNRMask(M, VT, HasSSSE3))
5798     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5799                                 X86::getShufflePALIGNRImmediate(SVOp),
5800                                 DAG);
5801
5802   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5803       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5804     if (VT == MVT::v2f64)
5805       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5806     if (VT == MVT::v2i64)
5807       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5808   }
5809
5810   if (isPSHUFHWMask(M, VT))
5811     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5812                                 X86::getShufflePSHUFHWImmediate(SVOp),
5813                                 DAG);
5814
5815   if (isPSHUFLWMask(M, VT))
5816     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5817                                 X86::getShufflePSHUFLWImmediate(SVOp),
5818                                 DAG);
5819
5820   if (isSHUFPMask(M, VT)) {
5821     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5822     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5823       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5824                                   TargetMask, DAG);
5825     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5826       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5827                                   TargetMask, DAG);
5828   }
5829
5830   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5831     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5832       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5833   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5834     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5835       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5836
5837   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5838   if (VT == MVT::v8i16) {
5839     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5840     if (NewOp.getNode())
5841       return NewOp;
5842   }
5843
5844   if (VT == MVT::v16i8) {
5845     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5846     if (NewOp.getNode())
5847       return NewOp;
5848   }
5849
5850   // Handle all 4 wide cases with a number of shuffles.
5851   if (NumElems == 4)
5852     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5853
5854   return SDValue();
5855 }
5856
5857 SDValue
5858 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5859                                                 SelectionDAG &DAG) const {
5860   EVT VT = Op.getValueType();
5861   DebugLoc dl = Op.getDebugLoc();
5862   if (VT.getSizeInBits() == 8) {
5863     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5864                                     Op.getOperand(0), Op.getOperand(1));
5865     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5866                                     DAG.getValueType(VT));
5867     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5868   } else if (VT.getSizeInBits() == 16) {
5869     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5870     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5871     if (Idx == 0)
5872       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5873                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5874                                      DAG.getNode(ISD::BITCAST, dl,
5875                                                  MVT::v4i32,
5876                                                  Op.getOperand(0)),
5877                                      Op.getOperand(1)));
5878     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5879                                     Op.getOperand(0), Op.getOperand(1));
5880     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5881                                     DAG.getValueType(VT));
5882     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5883   } else if (VT == MVT::f32) {
5884     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5885     // the result back to FR32 register. It's only worth matching if the
5886     // result has a single use which is a store or a bitcast to i32.  And in
5887     // the case of a store, it's not worth it if the index is a constant 0,
5888     // because a MOVSSmr can be used instead, which is smaller and faster.
5889     if (!Op.hasOneUse())
5890       return SDValue();
5891     SDNode *User = *Op.getNode()->use_begin();
5892     if ((User->getOpcode() != ISD::STORE ||
5893          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5894           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5895         (User->getOpcode() != ISD::BITCAST ||
5896          User->getValueType(0) != MVT::i32))
5897       return SDValue();
5898     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5899                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5900                                               Op.getOperand(0)),
5901                                               Op.getOperand(1));
5902     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5903   } else if (VT == MVT::i32) {
5904     // ExtractPS works with constant index.
5905     if (isa<ConstantSDNode>(Op.getOperand(1)))
5906       return Op;
5907   }
5908   return SDValue();
5909 }
5910
5911
5912 SDValue
5913 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5914                                            SelectionDAG &DAG) const {
5915   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5916     return SDValue();
5917
5918   if (Subtarget->hasSSE41()) {
5919     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5920     if (Res.getNode())
5921       return Res;
5922   }
5923
5924   EVT VT = Op.getValueType();
5925   DebugLoc dl = Op.getDebugLoc();
5926   // TODO: handle v16i8.
5927   if (VT.getSizeInBits() == 16) {
5928     SDValue Vec = Op.getOperand(0);
5929     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5930     if (Idx == 0)
5931       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5932                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5933                                      DAG.getNode(ISD::BITCAST, dl,
5934                                                  MVT::v4i32, Vec),
5935                                      Op.getOperand(1)));
5936     // Transform it so it match pextrw which produces a 32-bit result.
5937     EVT EltVT = MVT::i32;
5938     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5939                                     Op.getOperand(0), Op.getOperand(1));
5940     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5941                                     DAG.getValueType(VT));
5942     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5943   } else if (VT.getSizeInBits() == 32) {
5944     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5945     if (Idx == 0)
5946       return Op;
5947
5948     // SHUFPS the element to the lowest double word, then movss.
5949     int Mask[4] = { Idx, -1, -1, -1 };
5950     EVT VVT = Op.getOperand(0).getValueType();
5951     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5952                                        DAG.getUNDEF(VVT), Mask);
5953     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5954                        DAG.getIntPtrConstant(0));
5955   } else if (VT.getSizeInBits() == 64) {
5956     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5957     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5958     //        to match extract_elt for f64.
5959     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5960     if (Idx == 0)
5961       return Op;
5962
5963     // UNPCKHPD the element to the lowest double word, then movsd.
5964     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5965     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5966     int Mask[2] = { 1, -1 };
5967     EVT VVT = Op.getOperand(0).getValueType();
5968     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5969                                        DAG.getUNDEF(VVT), Mask);
5970     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5971                        DAG.getIntPtrConstant(0));
5972   }
5973
5974   return SDValue();
5975 }
5976
5977 SDValue
5978 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5979                                                SelectionDAG &DAG) const {
5980   EVT VT = Op.getValueType();
5981   EVT EltVT = VT.getVectorElementType();
5982   DebugLoc dl = Op.getDebugLoc();
5983
5984   SDValue N0 = Op.getOperand(0);
5985   SDValue N1 = Op.getOperand(1);
5986   SDValue N2 = Op.getOperand(2);
5987
5988   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5989       isa<ConstantSDNode>(N2)) {
5990     unsigned Opc;
5991     if (VT == MVT::v8i16)
5992       Opc = X86ISD::PINSRW;
5993     else if (VT == MVT::v16i8)
5994       Opc = X86ISD::PINSRB;
5995     else
5996       Opc = X86ISD::PINSRB;
5997
5998     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5999     // argument.
6000     if (N1.getValueType() != MVT::i32)
6001       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6002     if (N2.getValueType() != MVT::i32)
6003       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6004     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6005   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6006     // Bits [7:6] of the constant are the source select.  This will always be
6007     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6008     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6009     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6010     // Bits [5:4] of the constant are the destination select.  This is the
6011     //  value of the incoming immediate.
6012     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6013     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6014     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6015     // Create this as a scalar to vector..
6016     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6017     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6018   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6019     // PINSR* works with constant index.
6020     return Op;
6021   }
6022   return SDValue();
6023 }
6024
6025 SDValue
6026 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6027   EVT VT = Op.getValueType();
6028   EVT EltVT = VT.getVectorElementType();
6029
6030   if (Subtarget->hasSSE41())
6031     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6032
6033   if (EltVT == MVT::i8)
6034     return SDValue();
6035
6036   DebugLoc dl = Op.getDebugLoc();
6037   SDValue N0 = Op.getOperand(0);
6038   SDValue N1 = Op.getOperand(1);
6039   SDValue N2 = Op.getOperand(2);
6040
6041   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6042     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6043     // as its second argument.
6044     if (N1.getValueType() != MVT::i32)
6045       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6046     if (N2.getValueType() != MVT::i32)
6047       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6048     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6049   }
6050   return SDValue();
6051 }
6052
6053 SDValue
6054 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6055   DebugLoc dl = Op.getDebugLoc();
6056
6057   if (Op.getValueType() == MVT::v1i64 &&
6058       Op.getOperand(0).getValueType() == MVT::i64)
6059     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6060
6061   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6062   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6063          "Expected an SSE type!");
6064   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6065                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6066 }
6067
6068 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6069 // a simple subregister reference or explicit instructions to grab
6070 // upper bits of a vector.
6071 SDValue
6072 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6073   if (Subtarget->hasAVX()) {
6074     DebugLoc dl = Op.getNode()->getDebugLoc();
6075     SDValue Vec = Op.getNode()->getOperand(0);
6076     SDValue Idx = Op.getNode()->getOperand(1);
6077
6078     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6079         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6080         return Extract128BitVector(Vec, Idx, DAG, dl);
6081     }
6082   }
6083   return SDValue();
6084 }
6085
6086 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6087 // simple superregister reference or explicit instructions to insert
6088 // the upper bits of a vector.
6089 SDValue
6090 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6091   if (Subtarget->hasAVX()) {
6092     DebugLoc dl = Op.getNode()->getDebugLoc();
6093     SDValue Vec = Op.getNode()->getOperand(0);
6094     SDValue SubVec = Op.getNode()->getOperand(1);
6095     SDValue Idx = Op.getNode()->getOperand(2);
6096
6097     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6098         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6099       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6100     }
6101   }
6102   return SDValue();
6103 }
6104
6105 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6106 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6107 // one of the above mentioned nodes. It has to be wrapped because otherwise
6108 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6109 // be used to form addressing mode. These wrapped nodes will be selected
6110 // into MOV32ri.
6111 SDValue
6112 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6113   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6114
6115   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6116   // global base reg.
6117   unsigned char OpFlag = 0;
6118   unsigned WrapperKind = X86ISD::Wrapper;
6119   CodeModel::Model M = getTargetMachine().getCodeModel();
6120
6121   if (Subtarget->isPICStyleRIPRel() &&
6122       (M == CodeModel::Small || M == CodeModel::Kernel))
6123     WrapperKind = X86ISD::WrapperRIP;
6124   else if (Subtarget->isPICStyleGOT())
6125     OpFlag = X86II::MO_GOTOFF;
6126   else if (Subtarget->isPICStyleStubPIC())
6127     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6128
6129   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6130                                              CP->getAlignment(),
6131                                              CP->getOffset(), OpFlag);
6132   DebugLoc DL = CP->getDebugLoc();
6133   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6134   // With PIC, the address is actually $g + Offset.
6135   if (OpFlag) {
6136     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6137                          DAG.getNode(X86ISD::GlobalBaseReg,
6138                                      DebugLoc(), getPointerTy()),
6139                          Result);
6140   }
6141
6142   return Result;
6143 }
6144
6145 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6146   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6147
6148   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6149   // global base reg.
6150   unsigned char OpFlag = 0;
6151   unsigned WrapperKind = X86ISD::Wrapper;
6152   CodeModel::Model M = getTargetMachine().getCodeModel();
6153
6154   if (Subtarget->isPICStyleRIPRel() &&
6155       (M == CodeModel::Small || M == CodeModel::Kernel))
6156     WrapperKind = X86ISD::WrapperRIP;
6157   else if (Subtarget->isPICStyleGOT())
6158     OpFlag = X86II::MO_GOTOFF;
6159   else if (Subtarget->isPICStyleStubPIC())
6160     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6161
6162   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6163                                           OpFlag);
6164   DebugLoc DL = JT->getDebugLoc();
6165   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6166
6167   // With PIC, the address is actually $g + Offset.
6168   if (OpFlag)
6169     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6170                          DAG.getNode(X86ISD::GlobalBaseReg,
6171                                      DebugLoc(), getPointerTy()),
6172                          Result);
6173
6174   return Result;
6175 }
6176
6177 SDValue
6178 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6179   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6180
6181   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6182   // global base reg.
6183   unsigned char OpFlag = 0;
6184   unsigned WrapperKind = X86ISD::Wrapper;
6185   CodeModel::Model M = getTargetMachine().getCodeModel();
6186
6187   if (Subtarget->isPICStyleRIPRel() &&
6188       (M == CodeModel::Small || M == CodeModel::Kernel))
6189     WrapperKind = X86ISD::WrapperRIP;
6190   else if (Subtarget->isPICStyleGOT())
6191     OpFlag = X86II::MO_GOTOFF;
6192   else if (Subtarget->isPICStyleStubPIC())
6193     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6194
6195   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6196
6197   DebugLoc DL = Op.getDebugLoc();
6198   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6199
6200
6201   // With PIC, the address is actually $g + Offset.
6202   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6203       !Subtarget->is64Bit()) {
6204     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6205                          DAG.getNode(X86ISD::GlobalBaseReg,
6206                                      DebugLoc(), getPointerTy()),
6207                          Result);
6208   }
6209
6210   return Result;
6211 }
6212
6213 SDValue
6214 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6215   // Create the TargetBlockAddressAddress node.
6216   unsigned char OpFlags =
6217     Subtarget->ClassifyBlockAddressReference();
6218   CodeModel::Model M = getTargetMachine().getCodeModel();
6219   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6220   DebugLoc dl = Op.getDebugLoc();
6221   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6222                                        /*isTarget=*/true, OpFlags);
6223
6224   if (Subtarget->isPICStyleRIPRel() &&
6225       (M == CodeModel::Small || M == CodeModel::Kernel))
6226     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6227   else
6228     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6229
6230   // With PIC, the address is actually $g + Offset.
6231   if (isGlobalRelativeToPICBase(OpFlags)) {
6232     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6233                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6234                          Result);
6235   }
6236
6237   return Result;
6238 }
6239
6240 SDValue
6241 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6242                                       int64_t Offset,
6243                                       SelectionDAG &DAG) const {
6244   // Create the TargetGlobalAddress node, folding in the constant
6245   // offset if it is legal.
6246   unsigned char OpFlags =
6247     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6248   CodeModel::Model M = getTargetMachine().getCodeModel();
6249   SDValue Result;
6250   if (OpFlags == X86II::MO_NO_FLAG &&
6251       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6252     // A direct static reference to a global.
6253     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6254     Offset = 0;
6255   } else {
6256     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6257   }
6258
6259   if (Subtarget->isPICStyleRIPRel() &&
6260       (M == CodeModel::Small || M == CodeModel::Kernel))
6261     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6262   else
6263     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6264
6265   // With PIC, the address is actually $g + Offset.
6266   if (isGlobalRelativeToPICBase(OpFlags)) {
6267     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6268                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6269                          Result);
6270   }
6271
6272   // For globals that require a load from a stub to get the address, emit the
6273   // load.
6274   if (isGlobalStubReference(OpFlags))
6275     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6276                          MachinePointerInfo::getGOT(), false, false, 0);
6277
6278   // If there was a non-zero offset that we didn't fold, create an explicit
6279   // addition for it.
6280   if (Offset != 0)
6281     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6282                          DAG.getConstant(Offset, getPointerTy()));
6283
6284   return Result;
6285 }
6286
6287 SDValue
6288 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6289   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6290   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6291   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6292 }
6293
6294 static SDValue
6295 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6296            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6297            unsigned char OperandFlags) {
6298   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6299   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6300   DebugLoc dl = GA->getDebugLoc();
6301   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6302                                            GA->getValueType(0),
6303                                            GA->getOffset(),
6304                                            OperandFlags);
6305   if (InFlag) {
6306     SDValue Ops[] = { Chain,  TGA, *InFlag };
6307     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6308   } else {
6309     SDValue Ops[]  = { Chain, TGA };
6310     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6311   }
6312
6313   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6314   MFI->setAdjustsStack(true);
6315
6316   SDValue Flag = Chain.getValue(1);
6317   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6318 }
6319
6320 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6321 static SDValue
6322 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6323                                 const EVT PtrVT) {
6324   SDValue InFlag;
6325   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6326   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6327                                      DAG.getNode(X86ISD::GlobalBaseReg,
6328                                                  DebugLoc(), PtrVT), InFlag);
6329   InFlag = Chain.getValue(1);
6330
6331   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6332 }
6333
6334 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6335 static SDValue
6336 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6337                                 const EVT PtrVT) {
6338   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6339                     X86::RAX, X86II::MO_TLSGD);
6340 }
6341
6342 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6343 // "local exec" model.
6344 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6345                                    const EVT PtrVT, TLSModel::Model model,
6346                                    bool is64Bit) {
6347   DebugLoc dl = GA->getDebugLoc();
6348
6349   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6350   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6351                                                          is64Bit ? 257 : 256));
6352
6353   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6354                                       DAG.getIntPtrConstant(0),
6355                                       MachinePointerInfo(Ptr), false, false, 0);
6356
6357   unsigned char OperandFlags = 0;
6358   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6359   // initialexec.
6360   unsigned WrapperKind = X86ISD::Wrapper;
6361   if (model == TLSModel::LocalExec) {
6362     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6363   } else if (is64Bit) {
6364     assert(model == TLSModel::InitialExec);
6365     OperandFlags = X86II::MO_GOTTPOFF;
6366     WrapperKind = X86ISD::WrapperRIP;
6367   } else {
6368     assert(model == TLSModel::InitialExec);
6369     OperandFlags = X86II::MO_INDNTPOFF;
6370   }
6371
6372   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6373   // exec)
6374   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6375                                            GA->getValueType(0),
6376                                            GA->getOffset(), OperandFlags);
6377   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6378
6379   if (model == TLSModel::InitialExec)
6380     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6381                          MachinePointerInfo::getGOT(), false, false, 0);
6382
6383   // The address of the thread local variable is the add of the thread
6384   // pointer with the offset of the variable.
6385   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6386 }
6387
6388 SDValue
6389 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6390
6391   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6392   const GlobalValue *GV = GA->getGlobal();
6393
6394   if (Subtarget->isTargetELF()) {
6395     // TODO: implement the "local dynamic" model
6396     // TODO: implement the "initial exec"model for pic executables
6397
6398     // If GV is an alias then use the aliasee for determining
6399     // thread-localness.
6400     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6401       GV = GA->resolveAliasedGlobal(false);
6402
6403     TLSModel::Model model
6404       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6405
6406     switch (model) {
6407       case TLSModel::GeneralDynamic:
6408       case TLSModel::LocalDynamic: // not implemented
6409         if (Subtarget->is64Bit())
6410           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6411         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6412
6413       case TLSModel::InitialExec:
6414       case TLSModel::LocalExec:
6415         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6416                                    Subtarget->is64Bit());
6417     }
6418   } else if (Subtarget->isTargetDarwin()) {
6419     // Darwin only has one model of TLS.  Lower to that.
6420     unsigned char OpFlag = 0;
6421     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6422                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6423
6424     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6425     // global base reg.
6426     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6427                   !Subtarget->is64Bit();
6428     if (PIC32)
6429       OpFlag = X86II::MO_TLVP_PIC_BASE;
6430     else
6431       OpFlag = X86II::MO_TLVP;
6432     DebugLoc DL = Op.getDebugLoc();
6433     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6434                                                 GA->getValueType(0),
6435                                                 GA->getOffset(), OpFlag);
6436     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6437
6438     // With PIC32, the address is actually $g + Offset.
6439     if (PIC32)
6440       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6441                            DAG.getNode(X86ISD::GlobalBaseReg,
6442                                        DebugLoc(), getPointerTy()),
6443                            Offset);
6444
6445     // Lowering the machine isd will make sure everything is in the right
6446     // location.
6447     SDValue Chain = DAG.getEntryNode();
6448     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6449     SDValue Args[] = { Chain, Offset };
6450     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6451
6452     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6453     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6454     MFI->setAdjustsStack(true);
6455
6456     // And our return value (tls address) is in the standard call return value
6457     // location.
6458     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6459     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6460   }
6461
6462   assert(false &&
6463          "TLS not implemented for this target.");
6464
6465   llvm_unreachable("Unreachable");
6466   return SDValue();
6467 }
6468
6469
6470 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6471 /// take a 2 x i32 value to shift plus a shift amount.
6472 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6473   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6474   EVT VT = Op.getValueType();
6475   unsigned VTBits = VT.getSizeInBits();
6476   DebugLoc dl = Op.getDebugLoc();
6477   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6478   SDValue ShOpLo = Op.getOperand(0);
6479   SDValue ShOpHi = Op.getOperand(1);
6480   SDValue ShAmt  = Op.getOperand(2);
6481   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6482                                      DAG.getConstant(VTBits - 1, MVT::i8))
6483                        : DAG.getConstant(0, VT);
6484
6485   SDValue Tmp2, Tmp3;
6486   if (Op.getOpcode() == ISD::SHL_PARTS) {
6487     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6488     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6489   } else {
6490     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6491     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6492   }
6493
6494   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6495                                 DAG.getConstant(VTBits, MVT::i8));
6496   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6497                              AndNode, DAG.getConstant(0, MVT::i8));
6498
6499   SDValue Hi, Lo;
6500   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6501   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6502   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6503
6504   if (Op.getOpcode() == ISD::SHL_PARTS) {
6505     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6506     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6507   } else {
6508     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6509     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6510   }
6511
6512   SDValue Ops[2] = { Lo, Hi };
6513   return DAG.getMergeValues(Ops, 2, dl);
6514 }
6515
6516 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6517                                            SelectionDAG &DAG) const {
6518   EVT SrcVT = Op.getOperand(0).getValueType();
6519
6520   if (SrcVT.isVector())
6521     return SDValue();
6522
6523   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6524          "Unknown SINT_TO_FP to lower!");
6525
6526   // These are really Legal; return the operand so the caller accepts it as
6527   // Legal.
6528   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6529     return Op;
6530   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6531       Subtarget->is64Bit()) {
6532     return Op;
6533   }
6534
6535   DebugLoc dl = Op.getDebugLoc();
6536   unsigned Size = SrcVT.getSizeInBits()/8;
6537   MachineFunction &MF = DAG.getMachineFunction();
6538   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6539   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6540   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6541                                StackSlot,
6542                                MachinePointerInfo::getFixedStack(SSFI),
6543                                false, false, 0);
6544   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6545 }
6546
6547 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6548                                      SDValue StackSlot,
6549                                      SelectionDAG &DAG) const {
6550   // Build the FILD
6551   DebugLoc DL = Op.getDebugLoc();
6552   SDVTList Tys;
6553   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6554   if (useSSE)
6555     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6556   else
6557     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6558
6559   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6560
6561   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6562   MachineMemOperand *MMO =
6563     DAG.getMachineFunction()
6564     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6565                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6566
6567   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6568   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6569                                            X86ISD::FILD, DL,
6570                                            Tys, Ops, array_lengthof(Ops),
6571                                            SrcVT, MMO);
6572
6573   if (useSSE) {
6574     Chain = Result.getValue(1);
6575     SDValue InFlag = Result.getValue(2);
6576
6577     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6578     // shouldn't be necessary except that RFP cannot be live across
6579     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6580     MachineFunction &MF = DAG.getMachineFunction();
6581     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6582     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6583     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6584     Tys = DAG.getVTList(MVT::Other);
6585     SDValue Ops[] = {
6586       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6587     };
6588     MachineMemOperand *MMO =
6589       DAG.getMachineFunction()
6590       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6591                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6592
6593     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6594                                     Ops, array_lengthof(Ops),
6595                                     Op.getValueType(), MMO);
6596     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6597                          MachinePointerInfo::getFixedStack(SSFI),
6598                          false, false, 0);
6599   }
6600
6601   return Result;
6602 }
6603
6604 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6605 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6606                                                SelectionDAG &DAG) const {
6607   // This algorithm is not obvious. Here it is in C code, more or less:
6608   /*
6609     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6610       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6611       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6612
6613       // Copy ints to xmm registers.
6614       __m128i xh = _mm_cvtsi32_si128( hi );
6615       __m128i xl = _mm_cvtsi32_si128( lo );
6616
6617       // Combine into low half of a single xmm register.
6618       __m128i x = _mm_unpacklo_epi32( xh, xl );
6619       __m128d d;
6620       double sd;
6621
6622       // Merge in appropriate exponents to give the integer bits the right
6623       // magnitude.
6624       x = _mm_unpacklo_epi32( x, exp );
6625
6626       // Subtract away the biases to deal with the IEEE-754 double precision
6627       // implicit 1.
6628       d = _mm_sub_pd( (__m128d) x, bias );
6629
6630       // All conversions up to here are exact. The correctly rounded result is
6631       // calculated using the current rounding mode using the following
6632       // horizontal add.
6633       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6634       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6635                                 // store doesn't really need to be here (except
6636                                 // maybe to zero the other double)
6637       return sd;
6638     }
6639   */
6640
6641   DebugLoc dl = Op.getDebugLoc();
6642   LLVMContext *Context = DAG.getContext();
6643
6644   // Build some magic constants.
6645   std::vector<Constant*> CV0;
6646   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6647   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6648   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6649   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6650   Constant *C0 = ConstantVector::get(CV0);
6651   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6652
6653   std::vector<Constant*> CV1;
6654   CV1.push_back(
6655     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6656   CV1.push_back(
6657     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6658   Constant *C1 = ConstantVector::get(CV1);
6659   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6660
6661   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6662                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6663                                         Op.getOperand(0),
6664                                         DAG.getIntPtrConstant(1)));
6665   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6666                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6667                                         Op.getOperand(0),
6668                                         DAG.getIntPtrConstant(0)));
6669   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6670   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6671                               MachinePointerInfo::getConstantPool(),
6672                               false, false, 16);
6673   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6674   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6675   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6676                               MachinePointerInfo::getConstantPool(),
6677                               false, false, 16);
6678   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6679
6680   // Add the halves; easiest way is to swap them into another reg first.
6681   int ShufMask[2] = { 1, -1 };
6682   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6683                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6684   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6685   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6686                      DAG.getIntPtrConstant(0));
6687 }
6688
6689 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6690 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6691                                                SelectionDAG &DAG) const {
6692   DebugLoc dl = Op.getDebugLoc();
6693   // FP constant to bias correct the final result.
6694   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6695                                    MVT::f64);
6696
6697   // Load the 32-bit value into an XMM register.
6698   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6699                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6700                                          Op.getOperand(0),
6701                                          DAG.getIntPtrConstant(0)));
6702
6703   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6704                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6705                      DAG.getIntPtrConstant(0));
6706
6707   // Or the load with the bias.
6708   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6709                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6710                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6711                                                    MVT::v2f64, Load)),
6712                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6713                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6714                                                    MVT::v2f64, Bias)));
6715   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6716                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6717                    DAG.getIntPtrConstant(0));
6718
6719   // Subtract the bias.
6720   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6721
6722   // Handle final rounding.
6723   EVT DestVT = Op.getValueType();
6724
6725   if (DestVT.bitsLT(MVT::f64)) {
6726     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6727                        DAG.getIntPtrConstant(0));
6728   } else if (DestVT.bitsGT(MVT::f64)) {
6729     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6730   }
6731
6732   // Handle final rounding.
6733   return Sub;
6734 }
6735
6736 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6737                                            SelectionDAG &DAG) const {
6738   SDValue N0 = Op.getOperand(0);
6739   DebugLoc dl = Op.getDebugLoc();
6740
6741   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6742   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6743   // the optimization here.
6744   if (DAG.SignBitIsZero(N0))
6745     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6746
6747   EVT SrcVT = N0.getValueType();
6748   EVT DstVT = Op.getValueType();
6749   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6750     return LowerUINT_TO_FP_i64(Op, DAG);
6751   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6752     return LowerUINT_TO_FP_i32(Op, DAG);
6753
6754   // Make a 64-bit buffer, and use it to build an FILD.
6755   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6756   if (SrcVT == MVT::i32) {
6757     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6758     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6759                                      getPointerTy(), StackSlot, WordOff);
6760     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6761                                   StackSlot, MachinePointerInfo(),
6762                                   false, false, 0);
6763     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6764                                   OffsetSlot, MachinePointerInfo(),
6765                                   false, false, 0);
6766     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6767     return Fild;
6768   }
6769
6770   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6771   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6772                                 StackSlot, MachinePointerInfo(),
6773                                false, false, 0);
6774   // For i64 source, we need to add the appropriate power of 2 if the input
6775   // was negative.  This is the same as the optimization in
6776   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6777   // we must be careful to do the computation in x87 extended precision, not
6778   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6779   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6780   MachineMemOperand *MMO =
6781     DAG.getMachineFunction()
6782     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6783                           MachineMemOperand::MOLoad, 8, 8);
6784
6785   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6786   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6787   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6788                                          MVT::i64, MMO);
6789
6790   APInt FF(32, 0x5F800000ULL);
6791
6792   // Check whether the sign bit is set.
6793   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6794                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6795                                  ISD::SETLT);
6796
6797   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6798   SDValue FudgePtr = DAG.getConstantPool(
6799                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6800                                          getPointerTy());
6801
6802   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6803   SDValue Zero = DAG.getIntPtrConstant(0);
6804   SDValue Four = DAG.getIntPtrConstant(4);
6805   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6806                                Zero, Four);
6807   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6808
6809   // Load the value out, extending it from f32 to f80.
6810   // FIXME: Avoid the extend by constructing the right constant pool?
6811   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6812                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6813                                  MVT::f32, false, false, 4);
6814   // Extend everything to 80 bits to force it to be done on x87.
6815   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6816   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6817 }
6818
6819 std::pair<SDValue,SDValue> X86TargetLowering::
6820 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6821   DebugLoc DL = Op.getDebugLoc();
6822
6823   EVT DstTy = Op.getValueType();
6824
6825   if (!IsSigned) {
6826     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6827     DstTy = MVT::i64;
6828   }
6829
6830   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6831          DstTy.getSimpleVT() >= MVT::i16 &&
6832          "Unknown FP_TO_SINT to lower!");
6833
6834   // These are really Legal.
6835   if (DstTy == MVT::i32 &&
6836       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6837     return std::make_pair(SDValue(), SDValue());
6838   if (Subtarget->is64Bit() &&
6839       DstTy == MVT::i64 &&
6840       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6841     return std::make_pair(SDValue(), SDValue());
6842
6843   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6844   // stack slot.
6845   MachineFunction &MF = DAG.getMachineFunction();
6846   unsigned MemSize = DstTy.getSizeInBits()/8;
6847   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6848   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6849
6850
6851
6852   unsigned Opc;
6853   switch (DstTy.getSimpleVT().SimpleTy) {
6854   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6855   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6856   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6857   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6858   }
6859
6860   SDValue Chain = DAG.getEntryNode();
6861   SDValue Value = Op.getOperand(0);
6862   EVT TheVT = Op.getOperand(0).getValueType();
6863   if (isScalarFPTypeInSSEReg(TheVT)) {
6864     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6865     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6866                          MachinePointerInfo::getFixedStack(SSFI),
6867                          false, false, 0);
6868     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6869     SDValue Ops[] = {
6870       Chain, StackSlot, DAG.getValueType(TheVT)
6871     };
6872
6873     MachineMemOperand *MMO =
6874       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6875                               MachineMemOperand::MOLoad, MemSize, MemSize);
6876     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6877                                     DstTy, MMO);
6878     Chain = Value.getValue(1);
6879     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6880     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6881   }
6882
6883   MachineMemOperand *MMO =
6884     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6885                             MachineMemOperand::MOStore, MemSize, MemSize);
6886
6887   // Build the FP_TO_INT*_IN_MEM
6888   SDValue Ops[] = { Chain, Value, StackSlot };
6889   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6890                                          Ops, 3, DstTy, MMO);
6891
6892   return std::make_pair(FIST, StackSlot);
6893 }
6894
6895 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6896                                            SelectionDAG &DAG) const {
6897   if (Op.getValueType().isVector())
6898     return SDValue();
6899
6900   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6901   SDValue FIST = Vals.first, StackSlot = Vals.second;
6902   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6903   if (FIST.getNode() == 0) return Op;
6904
6905   // Load the result.
6906   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6907                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6908 }
6909
6910 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6911                                            SelectionDAG &DAG) const {
6912   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6913   SDValue FIST = Vals.first, StackSlot = Vals.second;
6914   assert(FIST.getNode() && "Unexpected failure");
6915
6916   // Load the result.
6917   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6918                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6919 }
6920
6921 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6922                                      SelectionDAG &DAG) const {
6923   LLVMContext *Context = DAG.getContext();
6924   DebugLoc dl = Op.getDebugLoc();
6925   EVT VT = Op.getValueType();
6926   EVT EltVT = VT;
6927   if (VT.isVector())
6928     EltVT = VT.getVectorElementType();
6929   std::vector<Constant*> CV;
6930   if (EltVT == MVT::f64) {
6931     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6932     CV.push_back(C);
6933     CV.push_back(C);
6934   } else {
6935     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6936     CV.push_back(C);
6937     CV.push_back(C);
6938     CV.push_back(C);
6939     CV.push_back(C);
6940   }
6941   Constant *C = ConstantVector::get(CV);
6942   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6943   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6944                              MachinePointerInfo::getConstantPool(),
6945                              false, false, 16);
6946   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6947 }
6948
6949 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6950   LLVMContext *Context = DAG.getContext();
6951   DebugLoc dl = Op.getDebugLoc();
6952   EVT VT = Op.getValueType();
6953   EVT EltVT = VT;
6954   if (VT.isVector())
6955     EltVT = VT.getVectorElementType();
6956   std::vector<Constant*> CV;
6957   if (EltVT == MVT::f64) {
6958     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6959     CV.push_back(C);
6960     CV.push_back(C);
6961   } else {
6962     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6963     CV.push_back(C);
6964     CV.push_back(C);
6965     CV.push_back(C);
6966     CV.push_back(C);
6967   }
6968   Constant *C = ConstantVector::get(CV);
6969   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6970   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6971                              MachinePointerInfo::getConstantPool(),
6972                              false, false, 16);
6973   if (VT.isVector()) {
6974     return DAG.getNode(ISD::BITCAST, dl, VT,
6975                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6976                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6977                                 Op.getOperand(0)),
6978                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6979   } else {
6980     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6981   }
6982 }
6983
6984 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6985   LLVMContext *Context = DAG.getContext();
6986   SDValue Op0 = Op.getOperand(0);
6987   SDValue Op1 = Op.getOperand(1);
6988   DebugLoc dl = Op.getDebugLoc();
6989   EVT VT = Op.getValueType();
6990   EVT SrcVT = Op1.getValueType();
6991
6992   // If second operand is smaller, extend it first.
6993   if (SrcVT.bitsLT(VT)) {
6994     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6995     SrcVT = VT;
6996   }
6997   // And if it is bigger, shrink it first.
6998   if (SrcVT.bitsGT(VT)) {
6999     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7000     SrcVT = VT;
7001   }
7002
7003   // At this point the operands and the result should have the same
7004   // type, and that won't be f80 since that is not custom lowered.
7005
7006   // First get the sign bit of second operand.
7007   std::vector<Constant*> CV;
7008   if (SrcVT == MVT::f64) {
7009     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7010     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7011   } else {
7012     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7013     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7014     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7015     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7016   }
7017   Constant *C = ConstantVector::get(CV);
7018   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7019   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7020                               MachinePointerInfo::getConstantPool(),
7021                               false, false, 16);
7022   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7023
7024   // Shift sign bit right or left if the two operands have different types.
7025   if (SrcVT.bitsGT(VT)) {
7026     // Op0 is MVT::f32, Op1 is MVT::f64.
7027     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7028     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7029                           DAG.getConstant(32, MVT::i32));
7030     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7031     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7032                           DAG.getIntPtrConstant(0));
7033   }
7034
7035   // Clear first operand sign bit.
7036   CV.clear();
7037   if (VT == MVT::f64) {
7038     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7039     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7040   } else {
7041     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7042     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7043     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7044     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7045   }
7046   C = ConstantVector::get(CV);
7047   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7048   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7049                               MachinePointerInfo::getConstantPool(),
7050                               false, false, 16);
7051   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7052
7053   // Or the value with the sign bit.
7054   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7055 }
7056
7057 /// Emit nodes that will be selected as "test Op0,Op0", or something
7058 /// equivalent.
7059 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7060                                     SelectionDAG &DAG) const {
7061   DebugLoc dl = Op.getDebugLoc();
7062
7063   // CF and OF aren't always set the way we want. Determine which
7064   // of these we need.
7065   bool NeedCF = false;
7066   bool NeedOF = false;
7067   switch (X86CC) {
7068   default: break;
7069   case X86::COND_A: case X86::COND_AE:
7070   case X86::COND_B: case X86::COND_BE:
7071     NeedCF = true;
7072     break;
7073   case X86::COND_G: case X86::COND_GE:
7074   case X86::COND_L: case X86::COND_LE:
7075   case X86::COND_O: case X86::COND_NO:
7076     NeedOF = true;
7077     break;
7078   }
7079
7080   // See if we can use the EFLAGS value from the operand instead of
7081   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7082   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7083   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7084     // Emit a CMP with 0, which is the TEST pattern.
7085     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7086                        DAG.getConstant(0, Op.getValueType()));
7087
7088   unsigned Opcode = 0;
7089   unsigned NumOperands = 0;
7090   switch (Op.getNode()->getOpcode()) {
7091   case ISD::ADD:
7092     // Due to an isel shortcoming, be conservative if this add is likely to be
7093     // selected as part of a load-modify-store instruction. When the root node
7094     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7095     // uses of other nodes in the match, such as the ADD in this case. This
7096     // leads to the ADD being left around and reselected, with the result being
7097     // two adds in the output.  Alas, even if none our users are stores, that
7098     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7099     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7100     // climbing the DAG back to the root, and it doesn't seem to be worth the
7101     // effort.
7102     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7103            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7104       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7105         goto default_case;
7106
7107     if (ConstantSDNode *C =
7108         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7109       // An add of one will be selected as an INC.
7110       if (C->getAPIntValue() == 1) {
7111         Opcode = X86ISD::INC;
7112         NumOperands = 1;
7113         break;
7114       }
7115
7116       // An add of negative one (subtract of one) will be selected as a DEC.
7117       if (C->getAPIntValue().isAllOnesValue()) {
7118         Opcode = X86ISD::DEC;
7119         NumOperands = 1;
7120         break;
7121       }
7122     }
7123
7124     // Otherwise use a regular EFLAGS-setting add.
7125     Opcode = X86ISD::ADD;
7126     NumOperands = 2;
7127     break;
7128   case ISD::AND: {
7129     // If the primary and result isn't used, don't bother using X86ISD::AND,
7130     // because a TEST instruction will be better.
7131     bool NonFlagUse = false;
7132     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7133            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7134       SDNode *User = *UI;
7135       unsigned UOpNo = UI.getOperandNo();
7136       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7137         // Look pass truncate.
7138         UOpNo = User->use_begin().getOperandNo();
7139         User = *User->use_begin();
7140       }
7141
7142       if (User->getOpcode() != ISD::BRCOND &&
7143           User->getOpcode() != ISD::SETCC &&
7144           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7145         NonFlagUse = true;
7146         break;
7147       }
7148     }
7149
7150     if (!NonFlagUse)
7151       break;
7152   }
7153     // FALL THROUGH
7154   case ISD::SUB:
7155   case ISD::OR:
7156   case ISD::XOR:
7157     // Due to the ISEL shortcoming noted above, be conservative if this op is
7158     // likely to be selected as part of a load-modify-store instruction.
7159     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7160            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7161       if (UI->getOpcode() == ISD::STORE)
7162         goto default_case;
7163
7164     // Otherwise use a regular EFLAGS-setting instruction.
7165     switch (Op.getNode()->getOpcode()) {
7166     default: llvm_unreachable("unexpected operator!");
7167     case ISD::SUB: Opcode = X86ISD::SUB; break;
7168     case ISD::OR:  Opcode = X86ISD::OR;  break;
7169     case ISD::XOR: Opcode = X86ISD::XOR; break;
7170     case ISD::AND: Opcode = X86ISD::AND; break;
7171     }
7172
7173     NumOperands = 2;
7174     break;
7175   case X86ISD::ADD:
7176   case X86ISD::SUB:
7177   case X86ISD::INC:
7178   case X86ISD::DEC:
7179   case X86ISD::OR:
7180   case X86ISD::XOR:
7181   case X86ISD::AND:
7182     return SDValue(Op.getNode(), 1);
7183   default:
7184   default_case:
7185     break;
7186   }
7187
7188   if (Opcode == 0)
7189     // Emit a CMP with 0, which is the TEST pattern.
7190     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7191                        DAG.getConstant(0, Op.getValueType()));
7192
7193   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7194   SmallVector<SDValue, 4> Ops;
7195   for (unsigned i = 0; i != NumOperands; ++i)
7196     Ops.push_back(Op.getOperand(i));
7197
7198   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7199   DAG.ReplaceAllUsesWith(Op, New);
7200   return SDValue(New.getNode(), 1);
7201 }
7202
7203 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7204 /// equivalent.
7205 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7206                                    SelectionDAG &DAG) const {
7207   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7208     if (C->getAPIntValue() == 0)
7209       return EmitTest(Op0, X86CC, DAG);
7210
7211   DebugLoc dl = Op0.getDebugLoc();
7212   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7213 }
7214
7215 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7216 /// if it's possible.
7217 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7218                                      DebugLoc dl, SelectionDAG &DAG) const {
7219   SDValue Op0 = And.getOperand(0);
7220   SDValue Op1 = And.getOperand(1);
7221   if (Op0.getOpcode() == ISD::TRUNCATE)
7222     Op0 = Op0.getOperand(0);
7223   if (Op1.getOpcode() == ISD::TRUNCATE)
7224     Op1 = Op1.getOperand(0);
7225
7226   SDValue LHS, RHS;
7227   if (Op1.getOpcode() == ISD::SHL)
7228     std::swap(Op0, Op1);
7229   if (Op0.getOpcode() == ISD::SHL) {
7230     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7231       if (And00C->getZExtValue() == 1) {
7232         // If we looked past a truncate, check that it's only truncating away
7233         // known zeros.
7234         unsigned BitWidth = Op0.getValueSizeInBits();
7235         unsigned AndBitWidth = And.getValueSizeInBits();
7236         if (BitWidth > AndBitWidth) {
7237           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7238           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7239           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7240             return SDValue();
7241         }
7242         LHS = Op1;
7243         RHS = Op0.getOperand(1);
7244       }
7245   } else if (Op1.getOpcode() == ISD::Constant) {
7246     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7247     SDValue AndLHS = Op0;
7248     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7249       LHS = AndLHS.getOperand(0);
7250       RHS = AndLHS.getOperand(1);
7251     }
7252   }
7253
7254   if (LHS.getNode()) {
7255     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7256     // instruction.  Since the shift amount is in-range-or-undefined, we know
7257     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7258     // the encoding for the i16 version is larger than the i32 version.
7259     // Also promote i16 to i32 for performance / code size reason.
7260     if (LHS.getValueType() == MVT::i8 ||
7261         LHS.getValueType() == MVT::i16)
7262       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7263
7264     // If the operand types disagree, extend the shift amount to match.  Since
7265     // BT ignores high bits (like shifts) we can use anyextend.
7266     if (LHS.getValueType() != RHS.getValueType())
7267       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7268
7269     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7270     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7271     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7272                        DAG.getConstant(Cond, MVT::i8), BT);
7273   }
7274
7275   return SDValue();
7276 }
7277
7278 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7279   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7280   SDValue Op0 = Op.getOperand(0);
7281   SDValue Op1 = Op.getOperand(1);
7282   DebugLoc dl = Op.getDebugLoc();
7283   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7284
7285   // Optimize to BT if possible.
7286   // Lower (X & (1 << N)) == 0 to BT(X, N).
7287   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7288   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7289   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7290       Op1.getOpcode() == ISD::Constant &&
7291       cast<ConstantSDNode>(Op1)->isNullValue() &&
7292       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7293     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7294     if (NewSetCC.getNode())
7295       return NewSetCC;
7296   }
7297
7298   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7299   // these.
7300   if (Op1.getOpcode() == ISD::Constant &&
7301       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7302        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7303       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7304
7305     // If the input is a setcc, then reuse the input setcc or use a new one with
7306     // the inverted condition.
7307     if (Op0.getOpcode() == X86ISD::SETCC) {
7308       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7309       bool Invert = (CC == ISD::SETNE) ^
7310         cast<ConstantSDNode>(Op1)->isNullValue();
7311       if (!Invert) return Op0;
7312
7313       CCode = X86::GetOppositeBranchCondition(CCode);
7314       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7315                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7316     }
7317   }
7318
7319   bool isFP = Op1.getValueType().isFloatingPoint();
7320   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7321   if (X86CC == X86::COND_INVALID)
7322     return SDValue();
7323
7324   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7325   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7326                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7327 }
7328
7329 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7330   SDValue Cond;
7331   SDValue Op0 = Op.getOperand(0);
7332   SDValue Op1 = Op.getOperand(1);
7333   SDValue CC = Op.getOperand(2);
7334   EVT VT = Op.getValueType();
7335   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7336   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7337   DebugLoc dl = Op.getDebugLoc();
7338
7339   if (isFP) {
7340     unsigned SSECC = 8;
7341     EVT VT0 = Op0.getValueType();
7342     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7343     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7344     bool Swap = false;
7345
7346     switch (SetCCOpcode) {
7347     default: break;
7348     case ISD::SETOEQ:
7349     case ISD::SETEQ:  SSECC = 0; break;
7350     case ISD::SETOGT:
7351     case ISD::SETGT: Swap = true; // Fallthrough
7352     case ISD::SETLT:
7353     case ISD::SETOLT: SSECC = 1; break;
7354     case ISD::SETOGE:
7355     case ISD::SETGE: Swap = true; // Fallthrough
7356     case ISD::SETLE:
7357     case ISD::SETOLE: SSECC = 2; break;
7358     case ISD::SETUO:  SSECC = 3; break;
7359     case ISD::SETUNE:
7360     case ISD::SETNE:  SSECC = 4; break;
7361     case ISD::SETULE: Swap = true;
7362     case ISD::SETUGE: SSECC = 5; break;
7363     case ISD::SETULT: Swap = true;
7364     case ISD::SETUGT: SSECC = 6; break;
7365     case ISD::SETO:   SSECC = 7; break;
7366     }
7367     if (Swap)
7368       std::swap(Op0, Op1);
7369
7370     // In the two special cases we can't handle, emit two comparisons.
7371     if (SSECC == 8) {
7372       if (SetCCOpcode == ISD::SETUEQ) {
7373         SDValue UNORD, EQ;
7374         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7375         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7376         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7377       }
7378       else if (SetCCOpcode == ISD::SETONE) {
7379         SDValue ORD, NEQ;
7380         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7381         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7382         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7383       }
7384       llvm_unreachable("Illegal FP comparison");
7385     }
7386     // Handle all other FP comparisons here.
7387     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7388   }
7389
7390   // We are handling one of the integer comparisons here.  Since SSE only has
7391   // GT and EQ comparisons for integer, swapping operands and multiple
7392   // operations may be required for some comparisons.
7393   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7394   bool Swap = false, Invert = false, FlipSigns = false;
7395
7396   switch (VT.getSimpleVT().SimpleTy) {
7397   default: break;
7398   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7399   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7400   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7401   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7402   }
7403
7404   switch (SetCCOpcode) {
7405   default: break;
7406   case ISD::SETNE:  Invert = true;
7407   case ISD::SETEQ:  Opc = EQOpc; break;
7408   case ISD::SETLT:  Swap = true;
7409   case ISD::SETGT:  Opc = GTOpc; break;
7410   case ISD::SETGE:  Swap = true;
7411   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7412   case ISD::SETULT: Swap = true;
7413   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7414   case ISD::SETUGE: Swap = true;
7415   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7416   }
7417   if (Swap)
7418     std::swap(Op0, Op1);
7419
7420   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7421   // bits of the inputs before performing those operations.
7422   if (FlipSigns) {
7423     EVT EltVT = VT.getVectorElementType();
7424     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7425                                       EltVT);
7426     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7427     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7428                                     SignBits.size());
7429     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7430     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7431   }
7432
7433   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7434
7435   // If the logical-not of the result is required, perform that now.
7436   if (Invert)
7437     Result = DAG.getNOT(dl, Result, VT);
7438
7439   return Result;
7440 }
7441
7442 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7443 static bool isX86LogicalCmp(SDValue Op) {
7444   unsigned Opc = Op.getNode()->getOpcode();
7445   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7446     return true;
7447   if (Op.getResNo() == 1 &&
7448       (Opc == X86ISD::ADD ||
7449        Opc == X86ISD::SUB ||
7450        Opc == X86ISD::ADC ||
7451        Opc == X86ISD::SBB ||
7452        Opc == X86ISD::SMUL ||
7453        Opc == X86ISD::UMUL ||
7454        Opc == X86ISD::INC ||
7455        Opc == X86ISD::DEC ||
7456        Opc == X86ISD::OR ||
7457        Opc == X86ISD::XOR ||
7458        Opc == X86ISD::AND))
7459     return true;
7460
7461   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7462     return true;
7463
7464   return false;
7465 }
7466
7467 static bool isZero(SDValue V) {
7468   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7469   return C && C->isNullValue();
7470 }
7471
7472 static bool isAllOnes(SDValue V) {
7473   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7474   return C && C->isAllOnesValue();
7475 }
7476
7477 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7478   bool addTest = true;
7479   SDValue Cond  = Op.getOperand(0);
7480   SDValue Op1 = Op.getOperand(1);
7481   SDValue Op2 = Op.getOperand(2);
7482   DebugLoc DL = Op.getDebugLoc();
7483   SDValue CC;
7484
7485   if (Cond.getOpcode() == ISD::SETCC) {
7486     SDValue NewCond = LowerSETCC(Cond, DAG);
7487     if (NewCond.getNode())
7488       Cond = NewCond;
7489   }
7490
7491   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7492   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7493   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7494   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7495   if (Cond.getOpcode() == X86ISD::SETCC &&
7496       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7497       isZero(Cond.getOperand(1).getOperand(1))) {
7498     SDValue Cmp = Cond.getOperand(1);
7499
7500     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7501
7502     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7503         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7504       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7505
7506       SDValue CmpOp0 = Cmp.getOperand(0);
7507       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7508                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7509
7510       SDValue Res =   // Res = 0 or -1.
7511         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7512                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7513
7514       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7515         Res = DAG.getNOT(DL, Res, Res.getValueType());
7516
7517       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7518       if (N2C == 0 || !N2C->isNullValue())
7519         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7520       return Res;
7521     }
7522   }
7523
7524   // Look past (and (setcc_carry (cmp ...)), 1).
7525   if (Cond.getOpcode() == ISD::AND &&
7526       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7527     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7528     if (C && C->getAPIntValue() == 1)
7529       Cond = Cond.getOperand(0);
7530   }
7531
7532   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7533   // setting operand in place of the X86ISD::SETCC.
7534   if (Cond.getOpcode() == X86ISD::SETCC ||
7535       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7536     CC = Cond.getOperand(0);
7537
7538     SDValue Cmp = Cond.getOperand(1);
7539     unsigned Opc = Cmp.getOpcode();
7540     EVT VT = Op.getValueType();
7541
7542     bool IllegalFPCMov = false;
7543     if (VT.isFloatingPoint() && !VT.isVector() &&
7544         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7545       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7546
7547     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7548         Opc == X86ISD::BT) { // FIXME
7549       Cond = Cmp;
7550       addTest = false;
7551     }
7552   }
7553
7554   if (addTest) {
7555     // Look pass the truncate.
7556     if (Cond.getOpcode() == ISD::TRUNCATE)
7557       Cond = Cond.getOperand(0);
7558
7559     // We know the result of AND is compared against zero. Try to match
7560     // it to BT.
7561     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7562       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7563       if (NewSetCC.getNode()) {
7564         CC = NewSetCC.getOperand(0);
7565         Cond = NewSetCC.getOperand(1);
7566         addTest = false;
7567       }
7568     }
7569   }
7570
7571   if (addTest) {
7572     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7573     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7574   }
7575
7576   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7577   // a <  b ?  0 : -1 -> RES = setcc_carry
7578   // a >= b ? -1 :  0 -> RES = setcc_carry
7579   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7580   if (Cond.getOpcode() == X86ISD::CMP) {
7581     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7582
7583     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7584         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7585       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7586                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7587       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7588         return DAG.getNOT(DL, Res, Res.getValueType());
7589       return Res;
7590     }
7591   }
7592
7593   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7594   // condition is true.
7595   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7596   SDValue Ops[] = { Op2, Op1, CC, Cond };
7597   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7598 }
7599
7600 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7601 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7602 // from the AND / OR.
7603 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7604   Opc = Op.getOpcode();
7605   if (Opc != ISD::OR && Opc != ISD::AND)
7606     return false;
7607   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7608           Op.getOperand(0).hasOneUse() &&
7609           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7610           Op.getOperand(1).hasOneUse());
7611 }
7612
7613 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7614 // 1 and that the SETCC node has a single use.
7615 static bool isXor1OfSetCC(SDValue Op) {
7616   if (Op.getOpcode() != ISD::XOR)
7617     return false;
7618   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7619   if (N1C && N1C->getAPIntValue() == 1) {
7620     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7621       Op.getOperand(0).hasOneUse();
7622   }
7623   return false;
7624 }
7625
7626 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7627   bool addTest = true;
7628   SDValue Chain = Op.getOperand(0);
7629   SDValue Cond  = Op.getOperand(1);
7630   SDValue Dest  = Op.getOperand(2);
7631   DebugLoc dl = Op.getDebugLoc();
7632   SDValue CC;
7633
7634   if (Cond.getOpcode() == ISD::SETCC) {
7635     SDValue NewCond = LowerSETCC(Cond, DAG);
7636     if (NewCond.getNode())
7637       Cond = NewCond;
7638   }
7639 #if 0
7640   // FIXME: LowerXALUO doesn't handle these!!
7641   else if (Cond.getOpcode() == X86ISD::ADD  ||
7642            Cond.getOpcode() == X86ISD::SUB  ||
7643            Cond.getOpcode() == X86ISD::SMUL ||
7644            Cond.getOpcode() == X86ISD::UMUL)
7645     Cond = LowerXALUO(Cond, DAG);
7646 #endif
7647
7648   // Look pass (and (setcc_carry (cmp ...)), 1).
7649   if (Cond.getOpcode() == ISD::AND &&
7650       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7651     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7652     if (C && C->getAPIntValue() == 1)
7653       Cond = Cond.getOperand(0);
7654   }
7655
7656   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7657   // setting operand in place of the X86ISD::SETCC.
7658   if (Cond.getOpcode() == X86ISD::SETCC ||
7659       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7660     CC = Cond.getOperand(0);
7661
7662     SDValue Cmp = Cond.getOperand(1);
7663     unsigned Opc = Cmp.getOpcode();
7664     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7665     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7666       Cond = Cmp;
7667       addTest = false;
7668     } else {
7669       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7670       default: break;
7671       case X86::COND_O:
7672       case X86::COND_B:
7673         // These can only come from an arithmetic instruction with overflow,
7674         // e.g. SADDO, UADDO.
7675         Cond = Cond.getNode()->getOperand(1);
7676         addTest = false;
7677         break;
7678       }
7679     }
7680   } else {
7681     unsigned CondOpc;
7682     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7683       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7684       if (CondOpc == ISD::OR) {
7685         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7686         // two branches instead of an explicit OR instruction with a
7687         // separate test.
7688         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7689             isX86LogicalCmp(Cmp)) {
7690           CC = Cond.getOperand(0).getOperand(0);
7691           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7692                               Chain, Dest, CC, Cmp);
7693           CC = Cond.getOperand(1).getOperand(0);
7694           Cond = Cmp;
7695           addTest = false;
7696         }
7697       } else { // ISD::AND
7698         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7699         // two branches instead of an explicit AND instruction with a
7700         // separate test. However, we only do this if this block doesn't
7701         // have a fall-through edge, because this requires an explicit
7702         // jmp when the condition is false.
7703         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7704             isX86LogicalCmp(Cmp) &&
7705             Op.getNode()->hasOneUse()) {
7706           X86::CondCode CCode =
7707             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7708           CCode = X86::GetOppositeBranchCondition(CCode);
7709           CC = DAG.getConstant(CCode, MVT::i8);
7710           SDNode *User = *Op.getNode()->use_begin();
7711           // Look for an unconditional branch following this conditional branch.
7712           // We need this because we need to reverse the successors in order
7713           // to implement FCMP_OEQ.
7714           if (User->getOpcode() == ISD::BR) {
7715             SDValue FalseBB = User->getOperand(1);
7716             SDNode *NewBR =
7717               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7718             assert(NewBR == User);
7719             (void)NewBR;
7720             Dest = FalseBB;
7721
7722             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7723                                 Chain, Dest, CC, Cmp);
7724             X86::CondCode CCode =
7725               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7726             CCode = X86::GetOppositeBranchCondition(CCode);
7727             CC = DAG.getConstant(CCode, MVT::i8);
7728             Cond = Cmp;
7729             addTest = false;
7730           }
7731         }
7732       }
7733     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7734       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7735       // It should be transformed during dag combiner except when the condition
7736       // is set by a arithmetics with overflow node.
7737       X86::CondCode CCode =
7738         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7739       CCode = X86::GetOppositeBranchCondition(CCode);
7740       CC = DAG.getConstant(CCode, MVT::i8);
7741       Cond = Cond.getOperand(0).getOperand(1);
7742       addTest = false;
7743     }
7744   }
7745
7746   if (addTest) {
7747     // Look pass the truncate.
7748     if (Cond.getOpcode() == ISD::TRUNCATE)
7749       Cond = Cond.getOperand(0);
7750
7751     // We know the result of AND is compared against zero. Try to match
7752     // it to BT.
7753     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7754       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7755       if (NewSetCC.getNode()) {
7756         CC = NewSetCC.getOperand(0);
7757         Cond = NewSetCC.getOperand(1);
7758         addTest = false;
7759       }
7760     }
7761   }
7762
7763   if (addTest) {
7764     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7765     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7766   }
7767   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7768                      Chain, Dest, CC, Cond);
7769 }
7770
7771
7772 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7773 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7774 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7775 // that the guard pages used by the OS virtual memory manager are allocated in
7776 // correct sequence.
7777 SDValue
7778 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7779                                            SelectionDAG &DAG) const {
7780   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7781          "This should be used only on Windows targets");
7782   DebugLoc dl = Op.getDebugLoc();
7783
7784   // Get the inputs.
7785   SDValue Chain = Op.getOperand(0);
7786   SDValue Size  = Op.getOperand(1);
7787   // FIXME: Ensure alignment here
7788
7789   SDValue Flag;
7790
7791   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7792
7793   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7794   Flag = Chain.getValue(1);
7795
7796   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7797
7798   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7799   Flag = Chain.getValue(1);
7800
7801   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7802
7803   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7804   return DAG.getMergeValues(Ops1, 2, dl);
7805 }
7806
7807 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7808   MachineFunction &MF = DAG.getMachineFunction();
7809   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7810
7811   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7812   DebugLoc DL = Op.getDebugLoc();
7813
7814   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7815     // vastart just stores the address of the VarArgsFrameIndex slot into the
7816     // memory location argument.
7817     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7818                                    getPointerTy());
7819     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7820                         MachinePointerInfo(SV), false, false, 0);
7821   }
7822
7823   // __va_list_tag:
7824   //   gp_offset         (0 - 6 * 8)
7825   //   fp_offset         (48 - 48 + 8 * 16)
7826   //   overflow_arg_area (point to parameters coming in memory).
7827   //   reg_save_area
7828   SmallVector<SDValue, 8> MemOps;
7829   SDValue FIN = Op.getOperand(1);
7830   // Store gp_offset
7831   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7832                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7833                                                MVT::i32),
7834                                FIN, MachinePointerInfo(SV), false, false, 0);
7835   MemOps.push_back(Store);
7836
7837   // Store fp_offset
7838   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7839                     FIN, DAG.getIntPtrConstant(4));
7840   Store = DAG.getStore(Op.getOperand(0), DL,
7841                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7842                                        MVT::i32),
7843                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7844   MemOps.push_back(Store);
7845
7846   // Store ptr to overflow_arg_area
7847   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7848                     FIN, DAG.getIntPtrConstant(4));
7849   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7850                                     getPointerTy());
7851   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7852                        MachinePointerInfo(SV, 8),
7853                        false, false, 0);
7854   MemOps.push_back(Store);
7855
7856   // Store ptr to reg_save_area.
7857   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7858                     FIN, DAG.getIntPtrConstant(8));
7859   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7860                                     getPointerTy());
7861   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7862                        MachinePointerInfo(SV, 16), false, false, 0);
7863   MemOps.push_back(Store);
7864   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7865                      &MemOps[0], MemOps.size());
7866 }
7867
7868 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7869   assert(Subtarget->is64Bit() &&
7870          "LowerVAARG only handles 64-bit va_arg!");
7871   assert((Subtarget->isTargetLinux() ||
7872           Subtarget->isTargetDarwin()) &&
7873           "Unhandled target in LowerVAARG");
7874   assert(Op.getNode()->getNumOperands() == 4);
7875   SDValue Chain = Op.getOperand(0);
7876   SDValue SrcPtr = Op.getOperand(1);
7877   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7878   unsigned Align = Op.getConstantOperandVal(3);
7879   DebugLoc dl = Op.getDebugLoc();
7880
7881   EVT ArgVT = Op.getNode()->getValueType(0);
7882   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7883   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7884   uint8_t ArgMode;
7885
7886   // Decide which area this value should be read from.
7887   // TODO: Implement the AMD64 ABI in its entirety. This simple
7888   // selection mechanism works only for the basic types.
7889   if (ArgVT == MVT::f80) {
7890     llvm_unreachable("va_arg for f80 not yet implemented");
7891   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7892     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7893   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7894     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7895   } else {
7896     llvm_unreachable("Unhandled argument type in LowerVAARG");
7897   }
7898
7899   if (ArgMode == 2) {
7900     // Sanity Check: Make sure using fp_offset makes sense.
7901     assert(!UseSoftFloat &&
7902            !(DAG.getMachineFunction()
7903                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7904            Subtarget->hasXMM());
7905   }
7906
7907   // Insert VAARG_64 node into the DAG
7908   // VAARG_64 returns two values: Variable Argument Address, Chain
7909   SmallVector<SDValue, 11> InstOps;
7910   InstOps.push_back(Chain);
7911   InstOps.push_back(SrcPtr);
7912   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7913   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7914   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7915   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7916   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7917                                           VTs, &InstOps[0], InstOps.size(),
7918                                           MVT::i64,
7919                                           MachinePointerInfo(SV),
7920                                           /*Align=*/0,
7921                                           /*Volatile=*/false,
7922                                           /*ReadMem=*/true,
7923                                           /*WriteMem=*/true);
7924   Chain = VAARG.getValue(1);
7925
7926   // Load the next argument and return it
7927   return DAG.getLoad(ArgVT, dl,
7928                      Chain,
7929                      VAARG,
7930                      MachinePointerInfo(),
7931                      false, false, 0);
7932 }
7933
7934 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7935   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7936   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7937   SDValue Chain = Op.getOperand(0);
7938   SDValue DstPtr = Op.getOperand(1);
7939   SDValue SrcPtr = Op.getOperand(2);
7940   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7941   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7942   DebugLoc DL = Op.getDebugLoc();
7943
7944   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7945                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7946                        false,
7947                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7948 }
7949
7950 SDValue
7951 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7952   DebugLoc dl = Op.getDebugLoc();
7953   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7954   switch (IntNo) {
7955   default: return SDValue();    // Don't custom lower most intrinsics.
7956   // Comparison intrinsics.
7957   case Intrinsic::x86_sse_comieq_ss:
7958   case Intrinsic::x86_sse_comilt_ss:
7959   case Intrinsic::x86_sse_comile_ss:
7960   case Intrinsic::x86_sse_comigt_ss:
7961   case Intrinsic::x86_sse_comige_ss:
7962   case Intrinsic::x86_sse_comineq_ss:
7963   case Intrinsic::x86_sse_ucomieq_ss:
7964   case Intrinsic::x86_sse_ucomilt_ss:
7965   case Intrinsic::x86_sse_ucomile_ss:
7966   case Intrinsic::x86_sse_ucomigt_ss:
7967   case Intrinsic::x86_sse_ucomige_ss:
7968   case Intrinsic::x86_sse_ucomineq_ss:
7969   case Intrinsic::x86_sse2_comieq_sd:
7970   case Intrinsic::x86_sse2_comilt_sd:
7971   case Intrinsic::x86_sse2_comile_sd:
7972   case Intrinsic::x86_sse2_comigt_sd:
7973   case Intrinsic::x86_sse2_comige_sd:
7974   case Intrinsic::x86_sse2_comineq_sd:
7975   case Intrinsic::x86_sse2_ucomieq_sd:
7976   case Intrinsic::x86_sse2_ucomilt_sd:
7977   case Intrinsic::x86_sse2_ucomile_sd:
7978   case Intrinsic::x86_sse2_ucomigt_sd:
7979   case Intrinsic::x86_sse2_ucomige_sd:
7980   case Intrinsic::x86_sse2_ucomineq_sd: {
7981     unsigned Opc = 0;
7982     ISD::CondCode CC = ISD::SETCC_INVALID;
7983     switch (IntNo) {
7984     default: break;
7985     case Intrinsic::x86_sse_comieq_ss:
7986     case Intrinsic::x86_sse2_comieq_sd:
7987       Opc = X86ISD::COMI;
7988       CC = ISD::SETEQ;
7989       break;
7990     case Intrinsic::x86_sse_comilt_ss:
7991     case Intrinsic::x86_sse2_comilt_sd:
7992       Opc = X86ISD::COMI;
7993       CC = ISD::SETLT;
7994       break;
7995     case Intrinsic::x86_sse_comile_ss:
7996     case Intrinsic::x86_sse2_comile_sd:
7997       Opc = X86ISD::COMI;
7998       CC = ISD::SETLE;
7999       break;
8000     case Intrinsic::x86_sse_comigt_ss:
8001     case Intrinsic::x86_sse2_comigt_sd:
8002       Opc = X86ISD::COMI;
8003       CC = ISD::SETGT;
8004       break;
8005     case Intrinsic::x86_sse_comige_ss:
8006     case Intrinsic::x86_sse2_comige_sd:
8007       Opc = X86ISD::COMI;
8008       CC = ISD::SETGE;
8009       break;
8010     case Intrinsic::x86_sse_comineq_ss:
8011     case Intrinsic::x86_sse2_comineq_sd:
8012       Opc = X86ISD::COMI;
8013       CC = ISD::SETNE;
8014       break;
8015     case Intrinsic::x86_sse_ucomieq_ss:
8016     case Intrinsic::x86_sse2_ucomieq_sd:
8017       Opc = X86ISD::UCOMI;
8018       CC = ISD::SETEQ;
8019       break;
8020     case Intrinsic::x86_sse_ucomilt_ss:
8021     case Intrinsic::x86_sse2_ucomilt_sd:
8022       Opc = X86ISD::UCOMI;
8023       CC = ISD::SETLT;
8024       break;
8025     case Intrinsic::x86_sse_ucomile_ss:
8026     case Intrinsic::x86_sse2_ucomile_sd:
8027       Opc = X86ISD::UCOMI;
8028       CC = ISD::SETLE;
8029       break;
8030     case Intrinsic::x86_sse_ucomigt_ss:
8031     case Intrinsic::x86_sse2_ucomigt_sd:
8032       Opc = X86ISD::UCOMI;
8033       CC = ISD::SETGT;
8034       break;
8035     case Intrinsic::x86_sse_ucomige_ss:
8036     case Intrinsic::x86_sse2_ucomige_sd:
8037       Opc = X86ISD::UCOMI;
8038       CC = ISD::SETGE;
8039       break;
8040     case Intrinsic::x86_sse_ucomineq_ss:
8041     case Intrinsic::x86_sse2_ucomineq_sd:
8042       Opc = X86ISD::UCOMI;
8043       CC = ISD::SETNE;
8044       break;
8045     }
8046
8047     SDValue LHS = Op.getOperand(1);
8048     SDValue RHS = Op.getOperand(2);
8049     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8050     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8051     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8052     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8053                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8054     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8055   }
8056   // ptest and testp intrinsics. The intrinsic these come from are designed to
8057   // return an integer value, not just an instruction so lower it to the ptest
8058   // or testp pattern and a setcc for the result.
8059   case Intrinsic::x86_sse41_ptestz:
8060   case Intrinsic::x86_sse41_ptestc:
8061   case Intrinsic::x86_sse41_ptestnzc:
8062   case Intrinsic::x86_avx_ptestz_256:
8063   case Intrinsic::x86_avx_ptestc_256:
8064   case Intrinsic::x86_avx_ptestnzc_256:
8065   case Intrinsic::x86_avx_vtestz_ps:
8066   case Intrinsic::x86_avx_vtestc_ps:
8067   case Intrinsic::x86_avx_vtestnzc_ps:
8068   case Intrinsic::x86_avx_vtestz_pd:
8069   case Intrinsic::x86_avx_vtestc_pd:
8070   case Intrinsic::x86_avx_vtestnzc_pd:
8071   case Intrinsic::x86_avx_vtestz_ps_256:
8072   case Intrinsic::x86_avx_vtestc_ps_256:
8073   case Intrinsic::x86_avx_vtestnzc_ps_256:
8074   case Intrinsic::x86_avx_vtestz_pd_256:
8075   case Intrinsic::x86_avx_vtestc_pd_256:
8076   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8077     bool IsTestPacked = false;
8078     unsigned X86CC = 0;
8079     switch (IntNo) {
8080     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8081     case Intrinsic::x86_avx_vtestz_ps:
8082     case Intrinsic::x86_avx_vtestz_pd:
8083     case Intrinsic::x86_avx_vtestz_ps_256:
8084     case Intrinsic::x86_avx_vtestz_pd_256:
8085       IsTestPacked = true; // Fallthrough
8086     case Intrinsic::x86_sse41_ptestz:
8087     case Intrinsic::x86_avx_ptestz_256:
8088       // ZF = 1
8089       X86CC = X86::COND_E;
8090       break;
8091     case Intrinsic::x86_avx_vtestc_ps:
8092     case Intrinsic::x86_avx_vtestc_pd:
8093     case Intrinsic::x86_avx_vtestc_ps_256:
8094     case Intrinsic::x86_avx_vtestc_pd_256:
8095       IsTestPacked = true; // Fallthrough
8096     case Intrinsic::x86_sse41_ptestc:
8097     case Intrinsic::x86_avx_ptestc_256:
8098       // CF = 1
8099       X86CC = X86::COND_B;
8100       break;
8101     case Intrinsic::x86_avx_vtestnzc_ps:
8102     case Intrinsic::x86_avx_vtestnzc_pd:
8103     case Intrinsic::x86_avx_vtestnzc_ps_256:
8104     case Intrinsic::x86_avx_vtestnzc_pd_256:
8105       IsTestPacked = true; // Fallthrough
8106     case Intrinsic::x86_sse41_ptestnzc:
8107     case Intrinsic::x86_avx_ptestnzc_256:
8108       // ZF and CF = 0
8109       X86CC = X86::COND_A;
8110       break;
8111     }
8112
8113     SDValue LHS = Op.getOperand(1);
8114     SDValue RHS = Op.getOperand(2);
8115     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8116     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8117     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8118     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8119     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8120   }
8121
8122   // Fix vector shift instructions where the last operand is a non-immediate
8123   // i32 value.
8124   case Intrinsic::x86_sse2_pslli_w:
8125   case Intrinsic::x86_sse2_pslli_d:
8126   case Intrinsic::x86_sse2_pslli_q:
8127   case Intrinsic::x86_sse2_psrli_w:
8128   case Intrinsic::x86_sse2_psrli_d:
8129   case Intrinsic::x86_sse2_psrli_q:
8130   case Intrinsic::x86_sse2_psrai_w:
8131   case Intrinsic::x86_sse2_psrai_d:
8132   case Intrinsic::x86_mmx_pslli_w:
8133   case Intrinsic::x86_mmx_pslli_d:
8134   case Intrinsic::x86_mmx_pslli_q:
8135   case Intrinsic::x86_mmx_psrli_w:
8136   case Intrinsic::x86_mmx_psrli_d:
8137   case Intrinsic::x86_mmx_psrli_q:
8138   case Intrinsic::x86_mmx_psrai_w:
8139   case Intrinsic::x86_mmx_psrai_d: {
8140     SDValue ShAmt = Op.getOperand(2);
8141     if (isa<ConstantSDNode>(ShAmt))
8142       return SDValue();
8143
8144     unsigned NewIntNo = 0;
8145     EVT ShAmtVT = MVT::v4i32;
8146     switch (IntNo) {
8147     case Intrinsic::x86_sse2_pslli_w:
8148       NewIntNo = Intrinsic::x86_sse2_psll_w;
8149       break;
8150     case Intrinsic::x86_sse2_pslli_d:
8151       NewIntNo = Intrinsic::x86_sse2_psll_d;
8152       break;
8153     case Intrinsic::x86_sse2_pslli_q:
8154       NewIntNo = Intrinsic::x86_sse2_psll_q;
8155       break;
8156     case Intrinsic::x86_sse2_psrli_w:
8157       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8158       break;
8159     case Intrinsic::x86_sse2_psrli_d:
8160       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8161       break;
8162     case Intrinsic::x86_sse2_psrli_q:
8163       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8164       break;
8165     case Intrinsic::x86_sse2_psrai_w:
8166       NewIntNo = Intrinsic::x86_sse2_psra_w;
8167       break;
8168     case Intrinsic::x86_sse2_psrai_d:
8169       NewIntNo = Intrinsic::x86_sse2_psra_d;
8170       break;
8171     default: {
8172       ShAmtVT = MVT::v2i32;
8173       switch (IntNo) {
8174       case Intrinsic::x86_mmx_pslli_w:
8175         NewIntNo = Intrinsic::x86_mmx_psll_w;
8176         break;
8177       case Intrinsic::x86_mmx_pslli_d:
8178         NewIntNo = Intrinsic::x86_mmx_psll_d;
8179         break;
8180       case Intrinsic::x86_mmx_pslli_q:
8181         NewIntNo = Intrinsic::x86_mmx_psll_q;
8182         break;
8183       case Intrinsic::x86_mmx_psrli_w:
8184         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8185         break;
8186       case Intrinsic::x86_mmx_psrli_d:
8187         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8188         break;
8189       case Intrinsic::x86_mmx_psrli_q:
8190         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8191         break;
8192       case Intrinsic::x86_mmx_psrai_w:
8193         NewIntNo = Intrinsic::x86_mmx_psra_w;
8194         break;
8195       case Intrinsic::x86_mmx_psrai_d:
8196         NewIntNo = Intrinsic::x86_mmx_psra_d;
8197         break;
8198       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8199       }
8200       break;
8201     }
8202     }
8203
8204     // The vector shift intrinsics with scalars uses 32b shift amounts but
8205     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8206     // to be zero.
8207     SDValue ShOps[4];
8208     ShOps[0] = ShAmt;
8209     ShOps[1] = DAG.getConstant(0, MVT::i32);
8210     if (ShAmtVT == MVT::v4i32) {
8211       ShOps[2] = DAG.getUNDEF(MVT::i32);
8212       ShOps[3] = DAG.getUNDEF(MVT::i32);
8213       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8214     } else {
8215       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8216 // FIXME this must be lowered to get rid of the invalid type.
8217     }
8218
8219     EVT VT = Op.getValueType();
8220     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8221     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8222                        DAG.getConstant(NewIntNo, MVT::i32),
8223                        Op.getOperand(1), ShAmt);
8224   }
8225   }
8226 }
8227
8228 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8229                                            SelectionDAG &DAG) const {
8230   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8231   MFI->setReturnAddressIsTaken(true);
8232
8233   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8234   DebugLoc dl = Op.getDebugLoc();
8235
8236   if (Depth > 0) {
8237     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8238     SDValue Offset =
8239       DAG.getConstant(TD->getPointerSize(),
8240                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8241     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8242                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8243                                    FrameAddr, Offset),
8244                        MachinePointerInfo(), false, false, 0);
8245   }
8246
8247   // Just load the return address.
8248   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8249   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8250                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8251 }
8252
8253 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8254   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8255   MFI->setFrameAddressIsTaken(true);
8256
8257   EVT VT = Op.getValueType();
8258   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8259   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8260   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8261   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8262   while (Depth--)
8263     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8264                             MachinePointerInfo(),
8265                             false, false, 0);
8266   return FrameAddr;
8267 }
8268
8269 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8270                                                      SelectionDAG &DAG) const {
8271   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8272 }
8273
8274 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8275   MachineFunction &MF = DAG.getMachineFunction();
8276   SDValue Chain     = Op.getOperand(0);
8277   SDValue Offset    = Op.getOperand(1);
8278   SDValue Handler   = Op.getOperand(2);
8279   DebugLoc dl       = Op.getDebugLoc();
8280
8281   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8282                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8283                                      getPointerTy());
8284   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8285
8286   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8287                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8288   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8289   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8290                        false, false, 0);
8291   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8292   MF.getRegInfo().addLiveOut(StoreAddrReg);
8293
8294   return DAG.getNode(X86ISD::EH_RETURN, dl,
8295                      MVT::Other,
8296                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8297 }
8298
8299 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8300                                              SelectionDAG &DAG) const {
8301   SDValue Root = Op.getOperand(0);
8302   SDValue Trmp = Op.getOperand(1); // trampoline
8303   SDValue FPtr = Op.getOperand(2); // nested function
8304   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8305   DebugLoc dl  = Op.getDebugLoc();
8306
8307   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8308
8309   if (Subtarget->is64Bit()) {
8310     SDValue OutChains[6];
8311
8312     // Large code-model.
8313     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8314     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8315
8316     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8317     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8318
8319     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8320
8321     // Load the pointer to the nested function into R11.
8322     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8323     SDValue Addr = Trmp;
8324     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8325                                 Addr, MachinePointerInfo(TrmpAddr),
8326                                 false, false, 0);
8327
8328     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8329                        DAG.getConstant(2, MVT::i64));
8330     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8331                                 MachinePointerInfo(TrmpAddr, 2),
8332                                 false, false, 2);
8333
8334     // Load the 'nest' parameter value into R10.
8335     // R10 is specified in X86CallingConv.td
8336     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8337     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8338                        DAG.getConstant(10, MVT::i64));
8339     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8340                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8341                                 false, false, 0);
8342
8343     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8344                        DAG.getConstant(12, MVT::i64));
8345     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8346                                 MachinePointerInfo(TrmpAddr, 12),
8347                                 false, false, 2);
8348
8349     // Jump to the nested function.
8350     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8351     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8352                        DAG.getConstant(20, MVT::i64));
8353     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8354                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8355                                 false, false, 0);
8356
8357     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8358     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8359                        DAG.getConstant(22, MVT::i64));
8360     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8361                                 MachinePointerInfo(TrmpAddr, 22),
8362                                 false, false, 0);
8363
8364     SDValue Ops[] =
8365       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8366     return DAG.getMergeValues(Ops, 2, dl);
8367   } else {
8368     const Function *Func =
8369       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8370     CallingConv::ID CC = Func->getCallingConv();
8371     unsigned NestReg;
8372
8373     switch (CC) {
8374     default:
8375       llvm_unreachable("Unsupported calling convention");
8376     case CallingConv::C:
8377     case CallingConv::X86_StdCall: {
8378       // Pass 'nest' parameter in ECX.
8379       // Must be kept in sync with X86CallingConv.td
8380       NestReg = X86::ECX;
8381
8382       // Check that ECX wasn't needed by an 'inreg' parameter.
8383       const FunctionType *FTy = Func->getFunctionType();
8384       const AttrListPtr &Attrs = Func->getAttributes();
8385
8386       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8387         unsigned InRegCount = 0;
8388         unsigned Idx = 1;
8389
8390         for (FunctionType::param_iterator I = FTy->param_begin(),
8391              E = FTy->param_end(); I != E; ++I, ++Idx)
8392           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8393             // FIXME: should only count parameters that are lowered to integers.
8394             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8395
8396         if (InRegCount > 2) {
8397           report_fatal_error("Nest register in use - reduce number of inreg"
8398                              " parameters!");
8399         }
8400       }
8401       break;
8402     }
8403     case CallingConv::X86_FastCall:
8404     case CallingConv::X86_ThisCall:
8405     case CallingConv::Fast:
8406       // Pass 'nest' parameter in EAX.
8407       // Must be kept in sync with X86CallingConv.td
8408       NestReg = X86::EAX;
8409       break;
8410     }
8411
8412     SDValue OutChains[4];
8413     SDValue Addr, Disp;
8414
8415     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8416                        DAG.getConstant(10, MVT::i32));
8417     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8418
8419     // This is storing the opcode for MOV32ri.
8420     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8421     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8422     OutChains[0] = DAG.getStore(Root, dl,
8423                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8424                                 Trmp, MachinePointerInfo(TrmpAddr),
8425                                 false, false, 0);
8426
8427     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8428                        DAG.getConstant(1, MVT::i32));
8429     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8430                                 MachinePointerInfo(TrmpAddr, 1),
8431                                 false, false, 1);
8432
8433     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8434     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8435                        DAG.getConstant(5, MVT::i32));
8436     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8437                                 MachinePointerInfo(TrmpAddr, 5),
8438                                 false, false, 1);
8439
8440     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8441                        DAG.getConstant(6, MVT::i32));
8442     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8443                                 MachinePointerInfo(TrmpAddr, 6),
8444                                 false, false, 1);
8445
8446     SDValue Ops[] =
8447       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8448     return DAG.getMergeValues(Ops, 2, dl);
8449   }
8450 }
8451
8452 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8453                                             SelectionDAG &DAG) const {
8454   /*
8455    The rounding mode is in bits 11:10 of FPSR, and has the following
8456    settings:
8457      00 Round to nearest
8458      01 Round to -inf
8459      10 Round to +inf
8460      11 Round to 0
8461
8462   FLT_ROUNDS, on the other hand, expects the following:
8463     -1 Undefined
8464      0 Round to 0
8465      1 Round to nearest
8466      2 Round to +inf
8467      3 Round to -inf
8468
8469   To perform the conversion, we do:
8470     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8471   */
8472
8473   MachineFunction &MF = DAG.getMachineFunction();
8474   const TargetMachine &TM = MF.getTarget();
8475   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8476   unsigned StackAlignment = TFI.getStackAlignment();
8477   EVT VT = Op.getValueType();
8478   DebugLoc DL = Op.getDebugLoc();
8479
8480   // Save FP Control Word to stack slot
8481   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8482   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8483
8484
8485   MachineMemOperand *MMO =
8486    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8487                            MachineMemOperand::MOStore, 2, 2);
8488
8489   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8490   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8491                                           DAG.getVTList(MVT::Other),
8492                                           Ops, 2, MVT::i16, MMO);
8493
8494   // Load FP Control Word from stack slot
8495   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8496                             MachinePointerInfo(), false, false, 0);
8497
8498   // Transform as necessary
8499   SDValue CWD1 =
8500     DAG.getNode(ISD::SRL, DL, MVT::i16,
8501                 DAG.getNode(ISD::AND, DL, MVT::i16,
8502                             CWD, DAG.getConstant(0x800, MVT::i16)),
8503                 DAG.getConstant(11, MVT::i8));
8504   SDValue CWD2 =
8505     DAG.getNode(ISD::SRL, DL, MVT::i16,
8506                 DAG.getNode(ISD::AND, DL, MVT::i16,
8507                             CWD, DAG.getConstant(0x400, MVT::i16)),
8508                 DAG.getConstant(9, MVT::i8));
8509
8510   SDValue RetVal =
8511     DAG.getNode(ISD::AND, DL, MVT::i16,
8512                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8513                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8514                             DAG.getConstant(1, MVT::i16)),
8515                 DAG.getConstant(3, MVT::i16));
8516
8517
8518   return DAG.getNode((VT.getSizeInBits() < 16 ?
8519                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8520 }
8521
8522 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8523   EVT VT = Op.getValueType();
8524   EVT OpVT = VT;
8525   unsigned NumBits = VT.getSizeInBits();
8526   DebugLoc dl = Op.getDebugLoc();
8527
8528   Op = Op.getOperand(0);
8529   if (VT == MVT::i8) {
8530     // Zero extend to i32 since there is not an i8 bsr.
8531     OpVT = MVT::i32;
8532     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8533   }
8534
8535   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8536   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8537   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8538
8539   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8540   SDValue Ops[] = {
8541     Op,
8542     DAG.getConstant(NumBits+NumBits-1, OpVT),
8543     DAG.getConstant(X86::COND_E, MVT::i8),
8544     Op.getValue(1)
8545   };
8546   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8547
8548   // Finally xor with NumBits-1.
8549   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8550
8551   if (VT == MVT::i8)
8552     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8553   return Op;
8554 }
8555
8556 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8557   EVT VT = Op.getValueType();
8558   EVT OpVT = VT;
8559   unsigned NumBits = VT.getSizeInBits();
8560   DebugLoc dl = Op.getDebugLoc();
8561
8562   Op = Op.getOperand(0);
8563   if (VT == MVT::i8) {
8564     OpVT = MVT::i32;
8565     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8566   }
8567
8568   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8569   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8570   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8571
8572   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8573   SDValue Ops[] = {
8574     Op,
8575     DAG.getConstant(NumBits, OpVT),
8576     DAG.getConstant(X86::COND_E, MVT::i8),
8577     Op.getValue(1)
8578   };
8579   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8580
8581   if (VT == MVT::i8)
8582     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8583   return Op;
8584 }
8585
8586 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8587   EVT VT = Op.getValueType();
8588   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8589   DebugLoc dl = Op.getDebugLoc();
8590
8591   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8592   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8593   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8594   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8595   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8596   //
8597   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8598   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8599   //  return AloBlo + AloBhi + AhiBlo;
8600
8601   SDValue A = Op.getOperand(0);
8602   SDValue B = Op.getOperand(1);
8603
8604   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8605                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8606                        A, DAG.getConstant(32, MVT::i32));
8607   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8608                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8609                        B, DAG.getConstant(32, MVT::i32));
8610   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8611                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8612                        A, B);
8613   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8614                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8615                        A, Bhi);
8616   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8617                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8618                        Ahi, B);
8619   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8620                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8621                        AloBhi, DAG.getConstant(32, MVT::i32));
8622   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8623                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8624                        AhiBlo, DAG.getConstant(32, MVT::i32));
8625   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8626   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8627   return Res;
8628 }
8629
8630 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8631   EVT VT = Op.getValueType();
8632   DebugLoc dl = Op.getDebugLoc();
8633   SDValue R = Op.getOperand(0);
8634
8635   LLVMContext *Context = DAG.getContext();
8636
8637   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8638
8639   if (VT == MVT::v4i32) {
8640     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8641                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8642                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8643
8644     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8645
8646     std::vector<Constant*> CV(4, CI);
8647     Constant *C = ConstantVector::get(CV);
8648     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8649     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8650                                  MachinePointerInfo::getConstantPool(),
8651                                  false, false, 16);
8652
8653     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8654     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8655     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8656     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8657   }
8658   if (VT == MVT::v16i8) {
8659     // a = a << 5;
8660     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8661                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8662                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8663
8664     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8665     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8666
8667     std::vector<Constant*> CVM1(16, CM1);
8668     std::vector<Constant*> CVM2(16, CM2);
8669     Constant *C = ConstantVector::get(CVM1);
8670     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8671     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8672                             MachinePointerInfo::getConstantPool(),
8673                             false, false, 16);
8674
8675     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8676     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8677     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8678                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8679                     DAG.getConstant(4, MVT::i32));
8680     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8681     // a += a
8682     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8683
8684     C = ConstantVector::get(CVM2);
8685     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8686     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8687                     MachinePointerInfo::getConstantPool(),
8688                     false, false, 16);
8689
8690     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8691     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8692     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8693                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8694                     DAG.getConstant(2, MVT::i32));
8695     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8696     // a += a
8697     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8698
8699     // return pblendv(r, r+r, a);
8700     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8701                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8702     return R;
8703   }
8704   return SDValue();
8705 }
8706
8707 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8708   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8709   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8710   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8711   // has only one use.
8712   SDNode *N = Op.getNode();
8713   SDValue LHS = N->getOperand(0);
8714   SDValue RHS = N->getOperand(1);
8715   unsigned BaseOp = 0;
8716   unsigned Cond = 0;
8717   DebugLoc DL = Op.getDebugLoc();
8718   switch (Op.getOpcode()) {
8719   default: llvm_unreachable("Unknown ovf instruction!");
8720   case ISD::SADDO:
8721     // A subtract of one will be selected as a INC. Note that INC doesn't
8722     // set CF, so we can't do this for UADDO.
8723     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8724       if (C->getAPIntValue() == 1) {
8725         BaseOp = X86ISD::INC;
8726         Cond = X86::COND_O;
8727         break;
8728       }
8729     BaseOp = X86ISD::ADD;
8730     Cond = X86::COND_O;
8731     break;
8732   case ISD::UADDO:
8733     BaseOp = X86ISD::ADD;
8734     Cond = X86::COND_B;
8735     break;
8736   case ISD::SSUBO:
8737     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8738     // set CF, so we can't do this for USUBO.
8739     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8740       if (C->getAPIntValue() == 1) {
8741         BaseOp = X86ISD::DEC;
8742         Cond = X86::COND_O;
8743         break;
8744       }
8745     BaseOp = X86ISD::SUB;
8746     Cond = X86::COND_O;
8747     break;
8748   case ISD::USUBO:
8749     BaseOp = X86ISD::SUB;
8750     Cond = X86::COND_B;
8751     break;
8752   case ISD::SMULO:
8753     BaseOp = X86ISD::SMUL;
8754     Cond = X86::COND_O;
8755     break;
8756   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8757     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8758                                  MVT::i32);
8759     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8760
8761     SDValue SetCC =
8762       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8763                   DAG.getConstant(X86::COND_O, MVT::i32),
8764                   SDValue(Sum.getNode(), 2));
8765
8766     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8767     return Sum;
8768   }
8769   }
8770
8771   // Also sets EFLAGS.
8772   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8773   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8774
8775   SDValue SetCC =
8776     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8777                 DAG.getConstant(Cond, MVT::i32),
8778                 SDValue(Sum.getNode(), 1));
8779
8780   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8781   return Sum;
8782 }
8783
8784 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8785   DebugLoc dl = Op.getDebugLoc();
8786
8787   if (!Subtarget->hasSSE2()) {
8788     SDValue Chain = Op.getOperand(0);
8789     SDValue Zero = DAG.getConstant(0,
8790                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8791     SDValue Ops[] = {
8792       DAG.getRegister(X86::ESP, MVT::i32), // Base
8793       DAG.getTargetConstant(1, MVT::i8),   // Scale
8794       DAG.getRegister(0, MVT::i32),        // Index
8795       DAG.getTargetConstant(0, MVT::i32),  // Disp
8796       DAG.getRegister(0, MVT::i32),        // Segment.
8797       Zero,
8798       Chain
8799     };
8800     SDNode *Res =
8801       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8802                           array_lengthof(Ops));
8803     return SDValue(Res, 0);
8804   }
8805
8806   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8807   if (!isDev)
8808     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8809
8810   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8811   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8812   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8813   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8814
8815   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8816   if (!Op1 && !Op2 && !Op3 && Op4)
8817     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8818
8819   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8820   if (Op1 && !Op2 && !Op3 && !Op4)
8821     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8822
8823   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8824   //           (MFENCE)>;
8825   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8826 }
8827
8828 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8829   EVT T = Op.getValueType();
8830   DebugLoc DL = Op.getDebugLoc();
8831   unsigned Reg = 0;
8832   unsigned size = 0;
8833   switch(T.getSimpleVT().SimpleTy) {
8834   default:
8835     assert(false && "Invalid value type!");
8836   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8837   case MVT::i16: Reg = X86::AX;  size = 2; break;
8838   case MVT::i32: Reg = X86::EAX; size = 4; break;
8839   case MVT::i64:
8840     assert(Subtarget->is64Bit() && "Node not type legal!");
8841     Reg = X86::RAX; size = 8;
8842     break;
8843   }
8844   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8845                                     Op.getOperand(2), SDValue());
8846   SDValue Ops[] = { cpIn.getValue(0),
8847                     Op.getOperand(1),
8848                     Op.getOperand(3),
8849                     DAG.getTargetConstant(size, MVT::i8),
8850                     cpIn.getValue(1) };
8851   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8852   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8853   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8854                                            Ops, 5, T, MMO);
8855   SDValue cpOut =
8856     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8857   return cpOut;
8858 }
8859
8860 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8861                                                  SelectionDAG &DAG) const {
8862   assert(Subtarget->is64Bit() && "Result not type legalized?");
8863   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8864   SDValue TheChain = Op.getOperand(0);
8865   DebugLoc dl = Op.getDebugLoc();
8866   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8867   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8868   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8869                                    rax.getValue(2));
8870   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8871                             DAG.getConstant(32, MVT::i8));
8872   SDValue Ops[] = {
8873     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8874     rdx.getValue(1)
8875   };
8876   return DAG.getMergeValues(Ops, 2, dl);
8877 }
8878
8879 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8880                                             SelectionDAG &DAG) const {
8881   EVT SrcVT = Op.getOperand(0).getValueType();
8882   EVT DstVT = Op.getValueType();
8883   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8884          Subtarget->hasMMX() && "Unexpected custom BITCAST");
8885   assert((DstVT == MVT::i64 ||
8886           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8887          "Unexpected custom BITCAST");
8888   // i64 <=> MMX conversions are Legal.
8889   if (SrcVT==MVT::i64 && DstVT.isVector())
8890     return Op;
8891   if (DstVT==MVT::i64 && SrcVT.isVector())
8892     return Op;
8893   // MMX <=> MMX conversions are Legal.
8894   if (SrcVT.isVector() && DstVT.isVector())
8895     return Op;
8896   // All other conversions need to be expanded.
8897   return SDValue();
8898 }
8899
8900 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8901   SDNode *Node = Op.getNode();
8902   DebugLoc dl = Node->getDebugLoc();
8903   EVT T = Node->getValueType(0);
8904   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8905                               DAG.getConstant(0, T), Node->getOperand(2));
8906   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8907                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8908                        Node->getOperand(0),
8909                        Node->getOperand(1), negOp,
8910                        cast<AtomicSDNode>(Node)->getSrcValue(),
8911                        cast<AtomicSDNode>(Node)->getAlignment());
8912 }
8913
8914 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8915   EVT VT = Op.getNode()->getValueType(0);
8916
8917   // Let legalize expand this if it isn't a legal type yet.
8918   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8919     return SDValue();
8920
8921   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8922
8923   unsigned Opc;
8924   bool ExtraOp = false;
8925   switch (Op.getOpcode()) {
8926   default: assert(0 && "Invalid code");
8927   case ISD::ADDC: Opc = X86ISD::ADD; break;
8928   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8929   case ISD::SUBC: Opc = X86ISD::SUB; break;
8930   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8931   }
8932
8933   if (!ExtraOp)
8934     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8935                        Op.getOperand(1));
8936   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8937                      Op.getOperand(1), Op.getOperand(2));
8938 }
8939
8940 /// LowerOperation - Provide custom lowering hooks for some operations.
8941 ///
8942 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8943   switch (Op.getOpcode()) {
8944   default: llvm_unreachable("Should not custom lower this!");
8945   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8946   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8947   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8948   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8949   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8950   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8951   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8952   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8953   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
8954   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
8955   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8956   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8957   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8958   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8959   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8960   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8961   case ISD::SHL_PARTS:
8962   case ISD::SRA_PARTS:
8963   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8964   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8965   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8966   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8967   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8968   case ISD::FABS:               return LowerFABS(Op, DAG);
8969   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8970   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8971   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8972   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8973   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8974   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8975   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8976   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8977   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8978   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8979   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8980   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8981   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8982   case ISD::FRAME_TO_ARGS_OFFSET:
8983                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8984   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8985   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8986   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8987   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8988   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8989   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8990   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8991   case ISD::SHL:                return LowerSHL(Op, DAG);
8992   case ISD::SADDO:
8993   case ISD::UADDO:
8994   case ISD::SSUBO:
8995   case ISD::USUBO:
8996   case ISD::SMULO:
8997   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8998   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8999   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9000   case ISD::ADDC:
9001   case ISD::ADDE:
9002   case ISD::SUBC:
9003   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9004   }
9005 }
9006
9007 void X86TargetLowering::
9008 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9009                         SelectionDAG &DAG, unsigned NewOp) const {
9010   EVT T = Node->getValueType(0);
9011   DebugLoc dl = Node->getDebugLoc();
9012   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9013
9014   SDValue Chain = Node->getOperand(0);
9015   SDValue In1 = Node->getOperand(1);
9016   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9017                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9018   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9019                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9020   SDValue Ops[] = { Chain, In1, In2L, In2H };
9021   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9022   SDValue Result =
9023     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9024                             cast<MemSDNode>(Node)->getMemOperand());
9025   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9026   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9027   Results.push_back(Result.getValue(2));
9028 }
9029
9030 /// ReplaceNodeResults - Replace a node with an illegal result type
9031 /// with a new node built out of custom code.
9032 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9033                                            SmallVectorImpl<SDValue>&Results,
9034                                            SelectionDAG &DAG) const {
9035   DebugLoc dl = N->getDebugLoc();
9036   switch (N->getOpcode()) {
9037   default:
9038     assert(false && "Do not know how to custom type legalize this operation!");
9039     return;
9040   case ISD::ADDC:
9041   case ISD::ADDE:
9042   case ISD::SUBC:
9043   case ISD::SUBE:
9044     // We don't want to expand or promote these.
9045     return;
9046   case ISD::FP_TO_SINT: {
9047     std::pair<SDValue,SDValue> Vals =
9048         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9049     SDValue FIST = Vals.first, StackSlot = Vals.second;
9050     if (FIST.getNode() != 0) {
9051       EVT VT = N->getValueType(0);
9052       // Return a load from the stack slot.
9053       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9054                                     MachinePointerInfo(), false, false, 0));
9055     }
9056     return;
9057   }
9058   case ISD::READCYCLECOUNTER: {
9059     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9060     SDValue TheChain = N->getOperand(0);
9061     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9062     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9063                                      rd.getValue(1));
9064     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9065                                      eax.getValue(2));
9066     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9067     SDValue Ops[] = { eax, edx };
9068     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9069     Results.push_back(edx.getValue(1));
9070     return;
9071   }
9072   case ISD::ATOMIC_CMP_SWAP: {
9073     EVT T = N->getValueType(0);
9074     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9075     SDValue cpInL, cpInH;
9076     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9077                         DAG.getConstant(0, MVT::i32));
9078     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9079                         DAG.getConstant(1, MVT::i32));
9080     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9081     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9082                              cpInL.getValue(1));
9083     SDValue swapInL, swapInH;
9084     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9085                           DAG.getConstant(0, MVT::i32));
9086     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9087                           DAG.getConstant(1, MVT::i32));
9088     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9089                                cpInH.getValue(1));
9090     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9091                                swapInL.getValue(1));
9092     SDValue Ops[] = { swapInH.getValue(0),
9093                       N->getOperand(1),
9094                       swapInH.getValue(1) };
9095     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9096     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9097     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9098                                              Ops, 3, T, MMO);
9099     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9100                                         MVT::i32, Result.getValue(1));
9101     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9102                                         MVT::i32, cpOutL.getValue(2));
9103     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9104     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9105     Results.push_back(cpOutH.getValue(1));
9106     return;
9107   }
9108   case ISD::ATOMIC_LOAD_ADD:
9109     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9110     return;
9111   case ISD::ATOMIC_LOAD_AND:
9112     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9113     return;
9114   case ISD::ATOMIC_LOAD_NAND:
9115     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9116     return;
9117   case ISD::ATOMIC_LOAD_OR:
9118     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9119     return;
9120   case ISD::ATOMIC_LOAD_SUB:
9121     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9122     return;
9123   case ISD::ATOMIC_LOAD_XOR:
9124     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9125     return;
9126   case ISD::ATOMIC_SWAP:
9127     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9128     return;
9129   }
9130 }
9131
9132 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9133   switch (Opcode) {
9134   default: return NULL;
9135   case X86ISD::BSF:                return "X86ISD::BSF";
9136   case X86ISD::BSR:                return "X86ISD::BSR";
9137   case X86ISD::SHLD:               return "X86ISD::SHLD";
9138   case X86ISD::SHRD:               return "X86ISD::SHRD";
9139   case X86ISD::FAND:               return "X86ISD::FAND";
9140   case X86ISD::FOR:                return "X86ISD::FOR";
9141   case X86ISD::FXOR:               return "X86ISD::FXOR";
9142   case X86ISD::FSRL:               return "X86ISD::FSRL";
9143   case X86ISD::FILD:               return "X86ISD::FILD";
9144   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9145   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9146   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9147   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9148   case X86ISD::FLD:                return "X86ISD::FLD";
9149   case X86ISD::FST:                return "X86ISD::FST";
9150   case X86ISD::CALL:               return "X86ISD::CALL";
9151   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9152   case X86ISD::BT:                 return "X86ISD::BT";
9153   case X86ISD::CMP:                return "X86ISD::CMP";
9154   case X86ISD::COMI:               return "X86ISD::COMI";
9155   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9156   case X86ISD::SETCC:              return "X86ISD::SETCC";
9157   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9158   case X86ISD::CMOV:               return "X86ISD::CMOV";
9159   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9160   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9161   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9162   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9163   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9164   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9165   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9166   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9167   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9168   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9169   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9170   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9171   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9172   case X86ISD::PANDN:              return "X86ISD::PANDN";
9173   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9174   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9175   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9176   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9177   case X86ISD::FMAX:               return "X86ISD::FMAX";
9178   case X86ISD::FMIN:               return "X86ISD::FMIN";
9179   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9180   case X86ISD::FRCP:               return "X86ISD::FRCP";
9181   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9182   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9183   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9184   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9185   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9186   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9187   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9188   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9189   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9190   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9191   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9192   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9193   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9194   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9195   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9196   case X86ISD::VSHL:               return "X86ISD::VSHL";
9197   case X86ISD::VSRL:               return "X86ISD::VSRL";
9198   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9199   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9200   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9201   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9202   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9203   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9204   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9205   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9206   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9207   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9208   case X86ISD::ADD:                return "X86ISD::ADD";
9209   case X86ISD::SUB:                return "X86ISD::SUB";
9210   case X86ISD::ADC:                return "X86ISD::ADC";
9211   case X86ISD::SBB:                return "X86ISD::SBB";
9212   case X86ISD::SMUL:               return "X86ISD::SMUL";
9213   case X86ISD::UMUL:               return "X86ISD::UMUL";
9214   case X86ISD::INC:                return "X86ISD::INC";
9215   case X86ISD::DEC:                return "X86ISD::DEC";
9216   case X86ISD::OR:                 return "X86ISD::OR";
9217   case X86ISD::XOR:                return "X86ISD::XOR";
9218   case X86ISD::AND:                return "X86ISD::AND";
9219   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9220   case X86ISD::PTEST:              return "X86ISD::PTEST";
9221   case X86ISD::TESTP:              return "X86ISD::TESTP";
9222   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9223   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9224   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9225   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9226   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9227   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9228   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9229   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9230   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9231   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9232   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9233   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9234   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9235   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9236   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9237   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9238   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9239   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9240   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9241   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9242   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9243   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9244   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9245   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9246   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9247   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9248   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9249   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9250   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9251   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9252   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9253   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9254   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9255   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9256   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9257   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9258   }
9259 }
9260
9261 // isLegalAddressingMode - Return true if the addressing mode represented
9262 // by AM is legal for this target, for a load/store of the specified type.
9263 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9264                                               const Type *Ty) const {
9265   // X86 supports extremely general addressing modes.
9266   CodeModel::Model M = getTargetMachine().getCodeModel();
9267   Reloc::Model R = getTargetMachine().getRelocationModel();
9268
9269   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9270   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9271     return false;
9272
9273   if (AM.BaseGV) {
9274     unsigned GVFlags =
9275       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9276
9277     // If a reference to this global requires an extra load, we can't fold it.
9278     if (isGlobalStubReference(GVFlags))
9279       return false;
9280
9281     // If BaseGV requires a register for the PIC base, we cannot also have a
9282     // BaseReg specified.
9283     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9284       return false;
9285
9286     // If lower 4G is not available, then we must use rip-relative addressing.
9287     if ((M != CodeModel::Small || R != Reloc::Static) &&
9288         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9289       return false;
9290   }
9291
9292   switch (AM.Scale) {
9293   case 0:
9294   case 1:
9295   case 2:
9296   case 4:
9297   case 8:
9298     // These scales always work.
9299     break;
9300   case 3:
9301   case 5:
9302   case 9:
9303     // These scales are formed with basereg+scalereg.  Only accept if there is
9304     // no basereg yet.
9305     if (AM.HasBaseReg)
9306       return false;
9307     break;
9308   default:  // Other stuff never works.
9309     return false;
9310   }
9311
9312   return true;
9313 }
9314
9315
9316 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9317   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9318     return false;
9319   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9320   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9321   if (NumBits1 <= NumBits2)
9322     return false;
9323   return true;
9324 }
9325
9326 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9327   if (!VT1.isInteger() || !VT2.isInteger())
9328     return false;
9329   unsigned NumBits1 = VT1.getSizeInBits();
9330   unsigned NumBits2 = VT2.getSizeInBits();
9331   if (NumBits1 <= NumBits2)
9332     return false;
9333   return true;
9334 }
9335
9336 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9337   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9338   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9339 }
9340
9341 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9342   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9343   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9344 }
9345
9346 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9347   // i16 instructions are longer (0x66 prefix) and potentially slower.
9348   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9349 }
9350
9351 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9352 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9353 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9354 /// are assumed to be legal.
9355 bool
9356 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9357                                       EVT VT) const {
9358   // Very little shuffling can be done for 64-bit vectors right now.
9359   if (VT.getSizeInBits() == 64)
9360     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9361
9362   // FIXME: pshufb, blends, shifts.
9363   return (VT.getVectorNumElements() == 2 ||
9364           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9365           isMOVLMask(M, VT) ||
9366           isSHUFPMask(M, VT) ||
9367           isPSHUFDMask(M, VT) ||
9368           isPSHUFHWMask(M, VT) ||
9369           isPSHUFLWMask(M, VT) ||
9370           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9371           isUNPCKLMask(M, VT) ||
9372           isUNPCKHMask(M, VT) ||
9373           isUNPCKL_v_undef_Mask(M, VT) ||
9374           isUNPCKH_v_undef_Mask(M, VT));
9375 }
9376
9377 bool
9378 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9379                                           EVT VT) const {
9380   unsigned NumElts = VT.getVectorNumElements();
9381   // FIXME: This collection of masks seems suspect.
9382   if (NumElts == 2)
9383     return true;
9384   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9385     return (isMOVLMask(Mask, VT)  ||
9386             isCommutedMOVLMask(Mask, VT, true) ||
9387             isSHUFPMask(Mask, VT) ||
9388             isCommutedSHUFPMask(Mask, VT));
9389   }
9390   return false;
9391 }
9392
9393 //===----------------------------------------------------------------------===//
9394 //                           X86 Scheduler Hooks
9395 //===----------------------------------------------------------------------===//
9396
9397 // private utility function
9398 MachineBasicBlock *
9399 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9400                                                        MachineBasicBlock *MBB,
9401                                                        unsigned regOpc,
9402                                                        unsigned immOpc,
9403                                                        unsigned LoadOpc,
9404                                                        unsigned CXchgOpc,
9405                                                        unsigned notOpc,
9406                                                        unsigned EAXreg,
9407                                                        TargetRegisterClass *RC,
9408                                                        bool invSrc) const {
9409   // For the atomic bitwise operator, we generate
9410   //   thisMBB:
9411   //   newMBB:
9412   //     ld  t1 = [bitinstr.addr]
9413   //     op  t2 = t1, [bitinstr.val]
9414   //     mov EAX = t1
9415   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9416   //     bz  newMBB
9417   //     fallthrough -->nextMBB
9418   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9419   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9420   MachineFunction::iterator MBBIter = MBB;
9421   ++MBBIter;
9422
9423   /// First build the CFG
9424   MachineFunction *F = MBB->getParent();
9425   MachineBasicBlock *thisMBB = MBB;
9426   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9427   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9428   F->insert(MBBIter, newMBB);
9429   F->insert(MBBIter, nextMBB);
9430
9431   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9432   nextMBB->splice(nextMBB->begin(), thisMBB,
9433                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9434                   thisMBB->end());
9435   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9436
9437   // Update thisMBB to fall through to newMBB
9438   thisMBB->addSuccessor(newMBB);
9439
9440   // newMBB jumps to itself and fall through to nextMBB
9441   newMBB->addSuccessor(nextMBB);
9442   newMBB->addSuccessor(newMBB);
9443
9444   // Insert instructions into newMBB based on incoming instruction
9445   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9446          "unexpected number of operands");
9447   DebugLoc dl = bInstr->getDebugLoc();
9448   MachineOperand& destOper = bInstr->getOperand(0);
9449   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9450   int numArgs = bInstr->getNumOperands() - 1;
9451   for (int i=0; i < numArgs; ++i)
9452     argOpers[i] = &bInstr->getOperand(i+1);
9453
9454   // x86 address has 4 operands: base, index, scale, and displacement
9455   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9456   int valArgIndx = lastAddrIndx + 1;
9457
9458   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9459   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9460   for (int i=0; i <= lastAddrIndx; ++i)
9461     (*MIB).addOperand(*argOpers[i]);
9462
9463   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9464   if (invSrc) {
9465     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9466   }
9467   else
9468     tt = t1;
9469
9470   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9471   assert((argOpers[valArgIndx]->isReg() ||
9472           argOpers[valArgIndx]->isImm()) &&
9473          "invalid operand");
9474   if (argOpers[valArgIndx]->isReg())
9475     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9476   else
9477     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9478   MIB.addReg(tt);
9479   (*MIB).addOperand(*argOpers[valArgIndx]);
9480
9481   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9482   MIB.addReg(t1);
9483
9484   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9485   for (int i=0; i <= lastAddrIndx; ++i)
9486     (*MIB).addOperand(*argOpers[i]);
9487   MIB.addReg(t2);
9488   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9489   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9490                     bInstr->memoperands_end());
9491
9492   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9493   MIB.addReg(EAXreg);
9494
9495   // insert branch
9496   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9497
9498   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9499   return nextMBB;
9500 }
9501
9502 // private utility function:  64 bit atomics on 32 bit host.
9503 MachineBasicBlock *
9504 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9505                                                        MachineBasicBlock *MBB,
9506                                                        unsigned regOpcL,
9507                                                        unsigned regOpcH,
9508                                                        unsigned immOpcL,
9509                                                        unsigned immOpcH,
9510                                                        bool invSrc) const {
9511   // For the atomic bitwise operator, we generate
9512   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9513   //     ld t1,t2 = [bitinstr.addr]
9514   //   newMBB:
9515   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9516   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9517   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9518   //     mov ECX, EBX <- t5, t6
9519   //     mov EAX, EDX <- t1, t2
9520   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9521   //     mov t3, t4 <- EAX, EDX
9522   //     bz  newMBB
9523   //     result in out1, out2
9524   //     fallthrough -->nextMBB
9525
9526   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9527   const unsigned LoadOpc = X86::MOV32rm;
9528   const unsigned NotOpc = X86::NOT32r;
9529   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9530   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9531   MachineFunction::iterator MBBIter = MBB;
9532   ++MBBIter;
9533
9534   /// First build the CFG
9535   MachineFunction *F = MBB->getParent();
9536   MachineBasicBlock *thisMBB = MBB;
9537   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9538   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9539   F->insert(MBBIter, newMBB);
9540   F->insert(MBBIter, nextMBB);
9541
9542   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9543   nextMBB->splice(nextMBB->begin(), thisMBB,
9544                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9545                   thisMBB->end());
9546   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9547
9548   // Update thisMBB to fall through to newMBB
9549   thisMBB->addSuccessor(newMBB);
9550
9551   // newMBB jumps to itself and fall through to nextMBB
9552   newMBB->addSuccessor(nextMBB);
9553   newMBB->addSuccessor(newMBB);
9554
9555   DebugLoc dl = bInstr->getDebugLoc();
9556   // Insert instructions into newMBB based on incoming instruction
9557   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9558   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9559          "unexpected number of operands");
9560   MachineOperand& dest1Oper = bInstr->getOperand(0);
9561   MachineOperand& dest2Oper = bInstr->getOperand(1);
9562   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9563   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9564     argOpers[i] = &bInstr->getOperand(i+2);
9565
9566     // We use some of the operands multiple times, so conservatively just
9567     // clear any kill flags that might be present.
9568     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9569       argOpers[i]->setIsKill(false);
9570   }
9571
9572   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9573   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9574
9575   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9576   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9577   for (int i=0; i <= lastAddrIndx; ++i)
9578     (*MIB).addOperand(*argOpers[i]);
9579   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9580   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9581   // add 4 to displacement.
9582   for (int i=0; i <= lastAddrIndx-2; ++i)
9583     (*MIB).addOperand(*argOpers[i]);
9584   MachineOperand newOp3 = *(argOpers[3]);
9585   if (newOp3.isImm())
9586     newOp3.setImm(newOp3.getImm()+4);
9587   else
9588     newOp3.setOffset(newOp3.getOffset()+4);
9589   (*MIB).addOperand(newOp3);
9590   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9591
9592   // t3/4 are defined later, at the bottom of the loop
9593   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9594   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9595   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9596     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9597   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9598     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9599
9600   // The subsequent operations should be using the destination registers of
9601   //the PHI instructions.
9602   if (invSrc) {
9603     t1 = F->getRegInfo().createVirtualRegister(RC);
9604     t2 = F->getRegInfo().createVirtualRegister(RC);
9605     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9606     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9607   } else {
9608     t1 = dest1Oper.getReg();
9609     t2 = dest2Oper.getReg();
9610   }
9611
9612   int valArgIndx = lastAddrIndx + 1;
9613   assert((argOpers[valArgIndx]->isReg() ||
9614           argOpers[valArgIndx]->isImm()) &&
9615          "invalid operand");
9616   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9617   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9618   if (argOpers[valArgIndx]->isReg())
9619     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9620   else
9621     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9622   if (regOpcL != X86::MOV32rr)
9623     MIB.addReg(t1);
9624   (*MIB).addOperand(*argOpers[valArgIndx]);
9625   assert(argOpers[valArgIndx + 1]->isReg() ==
9626          argOpers[valArgIndx]->isReg());
9627   assert(argOpers[valArgIndx + 1]->isImm() ==
9628          argOpers[valArgIndx]->isImm());
9629   if (argOpers[valArgIndx + 1]->isReg())
9630     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9631   else
9632     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9633   if (regOpcH != X86::MOV32rr)
9634     MIB.addReg(t2);
9635   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9636
9637   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9638   MIB.addReg(t1);
9639   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9640   MIB.addReg(t2);
9641
9642   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9643   MIB.addReg(t5);
9644   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9645   MIB.addReg(t6);
9646
9647   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9648   for (int i=0; i <= lastAddrIndx; ++i)
9649     (*MIB).addOperand(*argOpers[i]);
9650
9651   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9652   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9653                     bInstr->memoperands_end());
9654
9655   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9656   MIB.addReg(X86::EAX);
9657   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9658   MIB.addReg(X86::EDX);
9659
9660   // insert branch
9661   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9662
9663   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9664   return nextMBB;
9665 }
9666
9667 // private utility function
9668 MachineBasicBlock *
9669 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9670                                                       MachineBasicBlock *MBB,
9671                                                       unsigned cmovOpc) const {
9672   // For the atomic min/max operator, we generate
9673   //   thisMBB:
9674   //   newMBB:
9675   //     ld t1 = [min/max.addr]
9676   //     mov t2 = [min/max.val]
9677   //     cmp  t1, t2
9678   //     cmov[cond] t2 = t1
9679   //     mov EAX = t1
9680   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9681   //     bz   newMBB
9682   //     fallthrough -->nextMBB
9683   //
9684   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9685   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9686   MachineFunction::iterator MBBIter = MBB;
9687   ++MBBIter;
9688
9689   /// First build the CFG
9690   MachineFunction *F = MBB->getParent();
9691   MachineBasicBlock *thisMBB = MBB;
9692   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9693   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9694   F->insert(MBBIter, newMBB);
9695   F->insert(MBBIter, nextMBB);
9696
9697   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9698   nextMBB->splice(nextMBB->begin(), thisMBB,
9699                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9700                   thisMBB->end());
9701   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9702
9703   // Update thisMBB to fall through to newMBB
9704   thisMBB->addSuccessor(newMBB);
9705
9706   // newMBB jumps to newMBB and fall through to nextMBB
9707   newMBB->addSuccessor(nextMBB);
9708   newMBB->addSuccessor(newMBB);
9709
9710   DebugLoc dl = mInstr->getDebugLoc();
9711   // Insert instructions into newMBB based on incoming instruction
9712   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9713          "unexpected number of operands");
9714   MachineOperand& destOper = mInstr->getOperand(0);
9715   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9716   int numArgs = mInstr->getNumOperands() - 1;
9717   for (int i=0; i < numArgs; ++i)
9718     argOpers[i] = &mInstr->getOperand(i+1);
9719
9720   // x86 address has 4 operands: base, index, scale, and displacement
9721   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9722   int valArgIndx = lastAddrIndx + 1;
9723
9724   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9725   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9726   for (int i=0; i <= lastAddrIndx; ++i)
9727     (*MIB).addOperand(*argOpers[i]);
9728
9729   // We only support register and immediate values
9730   assert((argOpers[valArgIndx]->isReg() ||
9731           argOpers[valArgIndx]->isImm()) &&
9732          "invalid operand");
9733
9734   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9735   if (argOpers[valArgIndx]->isReg())
9736     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9737   else
9738     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9739   (*MIB).addOperand(*argOpers[valArgIndx]);
9740
9741   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9742   MIB.addReg(t1);
9743
9744   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9745   MIB.addReg(t1);
9746   MIB.addReg(t2);
9747
9748   // Generate movc
9749   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9750   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9751   MIB.addReg(t2);
9752   MIB.addReg(t1);
9753
9754   // Cmp and exchange if none has modified the memory location
9755   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9756   for (int i=0; i <= lastAddrIndx; ++i)
9757     (*MIB).addOperand(*argOpers[i]);
9758   MIB.addReg(t3);
9759   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9760   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9761                     mInstr->memoperands_end());
9762
9763   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9764   MIB.addReg(X86::EAX);
9765
9766   // insert branch
9767   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9768
9769   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9770   return nextMBB;
9771 }
9772
9773 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9774 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9775 // in the .td file.
9776 MachineBasicBlock *
9777 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9778                             unsigned numArgs, bool memArg) const {
9779   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9780          "Target must have SSE4.2 or AVX features enabled");
9781
9782   DebugLoc dl = MI->getDebugLoc();
9783   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9784   unsigned Opc;
9785   if (!Subtarget->hasAVX()) {
9786     if (memArg)
9787       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9788     else
9789       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9790   } else {
9791     if (memArg)
9792       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9793     else
9794       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9795   }
9796
9797   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9798   for (unsigned i = 0; i < numArgs; ++i) {
9799     MachineOperand &Op = MI->getOperand(i+1);
9800     if (!(Op.isReg() && Op.isImplicit()))
9801       MIB.addOperand(Op);
9802   }
9803   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9804     .addReg(X86::XMM0);
9805
9806   MI->eraseFromParent();
9807   return BB;
9808 }
9809
9810 MachineBasicBlock *
9811 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9812   DebugLoc dl = MI->getDebugLoc();
9813   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9814
9815   // Address into RAX/EAX, other two args into ECX, EDX.
9816   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9817   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9818   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9819   for (int i = 0; i < X86::AddrNumOperands; ++i)
9820     MIB.addOperand(MI->getOperand(i));
9821
9822   unsigned ValOps = X86::AddrNumOperands;
9823   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9824     .addReg(MI->getOperand(ValOps).getReg());
9825   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9826     .addReg(MI->getOperand(ValOps+1).getReg());
9827
9828   // The instruction doesn't actually take any operands though.
9829   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9830
9831   MI->eraseFromParent(); // The pseudo is gone now.
9832   return BB;
9833 }
9834
9835 MachineBasicBlock *
9836 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9837   DebugLoc dl = MI->getDebugLoc();
9838   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9839
9840   // First arg in ECX, the second in EAX.
9841   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9842     .addReg(MI->getOperand(0).getReg());
9843   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9844     .addReg(MI->getOperand(1).getReg());
9845
9846   // The instruction doesn't actually take any operands though.
9847   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9848
9849   MI->eraseFromParent(); // The pseudo is gone now.
9850   return BB;
9851 }
9852
9853 MachineBasicBlock *
9854 X86TargetLowering::EmitVAARG64WithCustomInserter(
9855                    MachineInstr *MI,
9856                    MachineBasicBlock *MBB) const {
9857   // Emit va_arg instruction on X86-64.
9858
9859   // Operands to this pseudo-instruction:
9860   // 0  ) Output        : destination address (reg)
9861   // 1-5) Input         : va_list address (addr, i64mem)
9862   // 6  ) ArgSize       : Size (in bytes) of vararg type
9863   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9864   // 8  ) Align         : Alignment of type
9865   // 9  ) EFLAGS (implicit-def)
9866
9867   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9868   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9869
9870   unsigned DestReg = MI->getOperand(0).getReg();
9871   MachineOperand &Base = MI->getOperand(1);
9872   MachineOperand &Scale = MI->getOperand(2);
9873   MachineOperand &Index = MI->getOperand(3);
9874   MachineOperand &Disp = MI->getOperand(4);
9875   MachineOperand &Segment = MI->getOperand(5);
9876   unsigned ArgSize = MI->getOperand(6).getImm();
9877   unsigned ArgMode = MI->getOperand(7).getImm();
9878   unsigned Align = MI->getOperand(8).getImm();
9879
9880   // Memory Reference
9881   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9882   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9883   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9884
9885   // Machine Information
9886   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9887   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9888   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9889   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9890   DebugLoc DL = MI->getDebugLoc();
9891
9892   // struct va_list {
9893   //   i32   gp_offset
9894   //   i32   fp_offset
9895   //   i64   overflow_area (address)
9896   //   i64   reg_save_area (address)
9897   // }
9898   // sizeof(va_list) = 24
9899   // alignment(va_list) = 8
9900
9901   unsigned TotalNumIntRegs = 6;
9902   unsigned TotalNumXMMRegs = 8;
9903   bool UseGPOffset = (ArgMode == 1);
9904   bool UseFPOffset = (ArgMode == 2);
9905   unsigned MaxOffset = TotalNumIntRegs * 8 +
9906                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9907
9908   /* Align ArgSize to a multiple of 8 */
9909   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9910   bool NeedsAlign = (Align > 8);
9911
9912   MachineBasicBlock *thisMBB = MBB;
9913   MachineBasicBlock *overflowMBB;
9914   MachineBasicBlock *offsetMBB;
9915   MachineBasicBlock *endMBB;
9916
9917   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9918   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9919   unsigned OffsetReg = 0;
9920
9921   if (!UseGPOffset && !UseFPOffset) {
9922     // If we only pull from the overflow region, we don't create a branch.
9923     // We don't need to alter control flow.
9924     OffsetDestReg = 0; // unused
9925     OverflowDestReg = DestReg;
9926
9927     offsetMBB = NULL;
9928     overflowMBB = thisMBB;
9929     endMBB = thisMBB;
9930   } else {
9931     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9932     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9933     // If not, pull from overflow_area. (branch to overflowMBB)
9934     //
9935     //       thisMBB
9936     //         |     .
9937     //         |        .
9938     //     offsetMBB   overflowMBB
9939     //         |        .
9940     //         |     .
9941     //        endMBB
9942
9943     // Registers for the PHI in endMBB
9944     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9945     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9946
9947     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9948     MachineFunction *MF = MBB->getParent();
9949     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9950     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9951     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9952
9953     MachineFunction::iterator MBBIter = MBB;
9954     ++MBBIter;
9955
9956     // Insert the new basic blocks
9957     MF->insert(MBBIter, offsetMBB);
9958     MF->insert(MBBIter, overflowMBB);
9959     MF->insert(MBBIter, endMBB);
9960
9961     // Transfer the remainder of MBB and its successor edges to endMBB.
9962     endMBB->splice(endMBB->begin(), thisMBB,
9963                     llvm::next(MachineBasicBlock::iterator(MI)),
9964                     thisMBB->end());
9965     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9966
9967     // Make offsetMBB and overflowMBB successors of thisMBB
9968     thisMBB->addSuccessor(offsetMBB);
9969     thisMBB->addSuccessor(overflowMBB);
9970
9971     // endMBB is a successor of both offsetMBB and overflowMBB
9972     offsetMBB->addSuccessor(endMBB);
9973     overflowMBB->addSuccessor(endMBB);
9974
9975     // Load the offset value into a register
9976     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9977     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9978       .addOperand(Base)
9979       .addOperand(Scale)
9980       .addOperand(Index)
9981       .addDisp(Disp, UseFPOffset ? 4 : 0)
9982       .addOperand(Segment)
9983       .setMemRefs(MMOBegin, MMOEnd);
9984
9985     // Check if there is enough room left to pull this argument.
9986     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9987       .addReg(OffsetReg)
9988       .addImm(MaxOffset + 8 - ArgSizeA8);
9989
9990     // Branch to "overflowMBB" if offset >= max
9991     // Fall through to "offsetMBB" otherwise
9992     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9993       .addMBB(overflowMBB);
9994   }
9995
9996   // In offsetMBB, emit code to use the reg_save_area.
9997   if (offsetMBB) {
9998     assert(OffsetReg != 0);
9999
10000     // Read the reg_save_area address.
10001     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10002     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10003       .addOperand(Base)
10004       .addOperand(Scale)
10005       .addOperand(Index)
10006       .addDisp(Disp, 16)
10007       .addOperand(Segment)
10008       .setMemRefs(MMOBegin, MMOEnd);
10009
10010     // Zero-extend the offset
10011     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10012       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10013         .addImm(0)
10014         .addReg(OffsetReg)
10015         .addImm(X86::sub_32bit);
10016
10017     // Add the offset to the reg_save_area to get the final address.
10018     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10019       .addReg(OffsetReg64)
10020       .addReg(RegSaveReg);
10021
10022     // Compute the offset for the next argument
10023     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10024     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10025       .addReg(OffsetReg)
10026       .addImm(UseFPOffset ? 16 : 8);
10027
10028     // Store it back into the va_list.
10029     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10030       .addOperand(Base)
10031       .addOperand(Scale)
10032       .addOperand(Index)
10033       .addDisp(Disp, UseFPOffset ? 4 : 0)
10034       .addOperand(Segment)
10035       .addReg(NextOffsetReg)
10036       .setMemRefs(MMOBegin, MMOEnd);
10037
10038     // Jump to endMBB
10039     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10040       .addMBB(endMBB);
10041   }
10042
10043   //
10044   // Emit code to use overflow area
10045   //
10046
10047   // Load the overflow_area address into a register.
10048   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10049   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10050     .addOperand(Base)
10051     .addOperand(Scale)
10052     .addOperand(Index)
10053     .addDisp(Disp, 8)
10054     .addOperand(Segment)
10055     .setMemRefs(MMOBegin, MMOEnd);
10056
10057   // If we need to align it, do so. Otherwise, just copy the address
10058   // to OverflowDestReg.
10059   if (NeedsAlign) {
10060     // Align the overflow address
10061     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10062     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10063
10064     // aligned_addr = (addr + (align-1)) & ~(align-1)
10065     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10066       .addReg(OverflowAddrReg)
10067       .addImm(Align-1);
10068
10069     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10070       .addReg(TmpReg)
10071       .addImm(~(uint64_t)(Align-1));
10072   } else {
10073     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10074       .addReg(OverflowAddrReg);
10075   }
10076
10077   // Compute the next overflow address after this argument.
10078   // (the overflow address should be kept 8-byte aligned)
10079   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10080   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10081     .addReg(OverflowDestReg)
10082     .addImm(ArgSizeA8);
10083
10084   // Store the new overflow address.
10085   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10086     .addOperand(Base)
10087     .addOperand(Scale)
10088     .addOperand(Index)
10089     .addDisp(Disp, 8)
10090     .addOperand(Segment)
10091     .addReg(NextAddrReg)
10092     .setMemRefs(MMOBegin, MMOEnd);
10093
10094   // If we branched, emit the PHI to the front of endMBB.
10095   if (offsetMBB) {
10096     BuildMI(*endMBB, endMBB->begin(), DL,
10097             TII->get(X86::PHI), DestReg)
10098       .addReg(OffsetDestReg).addMBB(offsetMBB)
10099       .addReg(OverflowDestReg).addMBB(overflowMBB);
10100   }
10101
10102   // Erase the pseudo instruction
10103   MI->eraseFromParent();
10104
10105   return endMBB;
10106 }
10107
10108 MachineBasicBlock *
10109 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10110                                                  MachineInstr *MI,
10111                                                  MachineBasicBlock *MBB) const {
10112   // Emit code to save XMM registers to the stack. The ABI says that the
10113   // number of registers to save is given in %al, so it's theoretically
10114   // possible to do an indirect jump trick to avoid saving all of them,
10115   // however this code takes a simpler approach and just executes all
10116   // of the stores if %al is non-zero. It's less code, and it's probably
10117   // easier on the hardware branch predictor, and stores aren't all that
10118   // expensive anyway.
10119
10120   // Create the new basic blocks. One block contains all the XMM stores,
10121   // and one block is the final destination regardless of whether any
10122   // stores were performed.
10123   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10124   MachineFunction *F = MBB->getParent();
10125   MachineFunction::iterator MBBIter = MBB;
10126   ++MBBIter;
10127   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10128   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10129   F->insert(MBBIter, XMMSaveMBB);
10130   F->insert(MBBIter, EndMBB);
10131
10132   // Transfer the remainder of MBB and its successor edges to EndMBB.
10133   EndMBB->splice(EndMBB->begin(), MBB,
10134                  llvm::next(MachineBasicBlock::iterator(MI)),
10135                  MBB->end());
10136   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10137
10138   // The original block will now fall through to the XMM save block.
10139   MBB->addSuccessor(XMMSaveMBB);
10140   // The XMMSaveMBB will fall through to the end block.
10141   XMMSaveMBB->addSuccessor(EndMBB);
10142
10143   // Now add the instructions.
10144   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10145   DebugLoc DL = MI->getDebugLoc();
10146
10147   unsigned CountReg = MI->getOperand(0).getReg();
10148   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10149   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10150
10151   if (!Subtarget->isTargetWin64()) {
10152     // If %al is 0, branch around the XMM save block.
10153     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10154     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10155     MBB->addSuccessor(EndMBB);
10156   }
10157
10158   // In the XMM save block, save all the XMM argument registers.
10159   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10160     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10161     MachineMemOperand *MMO =
10162       F->getMachineMemOperand(
10163           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10164         MachineMemOperand::MOStore,
10165         /*Size=*/16, /*Align=*/16);
10166     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10167       .addFrameIndex(RegSaveFrameIndex)
10168       .addImm(/*Scale=*/1)
10169       .addReg(/*IndexReg=*/0)
10170       .addImm(/*Disp=*/Offset)
10171       .addReg(/*Segment=*/0)
10172       .addReg(MI->getOperand(i).getReg())
10173       .addMemOperand(MMO);
10174   }
10175
10176   MI->eraseFromParent();   // The pseudo instruction is gone now.
10177
10178   return EndMBB;
10179 }
10180
10181 MachineBasicBlock *
10182 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10183                                      MachineBasicBlock *BB) const {
10184   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10185   DebugLoc DL = MI->getDebugLoc();
10186
10187   // To "insert" a SELECT_CC instruction, we actually have to insert the
10188   // diamond control-flow pattern.  The incoming instruction knows the
10189   // destination vreg to set, the condition code register to branch on, the
10190   // true/false values to select between, and a branch opcode to use.
10191   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10192   MachineFunction::iterator It = BB;
10193   ++It;
10194
10195   //  thisMBB:
10196   //  ...
10197   //   TrueVal = ...
10198   //   cmpTY ccX, r1, r2
10199   //   bCC copy1MBB
10200   //   fallthrough --> copy0MBB
10201   MachineBasicBlock *thisMBB = BB;
10202   MachineFunction *F = BB->getParent();
10203   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10204   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10205   F->insert(It, copy0MBB);
10206   F->insert(It, sinkMBB);
10207
10208   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10209   // live into the sink and copy blocks.
10210   const MachineFunction *MF = BB->getParent();
10211   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10212   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10213
10214   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10215     const MachineOperand &MO = MI->getOperand(I);
10216     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10217     unsigned Reg = MO.getReg();
10218     if (Reg != X86::EFLAGS) continue;
10219     copy0MBB->addLiveIn(Reg);
10220     sinkMBB->addLiveIn(Reg);
10221   }
10222
10223   // Transfer the remainder of BB and its successor edges to sinkMBB.
10224   sinkMBB->splice(sinkMBB->begin(), BB,
10225                   llvm::next(MachineBasicBlock::iterator(MI)),
10226                   BB->end());
10227   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10228
10229   // Add the true and fallthrough blocks as its successors.
10230   BB->addSuccessor(copy0MBB);
10231   BB->addSuccessor(sinkMBB);
10232
10233   // Create the conditional branch instruction.
10234   unsigned Opc =
10235     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10236   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10237
10238   //  copy0MBB:
10239   //   %FalseValue = ...
10240   //   # fallthrough to sinkMBB
10241   copy0MBB->addSuccessor(sinkMBB);
10242
10243   //  sinkMBB:
10244   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10245   //  ...
10246   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10247           TII->get(X86::PHI), MI->getOperand(0).getReg())
10248     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10249     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10250
10251   MI->eraseFromParent();   // The pseudo instruction is gone now.
10252   return sinkMBB;
10253 }
10254
10255 MachineBasicBlock *
10256 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10257                                           MachineBasicBlock *BB) const {
10258   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10259   DebugLoc DL = MI->getDebugLoc();
10260
10261   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10262   // non-trivial part is impdef of ESP.
10263   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10264   // mingw-w64.
10265
10266   const char *StackProbeSymbol =
10267       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10268
10269   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10270     .addExternalSymbol(StackProbeSymbol)
10271     .addReg(X86::EAX, RegState::Implicit)
10272     .addReg(X86::ESP, RegState::Implicit)
10273     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10274     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10275     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10276
10277   MI->eraseFromParent();   // The pseudo instruction is gone now.
10278   return BB;
10279 }
10280
10281 MachineBasicBlock *
10282 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10283                                       MachineBasicBlock *BB) const {
10284   // This is pretty easy.  We're taking the value that we received from
10285   // our load from the relocation, sticking it in either RDI (x86-64)
10286   // or EAX and doing an indirect call.  The return value will then
10287   // be in the normal return register.
10288   const X86InstrInfo *TII
10289     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10290   DebugLoc DL = MI->getDebugLoc();
10291   MachineFunction *F = BB->getParent();
10292
10293   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10294   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10295
10296   if (Subtarget->is64Bit()) {
10297     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10298                                       TII->get(X86::MOV64rm), X86::RDI)
10299     .addReg(X86::RIP)
10300     .addImm(0).addReg(0)
10301     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10302                       MI->getOperand(3).getTargetFlags())
10303     .addReg(0);
10304     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10305     addDirectMem(MIB, X86::RDI);
10306   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10307     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10308                                       TII->get(X86::MOV32rm), X86::EAX)
10309     .addReg(0)
10310     .addImm(0).addReg(0)
10311     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10312                       MI->getOperand(3).getTargetFlags())
10313     .addReg(0);
10314     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10315     addDirectMem(MIB, X86::EAX);
10316   } else {
10317     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10318                                       TII->get(X86::MOV32rm), X86::EAX)
10319     .addReg(TII->getGlobalBaseReg(F))
10320     .addImm(0).addReg(0)
10321     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10322                       MI->getOperand(3).getTargetFlags())
10323     .addReg(0);
10324     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10325     addDirectMem(MIB, X86::EAX);
10326   }
10327
10328   MI->eraseFromParent(); // The pseudo instruction is gone now.
10329   return BB;
10330 }
10331
10332 MachineBasicBlock *
10333 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10334                                                MachineBasicBlock *BB) const {
10335   switch (MI->getOpcode()) {
10336   default: assert(false && "Unexpected instr type to insert");
10337   case X86::TAILJMPd64:
10338   case X86::TAILJMPr64:
10339   case X86::TAILJMPm64:
10340     assert(!"TAILJMP64 would not be touched here.");
10341   case X86::TCRETURNdi64:
10342   case X86::TCRETURNri64:
10343   case X86::TCRETURNmi64:
10344     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10345     // On AMD64, additional defs should be added before register allocation.
10346     if (!Subtarget->isTargetWin64()) {
10347       MI->addRegisterDefined(X86::RSI);
10348       MI->addRegisterDefined(X86::RDI);
10349       MI->addRegisterDefined(X86::XMM6);
10350       MI->addRegisterDefined(X86::XMM7);
10351       MI->addRegisterDefined(X86::XMM8);
10352       MI->addRegisterDefined(X86::XMM9);
10353       MI->addRegisterDefined(X86::XMM10);
10354       MI->addRegisterDefined(X86::XMM11);
10355       MI->addRegisterDefined(X86::XMM12);
10356       MI->addRegisterDefined(X86::XMM13);
10357       MI->addRegisterDefined(X86::XMM14);
10358       MI->addRegisterDefined(X86::XMM15);
10359     }
10360     return BB;
10361   case X86::WIN_ALLOCA:
10362     return EmitLoweredWinAlloca(MI, BB);
10363   case X86::TLSCall_32:
10364   case X86::TLSCall_64:
10365     return EmitLoweredTLSCall(MI, BB);
10366   case X86::CMOV_GR8:
10367   case X86::CMOV_FR32:
10368   case X86::CMOV_FR64:
10369   case X86::CMOV_V4F32:
10370   case X86::CMOV_V2F64:
10371   case X86::CMOV_V2I64:
10372   case X86::CMOV_GR16:
10373   case X86::CMOV_GR32:
10374   case X86::CMOV_RFP32:
10375   case X86::CMOV_RFP64:
10376   case X86::CMOV_RFP80:
10377     return EmitLoweredSelect(MI, BB);
10378
10379   case X86::FP32_TO_INT16_IN_MEM:
10380   case X86::FP32_TO_INT32_IN_MEM:
10381   case X86::FP32_TO_INT64_IN_MEM:
10382   case X86::FP64_TO_INT16_IN_MEM:
10383   case X86::FP64_TO_INT32_IN_MEM:
10384   case X86::FP64_TO_INT64_IN_MEM:
10385   case X86::FP80_TO_INT16_IN_MEM:
10386   case X86::FP80_TO_INT32_IN_MEM:
10387   case X86::FP80_TO_INT64_IN_MEM: {
10388     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10389     DebugLoc DL = MI->getDebugLoc();
10390
10391     // Change the floating point control register to use "round towards zero"
10392     // mode when truncating to an integer value.
10393     MachineFunction *F = BB->getParent();
10394     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10395     addFrameReference(BuildMI(*BB, MI, DL,
10396                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10397
10398     // Load the old value of the high byte of the control word...
10399     unsigned OldCW =
10400       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10401     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10402                       CWFrameIdx);
10403
10404     // Set the high part to be round to zero...
10405     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10406       .addImm(0xC7F);
10407
10408     // Reload the modified control word now...
10409     addFrameReference(BuildMI(*BB, MI, DL,
10410                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10411
10412     // Restore the memory image of control word to original value
10413     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10414       .addReg(OldCW);
10415
10416     // Get the X86 opcode to use.
10417     unsigned Opc;
10418     switch (MI->getOpcode()) {
10419     default: llvm_unreachable("illegal opcode!");
10420     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10421     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10422     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10423     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10424     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10425     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10426     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10427     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10428     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10429     }
10430
10431     X86AddressMode AM;
10432     MachineOperand &Op = MI->getOperand(0);
10433     if (Op.isReg()) {
10434       AM.BaseType = X86AddressMode::RegBase;
10435       AM.Base.Reg = Op.getReg();
10436     } else {
10437       AM.BaseType = X86AddressMode::FrameIndexBase;
10438       AM.Base.FrameIndex = Op.getIndex();
10439     }
10440     Op = MI->getOperand(1);
10441     if (Op.isImm())
10442       AM.Scale = Op.getImm();
10443     Op = MI->getOperand(2);
10444     if (Op.isImm())
10445       AM.IndexReg = Op.getImm();
10446     Op = MI->getOperand(3);
10447     if (Op.isGlobal()) {
10448       AM.GV = Op.getGlobal();
10449     } else {
10450       AM.Disp = Op.getImm();
10451     }
10452     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10453                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10454
10455     // Reload the original control word now.
10456     addFrameReference(BuildMI(*BB, MI, DL,
10457                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10458
10459     MI->eraseFromParent();   // The pseudo instruction is gone now.
10460     return BB;
10461   }
10462     // String/text processing lowering.
10463   case X86::PCMPISTRM128REG:
10464   case X86::VPCMPISTRM128REG:
10465     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10466   case X86::PCMPISTRM128MEM:
10467   case X86::VPCMPISTRM128MEM:
10468     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10469   case X86::PCMPESTRM128REG:
10470   case X86::VPCMPESTRM128REG:
10471     return EmitPCMP(MI, BB, 5, false /* in mem */);
10472   case X86::PCMPESTRM128MEM:
10473   case X86::VPCMPESTRM128MEM:
10474     return EmitPCMP(MI, BB, 5, true /* in mem */);
10475
10476     // Thread synchronization.
10477   case X86::MONITOR:
10478     return EmitMonitor(MI, BB);
10479   case X86::MWAIT:
10480     return EmitMwait(MI, BB);
10481
10482     // Atomic Lowering.
10483   case X86::ATOMAND32:
10484     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10485                                                X86::AND32ri, X86::MOV32rm,
10486                                                X86::LCMPXCHG32,
10487                                                X86::NOT32r, X86::EAX,
10488                                                X86::GR32RegisterClass);
10489   case X86::ATOMOR32:
10490     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10491                                                X86::OR32ri, X86::MOV32rm,
10492                                                X86::LCMPXCHG32,
10493                                                X86::NOT32r, X86::EAX,
10494                                                X86::GR32RegisterClass);
10495   case X86::ATOMXOR32:
10496     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10497                                                X86::XOR32ri, X86::MOV32rm,
10498                                                X86::LCMPXCHG32,
10499                                                X86::NOT32r, X86::EAX,
10500                                                X86::GR32RegisterClass);
10501   case X86::ATOMNAND32:
10502     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10503                                                X86::AND32ri, X86::MOV32rm,
10504                                                X86::LCMPXCHG32,
10505                                                X86::NOT32r, X86::EAX,
10506                                                X86::GR32RegisterClass, true);
10507   case X86::ATOMMIN32:
10508     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10509   case X86::ATOMMAX32:
10510     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10511   case X86::ATOMUMIN32:
10512     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10513   case X86::ATOMUMAX32:
10514     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10515
10516   case X86::ATOMAND16:
10517     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10518                                                X86::AND16ri, X86::MOV16rm,
10519                                                X86::LCMPXCHG16,
10520                                                X86::NOT16r, X86::AX,
10521                                                X86::GR16RegisterClass);
10522   case X86::ATOMOR16:
10523     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10524                                                X86::OR16ri, X86::MOV16rm,
10525                                                X86::LCMPXCHG16,
10526                                                X86::NOT16r, X86::AX,
10527                                                X86::GR16RegisterClass);
10528   case X86::ATOMXOR16:
10529     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10530                                                X86::XOR16ri, X86::MOV16rm,
10531                                                X86::LCMPXCHG16,
10532                                                X86::NOT16r, X86::AX,
10533                                                X86::GR16RegisterClass);
10534   case X86::ATOMNAND16:
10535     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10536                                                X86::AND16ri, X86::MOV16rm,
10537                                                X86::LCMPXCHG16,
10538                                                X86::NOT16r, X86::AX,
10539                                                X86::GR16RegisterClass, true);
10540   case X86::ATOMMIN16:
10541     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10542   case X86::ATOMMAX16:
10543     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10544   case X86::ATOMUMIN16:
10545     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10546   case X86::ATOMUMAX16:
10547     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10548
10549   case X86::ATOMAND8:
10550     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10551                                                X86::AND8ri, X86::MOV8rm,
10552                                                X86::LCMPXCHG8,
10553                                                X86::NOT8r, X86::AL,
10554                                                X86::GR8RegisterClass);
10555   case X86::ATOMOR8:
10556     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10557                                                X86::OR8ri, X86::MOV8rm,
10558                                                X86::LCMPXCHG8,
10559                                                X86::NOT8r, X86::AL,
10560                                                X86::GR8RegisterClass);
10561   case X86::ATOMXOR8:
10562     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10563                                                X86::XOR8ri, X86::MOV8rm,
10564                                                X86::LCMPXCHG8,
10565                                                X86::NOT8r, X86::AL,
10566                                                X86::GR8RegisterClass);
10567   case X86::ATOMNAND8:
10568     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10569                                                X86::AND8ri, X86::MOV8rm,
10570                                                X86::LCMPXCHG8,
10571                                                X86::NOT8r, X86::AL,
10572                                                X86::GR8RegisterClass, true);
10573   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10574   // This group is for 64-bit host.
10575   case X86::ATOMAND64:
10576     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10577                                                X86::AND64ri32, X86::MOV64rm,
10578                                                X86::LCMPXCHG64,
10579                                                X86::NOT64r, X86::RAX,
10580                                                X86::GR64RegisterClass);
10581   case X86::ATOMOR64:
10582     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10583                                                X86::OR64ri32, X86::MOV64rm,
10584                                                X86::LCMPXCHG64,
10585                                                X86::NOT64r, X86::RAX,
10586                                                X86::GR64RegisterClass);
10587   case X86::ATOMXOR64:
10588     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10589                                                X86::XOR64ri32, X86::MOV64rm,
10590                                                X86::LCMPXCHG64,
10591                                                X86::NOT64r, X86::RAX,
10592                                                X86::GR64RegisterClass);
10593   case X86::ATOMNAND64:
10594     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10595                                                X86::AND64ri32, X86::MOV64rm,
10596                                                X86::LCMPXCHG64,
10597                                                X86::NOT64r, X86::RAX,
10598                                                X86::GR64RegisterClass, true);
10599   case X86::ATOMMIN64:
10600     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10601   case X86::ATOMMAX64:
10602     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10603   case X86::ATOMUMIN64:
10604     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10605   case X86::ATOMUMAX64:
10606     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10607
10608   // This group does 64-bit operations on a 32-bit host.
10609   case X86::ATOMAND6432:
10610     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10611                                                X86::AND32rr, X86::AND32rr,
10612                                                X86::AND32ri, X86::AND32ri,
10613                                                false);
10614   case X86::ATOMOR6432:
10615     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10616                                                X86::OR32rr, X86::OR32rr,
10617                                                X86::OR32ri, X86::OR32ri,
10618                                                false);
10619   case X86::ATOMXOR6432:
10620     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10621                                                X86::XOR32rr, X86::XOR32rr,
10622                                                X86::XOR32ri, X86::XOR32ri,
10623                                                false);
10624   case X86::ATOMNAND6432:
10625     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10626                                                X86::AND32rr, X86::AND32rr,
10627                                                X86::AND32ri, X86::AND32ri,
10628                                                true);
10629   case X86::ATOMADD6432:
10630     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10631                                                X86::ADD32rr, X86::ADC32rr,
10632                                                X86::ADD32ri, X86::ADC32ri,
10633                                                false);
10634   case X86::ATOMSUB6432:
10635     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10636                                                X86::SUB32rr, X86::SBB32rr,
10637                                                X86::SUB32ri, X86::SBB32ri,
10638                                                false);
10639   case X86::ATOMSWAP6432:
10640     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10641                                                X86::MOV32rr, X86::MOV32rr,
10642                                                X86::MOV32ri, X86::MOV32ri,
10643                                                false);
10644   case X86::VASTART_SAVE_XMM_REGS:
10645     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10646
10647   case X86::VAARG_64:
10648     return EmitVAARG64WithCustomInserter(MI, BB);
10649   }
10650 }
10651
10652 //===----------------------------------------------------------------------===//
10653 //                           X86 Optimization Hooks
10654 //===----------------------------------------------------------------------===//
10655
10656 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10657                                                        const APInt &Mask,
10658                                                        APInt &KnownZero,
10659                                                        APInt &KnownOne,
10660                                                        const SelectionDAG &DAG,
10661                                                        unsigned Depth) const {
10662   unsigned Opc = Op.getOpcode();
10663   assert((Opc >= ISD::BUILTIN_OP_END ||
10664           Opc == ISD::INTRINSIC_WO_CHAIN ||
10665           Opc == ISD::INTRINSIC_W_CHAIN ||
10666           Opc == ISD::INTRINSIC_VOID) &&
10667          "Should use MaskedValueIsZero if you don't know whether Op"
10668          " is a target node!");
10669
10670   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10671   switch (Opc) {
10672   default: break;
10673   case X86ISD::ADD:
10674   case X86ISD::SUB:
10675   case X86ISD::ADC:
10676   case X86ISD::SBB:
10677   case X86ISD::SMUL:
10678   case X86ISD::UMUL:
10679   case X86ISD::INC:
10680   case X86ISD::DEC:
10681   case X86ISD::OR:
10682   case X86ISD::XOR:
10683   case X86ISD::AND:
10684     // These nodes' second result is a boolean.
10685     if (Op.getResNo() == 0)
10686       break;
10687     // Fallthrough
10688   case X86ISD::SETCC:
10689     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10690                                        Mask.getBitWidth() - 1);
10691     break;
10692   }
10693 }
10694
10695 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10696                                                          unsigned Depth) const {
10697   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10698   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10699     return Op.getValueType().getScalarType().getSizeInBits();
10700
10701   // Fallback case.
10702   return 1;
10703 }
10704
10705 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10706 /// node is a GlobalAddress + offset.
10707 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10708                                        const GlobalValue* &GA,
10709                                        int64_t &Offset) const {
10710   if (N->getOpcode() == X86ISD::Wrapper) {
10711     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10712       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10713       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10714       return true;
10715     }
10716   }
10717   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10718 }
10719
10720 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10721 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10722 /// if the load addresses are consecutive, non-overlapping, and in the right
10723 /// order.
10724 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10725                                      TargetLowering::DAGCombinerInfo &DCI) {
10726   DebugLoc dl = N->getDebugLoc();
10727   EVT VT = N->getValueType(0);
10728
10729   if (VT.getSizeInBits() != 128)
10730     return SDValue();
10731
10732   // Don't create instructions with illegal types after legalize types has run.
10733   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10734   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10735     return SDValue();
10736
10737   SmallVector<SDValue, 16> Elts;
10738   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10739     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10740
10741   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10742 }
10743
10744 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10745 /// generation and convert it from being a bunch of shuffles and extracts
10746 /// to a simple store and scalar loads to extract the elements.
10747 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10748                                                 const TargetLowering &TLI) {
10749   SDValue InputVector = N->getOperand(0);
10750
10751   // Only operate on vectors of 4 elements, where the alternative shuffling
10752   // gets to be more expensive.
10753   if (InputVector.getValueType() != MVT::v4i32)
10754     return SDValue();
10755
10756   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10757   // single use which is a sign-extend or zero-extend, and all elements are
10758   // used.
10759   SmallVector<SDNode *, 4> Uses;
10760   unsigned ExtractedElements = 0;
10761   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10762        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10763     if (UI.getUse().getResNo() != InputVector.getResNo())
10764       return SDValue();
10765
10766     SDNode *Extract = *UI;
10767     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10768       return SDValue();
10769
10770     if (Extract->getValueType(0) != MVT::i32)
10771       return SDValue();
10772     if (!Extract->hasOneUse())
10773       return SDValue();
10774     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10775         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10776       return SDValue();
10777     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10778       return SDValue();
10779
10780     // Record which element was extracted.
10781     ExtractedElements |=
10782       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10783
10784     Uses.push_back(Extract);
10785   }
10786
10787   // If not all the elements were used, this may not be worthwhile.
10788   if (ExtractedElements != 15)
10789     return SDValue();
10790
10791   // Ok, we've now decided to do the transformation.
10792   DebugLoc dl = InputVector.getDebugLoc();
10793
10794   // Store the value to a temporary stack slot.
10795   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10796   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10797                             MachinePointerInfo(), false, false, 0);
10798
10799   // Replace each use (extract) with a load of the appropriate element.
10800   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10801        UE = Uses.end(); UI != UE; ++UI) {
10802     SDNode *Extract = *UI;
10803
10804     // Compute the element's address.
10805     SDValue Idx = Extract->getOperand(1);
10806     unsigned EltSize =
10807         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10808     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10809     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10810
10811     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10812                                      StackPtr, OffsetVal);
10813
10814     // Load the scalar.
10815     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10816                                      ScalarAddr, MachinePointerInfo(),
10817                                      false, false, 0);
10818
10819     // Replace the exact with the load.
10820     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10821   }
10822
10823   // The replacement was made in place; don't return anything.
10824   return SDValue();
10825 }
10826
10827 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10828 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10829                                     const X86Subtarget *Subtarget) {
10830   DebugLoc DL = N->getDebugLoc();
10831   SDValue Cond = N->getOperand(0);
10832   // Get the LHS/RHS of the select.
10833   SDValue LHS = N->getOperand(1);
10834   SDValue RHS = N->getOperand(2);
10835
10836   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10837   // instructions match the semantics of the common C idiom x<y?x:y but not
10838   // x<=y?x:y, because of how they handle negative zero (which can be
10839   // ignored in unsafe-math mode).
10840   if (Subtarget->hasSSE2() &&
10841       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10842       Cond.getOpcode() == ISD::SETCC) {
10843     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10844
10845     unsigned Opcode = 0;
10846     // Check for x CC y ? x : y.
10847     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10848         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10849       switch (CC) {
10850       default: break;
10851       case ISD::SETULT:
10852         // Converting this to a min would handle NaNs incorrectly, and swapping
10853         // the operands would cause it to handle comparisons between positive
10854         // and negative zero incorrectly.
10855         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10856           if (!UnsafeFPMath &&
10857               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10858             break;
10859           std::swap(LHS, RHS);
10860         }
10861         Opcode = X86ISD::FMIN;
10862         break;
10863       case ISD::SETOLE:
10864         // Converting this to a min would handle comparisons between positive
10865         // and negative zero incorrectly.
10866         if (!UnsafeFPMath &&
10867             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10868           break;
10869         Opcode = X86ISD::FMIN;
10870         break;
10871       case ISD::SETULE:
10872         // Converting this to a min would handle both negative zeros and NaNs
10873         // incorrectly, but we can swap the operands to fix both.
10874         std::swap(LHS, RHS);
10875       case ISD::SETOLT:
10876       case ISD::SETLT:
10877       case ISD::SETLE:
10878         Opcode = X86ISD::FMIN;
10879         break;
10880
10881       case ISD::SETOGE:
10882         // Converting this to a max would handle comparisons between positive
10883         // and negative zero incorrectly.
10884         if (!UnsafeFPMath &&
10885             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10886           break;
10887         Opcode = X86ISD::FMAX;
10888         break;
10889       case ISD::SETUGT:
10890         // Converting this to a max would handle NaNs incorrectly, and swapping
10891         // the operands would cause it to handle comparisons between positive
10892         // and negative zero incorrectly.
10893         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10894           if (!UnsafeFPMath &&
10895               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10896             break;
10897           std::swap(LHS, RHS);
10898         }
10899         Opcode = X86ISD::FMAX;
10900         break;
10901       case ISD::SETUGE:
10902         // Converting this to a max would handle both negative zeros and NaNs
10903         // incorrectly, but we can swap the operands to fix both.
10904         std::swap(LHS, RHS);
10905       case ISD::SETOGT:
10906       case ISD::SETGT:
10907       case ISD::SETGE:
10908         Opcode = X86ISD::FMAX;
10909         break;
10910       }
10911     // Check for x CC y ? y : x -- a min/max with reversed arms.
10912     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10913                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10914       switch (CC) {
10915       default: break;
10916       case ISD::SETOGE:
10917         // Converting this to a min would handle comparisons between positive
10918         // and negative zero incorrectly, and swapping the operands would
10919         // cause it to handle NaNs incorrectly.
10920         if (!UnsafeFPMath &&
10921             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10922           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10923             break;
10924           std::swap(LHS, RHS);
10925         }
10926         Opcode = X86ISD::FMIN;
10927         break;
10928       case ISD::SETUGT:
10929         // Converting this to a min would handle NaNs incorrectly.
10930         if (!UnsafeFPMath &&
10931             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10932           break;
10933         Opcode = X86ISD::FMIN;
10934         break;
10935       case ISD::SETUGE:
10936         // Converting this to a min would handle both negative zeros and NaNs
10937         // incorrectly, but we can swap the operands to fix both.
10938         std::swap(LHS, RHS);
10939       case ISD::SETOGT:
10940       case ISD::SETGT:
10941       case ISD::SETGE:
10942         Opcode = X86ISD::FMIN;
10943         break;
10944
10945       case ISD::SETULT:
10946         // Converting this to a max would handle NaNs incorrectly.
10947         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10948           break;
10949         Opcode = X86ISD::FMAX;
10950         break;
10951       case ISD::SETOLE:
10952         // Converting this to a max would handle comparisons between positive
10953         // and negative zero incorrectly, and swapping the operands would
10954         // cause it to handle NaNs incorrectly.
10955         if (!UnsafeFPMath &&
10956             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10957           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10958             break;
10959           std::swap(LHS, RHS);
10960         }
10961         Opcode = X86ISD::FMAX;
10962         break;
10963       case ISD::SETULE:
10964         // Converting this to a max would handle both negative zeros and NaNs
10965         // incorrectly, but we can swap the operands to fix both.
10966         std::swap(LHS, RHS);
10967       case ISD::SETOLT:
10968       case ISD::SETLT:
10969       case ISD::SETLE:
10970         Opcode = X86ISD::FMAX;
10971         break;
10972       }
10973     }
10974
10975     if (Opcode)
10976       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10977   }
10978
10979   // If this is a select between two integer constants, try to do some
10980   // optimizations.
10981   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10982     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10983       // Don't do this for crazy integer types.
10984       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10985         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10986         // so that TrueC (the true value) is larger than FalseC.
10987         bool NeedsCondInvert = false;
10988
10989         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10990             // Efficiently invertible.
10991             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10992              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10993               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10994           NeedsCondInvert = true;
10995           std::swap(TrueC, FalseC);
10996         }
10997
10998         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10999         if (FalseC->getAPIntValue() == 0 &&
11000             TrueC->getAPIntValue().isPowerOf2()) {
11001           if (NeedsCondInvert) // Invert the condition if needed.
11002             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11003                                DAG.getConstant(1, Cond.getValueType()));
11004
11005           // Zero extend the condition if needed.
11006           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11007
11008           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11009           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11010                              DAG.getConstant(ShAmt, MVT::i8));
11011         }
11012
11013         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11014         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11015           if (NeedsCondInvert) // Invert the condition if needed.
11016             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11017                                DAG.getConstant(1, Cond.getValueType()));
11018
11019           // Zero extend the condition if needed.
11020           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11021                              FalseC->getValueType(0), Cond);
11022           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11023                              SDValue(FalseC, 0));
11024         }
11025
11026         // Optimize cases that will turn into an LEA instruction.  This requires
11027         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11028         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11029           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11030           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11031
11032           bool isFastMultiplier = false;
11033           if (Diff < 10) {
11034             switch ((unsigned char)Diff) {
11035               default: break;
11036               case 1:  // result = add base, cond
11037               case 2:  // result = lea base(    , cond*2)
11038               case 3:  // result = lea base(cond, cond*2)
11039               case 4:  // result = lea base(    , cond*4)
11040               case 5:  // result = lea base(cond, cond*4)
11041               case 8:  // result = lea base(    , cond*8)
11042               case 9:  // result = lea base(cond, cond*8)
11043                 isFastMultiplier = true;
11044                 break;
11045             }
11046           }
11047
11048           if (isFastMultiplier) {
11049             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11050             if (NeedsCondInvert) // Invert the condition if needed.
11051               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11052                                  DAG.getConstant(1, Cond.getValueType()));
11053
11054             // Zero extend the condition if needed.
11055             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11056                                Cond);
11057             // Scale the condition by the difference.
11058             if (Diff != 1)
11059               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11060                                  DAG.getConstant(Diff, Cond.getValueType()));
11061
11062             // Add the base if non-zero.
11063             if (FalseC->getAPIntValue() != 0)
11064               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11065                                  SDValue(FalseC, 0));
11066             return Cond;
11067           }
11068         }
11069       }
11070   }
11071
11072   return SDValue();
11073 }
11074
11075 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11076 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11077                                   TargetLowering::DAGCombinerInfo &DCI) {
11078   DebugLoc DL = N->getDebugLoc();
11079
11080   // If the flag operand isn't dead, don't touch this CMOV.
11081   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11082     return SDValue();
11083
11084   // If this is a select between two integer constants, try to do some
11085   // optimizations.  Note that the operands are ordered the opposite of SELECT
11086   // operands.
11087   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11088     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11089       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11090       // larger than FalseC (the false value).
11091       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11092
11093       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11094         CC = X86::GetOppositeBranchCondition(CC);
11095         std::swap(TrueC, FalseC);
11096       }
11097
11098       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11099       // This is efficient for any integer data type (including i8/i16) and
11100       // shift amount.
11101       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11102         SDValue Cond = N->getOperand(3);
11103         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11104                            DAG.getConstant(CC, MVT::i8), Cond);
11105
11106         // Zero extend the condition if needed.
11107         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11108
11109         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11110         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11111                            DAG.getConstant(ShAmt, MVT::i8));
11112         if (N->getNumValues() == 2)  // Dead flag value?
11113           return DCI.CombineTo(N, Cond, SDValue());
11114         return Cond;
11115       }
11116
11117       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11118       // for any integer data type, including i8/i16.
11119       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11120         SDValue Cond = N->getOperand(3);
11121         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11122                            DAG.getConstant(CC, MVT::i8), Cond);
11123
11124         // Zero extend the condition if needed.
11125         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11126                            FalseC->getValueType(0), Cond);
11127         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11128                            SDValue(FalseC, 0));
11129
11130         if (N->getNumValues() == 2)  // Dead flag value?
11131           return DCI.CombineTo(N, Cond, SDValue());
11132         return Cond;
11133       }
11134
11135       // Optimize cases that will turn into an LEA instruction.  This requires
11136       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11137       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11138         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11139         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11140
11141         bool isFastMultiplier = false;
11142         if (Diff < 10) {
11143           switch ((unsigned char)Diff) {
11144           default: break;
11145           case 1:  // result = add base, cond
11146           case 2:  // result = lea base(    , cond*2)
11147           case 3:  // result = lea base(cond, cond*2)
11148           case 4:  // result = lea base(    , cond*4)
11149           case 5:  // result = lea base(cond, cond*4)
11150           case 8:  // result = lea base(    , cond*8)
11151           case 9:  // result = lea base(cond, cond*8)
11152             isFastMultiplier = true;
11153             break;
11154           }
11155         }
11156
11157         if (isFastMultiplier) {
11158           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11159           SDValue Cond = N->getOperand(3);
11160           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11161                              DAG.getConstant(CC, MVT::i8), Cond);
11162           // Zero extend the condition if needed.
11163           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11164                              Cond);
11165           // Scale the condition by the difference.
11166           if (Diff != 1)
11167             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11168                                DAG.getConstant(Diff, Cond.getValueType()));
11169
11170           // Add the base if non-zero.
11171           if (FalseC->getAPIntValue() != 0)
11172             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11173                                SDValue(FalseC, 0));
11174           if (N->getNumValues() == 2)  // Dead flag value?
11175             return DCI.CombineTo(N, Cond, SDValue());
11176           return Cond;
11177         }
11178       }
11179     }
11180   }
11181   return SDValue();
11182 }
11183
11184
11185 /// PerformMulCombine - Optimize a single multiply with constant into two
11186 /// in order to implement it with two cheaper instructions, e.g.
11187 /// LEA + SHL, LEA + LEA.
11188 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11189                                  TargetLowering::DAGCombinerInfo &DCI) {
11190   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11191     return SDValue();
11192
11193   EVT VT = N->getValueType(0);
11194   if (VT != MVT::i64)
11195     return SDValue();
11196
11197   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11198   if (!C)
11199     return SDValue();
11200   uint64_t MulAmt = C->getZExtValue();
11201   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11202     return SDValue();
11203
11204   uint64_t MulAmt1 = 0;
11205   uint64_t MulAmt2 = 0;
11206   if ((MulAmt % 9) == 0) {
11207     MulAmt1 = 9;
11208     MulAmt2 = MulAmt / 9;
11209   } else if ((MulAmt % 5) == 0) {
11210     MulAmt1 = 5;
11211     MulAmt2 = MulAmt / 5;
11212   } else if ((MulAmt % 3) == 0) {
11213     MulAmt1 = 3;
11214     MulAmt2 = MulAmt / 3;
11215   }
11216   if (MulAmt2 &&
11217       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11218     DebugLoc DL = N->getDebugLoc();
11219
11220     if (isPowerOf2_64(MulAmt2) &&
11221         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11222       // If second multiplifer is pow2, issue it first. We want the multiply by
11223       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11224       // is an add.
11225       std::swap(MulAmt1, MulAmt2);
11226
11227     SDValue NewMul;
11228     if (isPowerOf2_64(MulAmt1))
11229       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11230                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11231     else
11232       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11233                            DAG.getConstant(MulAmt1, VT));
11234
11235     if (isPowerOf2_64(MulAmt2))
11236       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11237                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11238     else
11239       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11240                            DAG.getConstant(MulAmt2, VT));
11241
11242     // Do not add new nodes to DAG combiner worklist.
11243     DCI.CombineTo(N, NewMul, false);
11244   }
11245   return SDValue();
11246 }
11247
11248 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11249   SDValue N0 = N->getOperand(0);
11250   SDValue N1 = N->getOperand(1);
11251   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11252   EVT VT = N0.getValueType();
11253
11254   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11255   // since the result of setcc_c is all zero's or all ones.
11256   if (N1C && N0.getOpcode() == ISD::AND &&
11257       N0.getOperand(1).getOpcode() == ISD::Constant) {
11258     SDValue N00 = N0.getOperand(0);
11259     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11260         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11261           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11262          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11263       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11264       APInt ShAmt = N1C->getAPIntValue();
11265       Mask = Mask.shl(ShAmt);
11266       if (Mask != 0)
11267         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11268                            N00, DAG.getConstant(Mask, VT));
11269     }
11270   }
11271
11272   return SDValue();
11273 }
11274
11275 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11276 ///                       when possible.
11277 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11278                                    const X86Subtarget *Subtarget) {
11279   EVT VT = N->getValueType(0);
11280   if (!VT.isVector() && VT.isInteger() &&
11281       N->getOpcode() == ISD::SHL)
11282     return PerformSHLCombine(N, DAG);
11283
11284   // On X86 with SSE2 support, we can transform this to a vector shift if
11285   // all elements are shifted by the same amount.  We can't do this in legalize
11286   // because the a constant vector is typically transformed to a constant pool
11287   // so we have no knowledge of the shift amount.
11288   if (!Subtarget->hasSSE2())
11289     return SDValue();
11290
11291   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11292     return SDValue();
11293
11294   SDValue ShAmtOp = N->getOperand(1);
11295   EVT EltVT = VT.getVectorElementType();
11296   DebugLoc DL = N->getDebugLoc();
11297   SDValue BaseShAmt = SDValue();
11298   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11299     unsigned NumElts = VT.getVectorNumElements();
11300     unsigned i = 0;
11301     for (; i != NumElts; ++i) {
11302       SDValue Arg = ShAmtOp.getOperand(i);
11303       if (Arg.getOpcode() == ISD::UNDEF) continue;
11304       BaseShAmt = Arg;
11305       break;
11306     }
11307     for (; i != NumElts; ++i) {
11308       SDValue Arg = ShAmtOp.getOperand(i);
11309       if (Arg.getOpcode() == ISD::UNDEF) continue;
11310       if (Arg != BaseShAmt) {
11311         return SDValue();
11312       }
11313     }
11314   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11315              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11316     SDValue InVec = ShAmtOp.getOperand(0);
11317     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11318       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11319       unsigned i = 0;
11320       for (; i != NumElts; ++i) {
11321         SDValue Arg = InVec.getOperand(i);
11322         if (Arg.getOpcode() == ISD::UNDEF) continue;
11323         BaseShAmt = Arg;
11324         break;
11325       }
11326     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11327        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11328          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11329          if (C->getZExtValue() == SplatIdx)
11330            BaseShAmt = InVec.getOperand(1);
11331        }
11332     }
11333     if (BaseShAmt.getNode() == 0)
11334       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11335                               DAG.getIntPtrConstant(0));
11336   } else
11337     return SDValue();
11338
11339   // The shift amount is an i32.
11340   if (EltVT.bitsGT(MVT::i32))
11341     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11342   else if (EltVT.bitsLT(MVT::i32))
11343     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11344
11345   // The shift amount is identical so we can do a vector shift.
11346   SDValue  ValOp = N->getOperand(0);
11347   switch (N->getOpcode()) {
11348   default:
11349     llvm_unreachable("Unknown shift opcode!");
11350     break;
11351   case ISD::SHL:
11352     if (VT == MVT::v2i64)
11353       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11354                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11355                          ValOp, BaseShAmt);
11356     if (VT == MVT::v4i32)
11357       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11358                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11359                          ValOp, BaseShAmt);
11360     if (VT == MVT::v8i16)
11361       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11362                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11363                          ValOp, BaseShAmt);
11364     break;
11365   case ISD::SRA:
11366     if (VT == MVT::v4i32)
11367       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11368                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11369                          ValOp, BaseShAmt);
11370     if (VT == MVT::v8i16)
11371       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11372                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11373                          ValOp, BaseShAmt);
11374     break;
11375   case ISD::SRL:
11376     if (VT == MVT::v2i64)
11377       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11378                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11379                          ValOp, BaseShAmt);
11380     if (VT == MVT::v4i32)
11381       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11382                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11383                          ValOp, BaseShAmt);
11384     if (VT ==  MVT::v8i16)
11385       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11386                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11387                          ValOp, BaseShAmt);
11388     break;
11389   }
11390   return SDValue();
11391 }
11392
11393
11394 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11395                                  TargetLowering::DAGCombinerInfo &DCI,
11396                                  const X86Subtarget *Subtarget) {
11397   if (DCI.isBeforeLegalizeOps())
11398     return SDValue();
11399
11400   // Want to form PANDN nodes, in the hopes of then easily combining them with
11401   // OR and AND nodes to form PBLEND/PSIGN.
11402   EVT VT = N->getValueType(0);
11403   if (VT != MVT::v2i64)
11404     return SDValue();
11405
11406   SDValue N0 = N->getOperand(0);
11407   SDValue N1 = N->getOperand(1);
11408   DebugLoc DL = N->getDebugLoc();
11409
11410   // Check LHS for vnot
11411   if (N0.getOpcode() == ISD::XOR &&
11412       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11413     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11414
11415   // Check RHS for vnot
11416   if (N1.getOpcode() == ISD::XOR &&
11417       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11418     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11419
11420   return SDValue();
11421 }
11422
11423 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11424                                 TargetLowering::DAGCombinerInfo &DCI,
11425                                 const X86Subtarget *Subtarget) {
11426   if (DCI.isBeforeLegalizeOps())
11427     return SDValue();
11428
11429   EVT VT = N->getValueType(0);
11430   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11431     return SDValue();
11432
11433   SDValue N0 = N->getOperand(0);
11434   SDValue N1 = N->getOperand(1);
11435
11436   // look for psign/blend
11437   if (Subtarget->hasSSSE3()) {
11438     if (VT == MVT::v2i64) {
11439       // Canonicalize pandn to RHS
11440       if (N0.getOpcode() == X86ISD::PANDN)
11441         std::swap(N0, N1);
11442       // or (and (m, x), (pandn m, y))
11443       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11444         SDValue Mask = N1.getOperand(0);
11445         SDValue X    = N1.getOperand(1);
11446         SDValue Y;
11447         if (N0.getOperand(0) == Mask)
11448           Y = N0.getOperand(1);
11449         if (N0.getOperand(1) == Mask)
11450           Y = N0.getOperand(0);
11451
11452         // Check to see if the mask appeared in both the AND and PANDN and
11453         if (!Y.getNode())
11454           return SDValue();
11455
11456         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11457         if (Mask.getOpcode() != ISD::BITCAST ||
11458             X.getOpcode() != ISD::BITCAST ||
11459             Y.getOpcode() != ISD::BITCAST)
11460           return SDValue();
11461
11462         // Look through mask bitcast.
11463         Mask = Mask.getOperand(0);
11464         EVT MaskVT = Mask.getValueType();
11465
11466         // Validate that the Mask operand is a vector sra node.  The sra node
11467         // will be an intrinsic.
11468         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11469           return SDValue();
11470
11471         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11472         // there is no psrai.b
11473         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11474         case Intrinsic::x86_sse2_psrai_w:
11475         case Intrinsic::x86_sse2_psrai_d:
11476           break;
11477         default: return SDValue();
11478         }
11479
11480         // Check that the SRA is all signbits.
11481         SDValue SraC = Mask.getOperand(2);
11482         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11483         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11484         if ((SraAmt + 1) != EltBits)
11485           return SDValue();
11486
11487         DebugLoc DL = N->getDebugLoc();
11488
11489         // Now we know we at least have a plendvb with the mask val.  See if
11490         // we can form a psignb/w/d.
11491         // psign = x.type == y.type == mask.type && y = sub(0, x);
11492         X = X.getOperand(0);
11493         Y = Y.getOperand(0);
11494         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11495             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11496             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11497           unsigned Opc = 0;
11498           switch (EltBits) {
11499           case 8: Opc = X86ISD::PSIGNB; break;
11500           case 16: Opc = X86ISD::PSIGNW; break;
11501           case 32: Opc = X86ISD::PSIGND; break;
11502           default: break;
11503           }
11504           if (Opc) {
11505             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11506             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11507           }
11508         }
11509         // PBLENDVB only available on SSE 4.1
11510         if (!Subtarget->hasSSE41())
11511           return SDValue();
11512
11513         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11514         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11515         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11516         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11517         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11518       }
11519     }
11520   }
11521
11522   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11523   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11524     std::swap(N0, N1);
11525   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11526     return SDValue();
11527   if (!N0.hasOneUse() || !N1.hasOneUse())
11528     return SDValue();
11529
11530   SDValue ShAmt0 = N0.getOperand(1);
11531   if (ShAmt0.getValueType() != MVT::i8)
11532     return SDValue();
11533   SDValue ShAmt1 = N1.getOperand(1);
11534   if (ShAmt1.getValueType() != MVT::i8)
11535     return SDValue();
11536   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11537     ShAmt0 = ShAmt0.getOperand(0);
11538   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11539     ShAmt1 = ShAmt1.getOperand(0);
11540
11541   DebugLoc DL = N->getDebugLoc();
11542   unsigned Opc = X86ISD::SHLD;
11543   SDValue Op0 = N0.getOperand(0);
11544   SDValue Op1 = N1.getOperand(0);
11545   if (ShAmt0.getOpcode() == ISD::SUB) {
11546     Opc = X86ISD::SHRD;
11547     std::swap(Op0, Op1);
11548     std::swap(ShAmt0, ShAmt1);
11549   }
11550
11551   unsigned Bits = VT.getSizeInBits();
11552   if (ShAmt1.getOpcode() == ISD::SUB) {
11553     SDValue Sum = ShAmt1.getOperand(0);
11554     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11555       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11556       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11557         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11558       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11559         return DAG.getNode(Opc, DL, VT,
11560                            Op0, Op1,
11561                            DAG.getNode(ISD::TRUNCATE, DL,
11562                                        MVT::i8, ShAmt0));
11563     }
11564   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11565     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11566     if (ShAmt0C &&
11567         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11568       return DAG.getNode(Opc, DL, VT,
11569                          N0.getOperand(0), N1.getOperand(0),
11570                          DAG.getNode(ISD::TRUNCATE, DL,
11571                                        MVT::i8, ShAmt0));
11572   }
11573
11574   return SDValue();
11575 }
11576
11577 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11578 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11579                                    const X86Subtarget *Subtarget) {
11580   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11581   // the FP state in cases where an emms may be missing.
11582   // A preferable solution to the general problem is to figure out the right
11583   // places to insert EMMS.  This qualifies as a quick hack.
11584
11585   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11586   StoreSDNode *St = cast<StoreSDNode>(N);
11587   EVT VT = St->getValue().getValueType();
11588   if (VT.getSizeInBits() != 64)
11589     return SDValue();
11590
11591   const Function *F = DAG.getMachineFunction().getFunction();
11592   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11593   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11594     && Subtarget->hasSSE2();
11595   if ((VT.isVector() ||
11596        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11597       isa<LoadSDNode>(St->getValue()) &&
11598       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11599       St->getChain().hasOneUse() && !St->isVolatile()) {
11600     SDNode* LdVal = St->getValue().getNode();
11601     LoadSDNode *Ld = 0;
11602     int TokenFactorIndex = -1;
11603     SmallVector<SDValue, 8> Ops;
11604     SDNode* ChainVal = St->getChain().getNode();
11605     // Must be a store of a load.  We currently handle two cases:  the load
11606     // is a direct child, and it's under an intervening TokenFactor.  It is
11607     // possible to dig deeper under nested TokenFactors.
11608     if (ChainVal == LdVal)
11609       Ld = cast<LoadSDNode>(St->getChain());
11610     else if (St->getValue().hasOneUse() &&
11611              ChainVal->getOpcode() == ISD::TokenFactor) {
11612       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11613         if (ChainVal->getOperand(i).getNode() == LdVal) {
11614           TokenFactorIndex = i;
11615           Ld = cast<LoadSDNode>(St->getValue());
11616         } else
11617           Ops.push_back(ChainVal->getOperand(i));
11618       }
11619     }
11620
11621     if (!Ld || !ISD::isNormalLoad(Ld))
11622       return SDValue();
11623
11624     // If this is not the MMX case, i.e. we are just turning i64 load/store
11625     // into f64 load/store, avoid the transformation if there are multiple
11626     // uses of the loaded value.
11627     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11628       return SDValue();
11629
11630     DebugLoc LdDL = Ld->getDebugLoc();
11631     DebugLoc StDL = N->getDebugLoc();
11632     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11633     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11634     // pair instead.
11635     if (Subtarget->is64Bit() || F64IsLegal) {
11636       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11637       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11638                                   Ld->getPointerInfo(), Ld->isVolatile(),
11639                                   Ld->isNonTemporal(), Ld->getAlignment());
11640       SDValue NewChain = NewLd.getValue(1);
11641       if (TokenFactorIndex != -1) {
11642         Ops.push_back(NewChain);
11643         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11644                                Ops.size());
11645       }
11646       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11647                           St->getPointerInfo(),
11648                           St->isVolatile(), St->isNonTemporal(),
11649                           St->getAlignment());
11650     }
11651
11652     // Otherwise, lower to two pairs of 32-bit loads / stores.
11653     SDValue LoAddr = Ld->getBasePtr();
11654     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11655                                  DAG.getConstant(4, MVT::i32));
11656
11657     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11658                                Ld->getPointerInfo(),
11659                                Ld->isVolatile(), Ld->isNonTemporal(),
11660                                Ld->getAlignment());
11661     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11662                                Ld->getPointerInfo().getWithOffset(4),
11663                                Ld->isVolatile(), Ld->isNonTemporal(),
11664                                MinAlign(Ld->getAlignment(), 4));
11665
11666     SDValue NewChain = LoLd.getValue(1);
11667     if (TokenFactorIndex != -1) {
11668       Ops.push_back(LoLd);
11669       Ops.push_back(HiLd);
11670       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11671                              Ops.size());
11672     }
11673
11674     LoAddr = St->getBasePtr();
11675     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11676                          DAG.getConstant(4, MVT::i32));
11677
11678     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11679                                 St->getPointerInfo(),
11680                                 St->isVolatile(), St->isNonTemporal(),
11681                                 St->getAlignment());
11682     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11683                                 St->getPointerInfo().getWithOffset(4),
11684                                 St->isVolatile(),
11685                                 St->isNonTemporal(),
11686                                 MinAlign(St->getAlignment(), 4));
11687     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11688   }
11689   return SDValue();
11690 }
11691
11692 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11693 /// X86ISD::FXOR nodes.
11694 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11695   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11696   // F[X]OR(0.0, x) -> x
11697   // F[X]OR(x, 0.0) -> x
11698   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11699     if (C->getValueAPF().isPosZero())
11700       return N->getOperand(1);
11701   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11702     if (C->getValueAPF().isPosZero())
11703       return N->getOperand(0);
11704   return SDValue();
11705 }
11706
11707 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11708 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11709   // FAND(0.0, x) -> 0.0
11710   // FAND(x, 0.0) -> 0.0
11711   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11712     if (C->getValueAPF().isPosZero())
11713       return N->getOperand(0);
11714   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11715     if (C->getValueAPF().isPosZero())
11716       return N->getOperand(1);
11717   return SDValue();
11718 }
11719
11720 static SDValue PerformBTCombine(SDNode *N,
11721                                 SelectionDAG &DAG,
11722                                 TargetLowering::DAGCombinerInfo &DCI) {
11723   // BT ignores high bits in the bit index operand.
11724   SDValue Op1 = N->getOperand(1);
11725   if (Op1.hasOneUse()) {
11726     unsigned BitWidth = Op1.getValueSizeInBits();
11727     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11728     APInt KnownZero, KnownOne;
11729     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11730                                           !DCI.isBeforeLegalizeOps());
11731     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11732     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11733         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11734       DCI.CommitTargetLoweringOpt(TLO);
11735   }
11736   return SDValue();
11737 }
11738
11739 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11740   SDValue Op = N->getOperand(0);
11741   if (Op.getOpcode() == ISD::BITCAST)
11742     Op = Op.getOperand(0);
11743   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11744   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11745       VT.getVectorElementType().getSizeInBits() ==
11746       OpVT.getVectorElementType().getSizeInBits()) {
11747     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11748   }
11749   return SDValue();
11750 }
11751
11752 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11753   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11754   //           (and (i32 x86isd::setcc_carry), 1)
11755   // This eliminates the zext. This transformation is necessary because
11756   // ISD::SETCC is always legalized to i8.
11757   DebugLoc dl = N->getDebugLoc();
11758   SDValue N0 = N->getOperand(0);
11759   EVT VT = N->getValueType(0);
11760   if (N0.getOpcode() == ISD::AND &&
11761       N0.hasOneUse() &&
11762       N0.getOperand(0).hasOneUse()) {
11763     SDValue N00 = N0.getOperand(0);
11764     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11765       return SDValue();
11766     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11767     if (!C || C->getZExtValue() != 1)
11768       return SDValue();
11769     return DAG.getNode(ISD::AND, dl, VT,
11770                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11771                                    N00.getOperand(0), N00.getOperand(1)),
11772                        DAG.getConstant(1, VT));
11773   }
11774
11775   return SDValue();
11776 }
11777
11778 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11779 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11780   unsigned X86CC = N->getConstantOperandVal(0);
11781   SDValue EFLAG = N->getOperand(1);
11782   DebugLoc DL = N->getDebugLoc();
11783
11784   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11785   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11786   // cases.
11787   if (X86CC == X86::COND_B)
11788     return DAG.getNode(ISD::AND, DL, MVT::i8,
11789                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11790                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11791                        DAG.getConstant(1, MVT::i8));
11792
11793   return SDValue();
11794 }
11795
11796 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11797 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11798                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11799   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11800   // the result is either zero or one (depending on the input carry bit).
11801   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11802   if (X86::isZeroNode(N->getOperand(0)) &&
11803       X86::isZeroNode(N->getOperand(1)) &&
11804       // We don't have a good way to replace an EFLAGS use, so only do this when
11805       // dead right now.
11806       SDValue(N, 1).use_empty()) {
11807     DebugLoc DL = N->getDebugLoc();
11808     EVT VT = N->getValueType(0);
11809     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11810     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11811                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11812                                            DAG.getConstant(X86::COND_B,MVT::i8),
11813                                            N->getOperand(2)),
11814                                DAG.getConstant(1, VT));
11815     return DCI.CombineTo(N, Res1, CarryOut);
11816   }
11817
11818   return SDValue();
11819 }
11820
11821 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11822 //      (add Y, (setne X, 0)) -> sbb -1, Y
11823 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11824 //      (sub (setne X, 0), Y) -> adc -1, Y
11825 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11826   DebugLoc DL = N->getDebugLoc();
11827
11828   // Look through ZExts.
11829   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11830   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11831     return SDValue();
11832
11833   SDValue SetCC = Ext.getOperand(0);
11834   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11835     return SDValue();
11836
11837   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11838   if (CC != X86::COND_E && CC != X86::COND_NE)
11839     return SDValue();
11840
11841   SDValue Cmp = SetCC.getOperand(1);
11842   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11843       !X86::isZeroNode(Cmp.getOperand(1)) ||
11844       !Cmp.getOperand(0).getValueType().isInteger())
11845     return SDValue();
11846
11847   SDValue CmpOp0 = Cmp.getOperand(0);
11848   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11849                                DAG.getConstant(1, CmpOp0.getValueType()));
11850
11851   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11852   if (CC == X86::COND_NE)
11853     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11854                        DL, OtherVal.getValueType(), OtherVal,
11855                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11856   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11857                      DL, OtherVal.getValueType(), OtherVal,
11858                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11859 }
11860
11861 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11862                                              DAGCombinerInfo &DCI) const {
11863   SelectionDAG &DAG = DCI.DAG;
11864   switch (N->getOpcode()) {
11865   default: break;
11866   case ISD::EXTRACT_VECTOR_ELT:
11867     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11868   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11869   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11870   case ISD::ADD:
11871   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
11872   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11873   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11874   case ISD::SHL:
11875   case ISD::SRA:
11876   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11877   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11878   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11879   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11880   case X86ISD::FXOR:
11881   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11882   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11883   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11884   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11885   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11886   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
11887   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11888   case X86ISD::SHUFPD:
11889   case X86ISD::PALIGN:
11890   case X86ISD::PUNPCKHBW:
11891   case X86ISD::PUNPCKHWD:
11892   case X86ISD::PUNPCKHDQ:
11893   case X86ISD::PUNPCKHQDQ:
11894   case X86ISD::UNPCKHPS:
11895   case X86ISD::UNPCKHPD:
11896   case X86ISD::PUNPCKLBW:
11897   case X86ISD::PUNPCKLWD:
11898   case X86ISD::PUNPCKLDQ:
11899   case X86ISD::PUNPCKLQDQ:
11900   case X86ISD::UNPCKLPS:
11901   case X86ISD::UNPCKLPD:
11902   case X86ISD::MOVHLPS:
11903   case X86ISD::MOVLHPS:
11904   case X86ISD::PSHUFD:
11905   case X86ISD::PSHUFHW:
11906   case X86ISD::PSHUFLW:
11907   case X86ISD::MOVSS:
11908   case X86ISD::MOVSD:
11909   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11910   }
11911
11912   return SDValue();
11913 }
11914
11915 /// isTypeDesirableForOp - Return true if the target has native support for
11916 /// the specified value type and it is 'desirable' to use the type for the
11917 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11918 /// instruction encodings are longer and some i16 instructions are slow.
11919 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11920   if (!isTypeLegal(VT))
11921     return false;
11922   if (VT != MVT::i16)
11923     return true;
11924
11925   switch (Opc) {
11926   default:
11927     return true;
11928   case ISD::LOAD:
11929   case ISD::SIGN_EXTEND:
11930   case ISD::ZERO_EXTEND:
11931   case ISD::ANY_EXTEND:
11932   case ISD::SHL:
11933   case ISD::SRL:
11934   case ISD::SUB:
11935   case ISD::ADD:
11936   case ISD::MUL:
11937   case ISD::AND:
11938   case ISD::OR:
11939   case ISD::XOR:
11940     return false;
11941   }
11942 }
11943
11944 /// IsDesirableToPromoteOp - This method query the target whether it is
11945 /// beneficial for dag combiner to promote the specified node. If true, it
11946 /// should return the desired promotion type by reference.
11947 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11948   EVT VT = Op.getValueType();
11949   if (VT != MVT::i16)
11950     return false;
11951
11952   bool Promote = false;
11953   bool Commute = false;
11954   switch (Op.getOpcode()) {
11955   default: break;
11956   case ISD::LOAD: {
11957     LoadSDNode *LD = cast<LoadSDNode>(Op);
11958     // If the non-extending load has a single use and it's not live out, then it
11959     // might be folded.
11960     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11961                                                      Op.hasOneUse()*/) {
11962       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11963              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11964         // The only case where we'd want to promote LOAD (rather then it being
11965         // promoted as an operand is when it's only use is liveout.
11966         if (UI->getOpcode() != ISD::CopyToReg)
11967           return false;
11968       }
11969     }
11970     Promote = true;
11971     break;
11972   }
11973   case ISD::SIGN_EXTEND:
11974   case ISD::ZERO_EXTEND:
11975   case ISD::ANY_EXTEND:
11976     Promote = true;
11977     break;
11978   case ISD::SHL:
11979   case ISD::SRL: {
11980     SDValue N0 = Op.getOperand(0);
11981     // Look out for (store (shl (load), x)).
11982     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11983       return false;
11984     Promote = true;
11985     break;
11986   }
11987   case ISD::ADD:
11988   case ISD::MUL:
11989   case ISD::AND:
11990   case ISD::OR:
11991   case ISD::XOR:
11992     Commute = true;
11993     // fallthrough
11994   case ISD::SUB: {
11995     SDValue N0 = Op.getOperand(0);
11996     SDValue N1 = Op.getOperand(1);
11997     if (!Commute && MayFoldLoad(N1))
11998       return false;
11999     // Avoid disabling potential load folding opportunities.
12000     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12001       return false;
12002     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12003       return false;
12004     Promote = true;
12005   }
12006   }
12007
12008   PVT = MVT::i32;
12009   return Promote;
12010 }
12011
12012 //===----------------------------------------------------------------------===//
12013 //                           X86 Inline Assembly Support
12014 //===----------------------------------------------------------------------===//
12015
12016 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12017   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12018
12019   std::string AsmStr = IA->getAsmString();
12020
12021   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12022   SmallVector<StringRef, 4> AsmPieces;
12023   SplitString(AsmStr, AsmPieces, ";\n");
12024
12025   switch (AsmPieces.size()) {
12026   default: return false;
12027   case 1:
12028     AsmStr = AsmPieces[0];
12029     AsmPieces.clear();
12030     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12031
12032     // FIXME: this should verify that we are targetting a 486 or better.  If not,
12033     // we will turn this bswap into something that will be lowered to logical ops
12034     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12035     // so don't worry about this.
12036     // bswap $0
12037     if (AsmPieces.size() == 2 &&
12038         (AsmPieces[0] == "bswap" ||
12039          AsmPieces[0] == "bswapq" ||
12040          AsmPieces[0] == "bswapl") &&
12041         (AsmPieces[1] == "$0" ||
12042          AsmPieces[1] == "${0:q}")) {
12043       // No need to check constraints, nothing other than the equivalent of
12044       // "=r,0" would be valid here.
12045       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12046       if (!Ty || Ty->getBitWidth() % 16 != 0)
12047         return false;
12048       return IntrinsicLowering::LowerToByteSwap(CI);
12049     }
12050     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12051     if (CI->getType()->isIntegerTy(16) &&
12052         AsmPieces.size() == 3 &&
12053         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12054         AsmPieces[1] == "$$8," &&
12055         AsmPieces[2] == "${0:w}" &&
12056         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12057       AsmPieces.clear();
12058       const std::string &ConstraintsStr = IA->getConstraintString();
12059       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12060       std::sort(AsmPieces.begin(), AsmPieces.end());
12061       if (AsmPieces.size() == 4 &&
12062           AsmPieces[0] == "~{cc}" &&
12063           AsmPieces[1] == "~{dirflag}" &&
12064           AsmPieces[2] == "~{flags}" &&
12065           AsmPieces[3] == "~{fpsr}") {
12066         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12067         if (!Ty || Ty->getBitWidth() % 16 != 0)
12068           return false;
12069         return IntrinsicLowering::LowerToByteSwap(CI);
12070       }
12071     }
12072     break;
12073   case 3:
12074     if (CI->getType()->isIntegerTy(32) &&
12075         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12076       SmallVector<StringRef, 4> Words;
12077       SplitString(AsmPieces[0], Words, " \t,");
12078       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12079           Words[2] == "${0:w}") {
12080         Words.clear();
12081         SplitString(AsmPieces[1], Words, " \t,");
12082         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12083             Words[2] == "$0") {
12084           Words.clear();
12085           SplitString(AsmPieces[2], Words, " \t,");
12086           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12087               Words[2] == "${0:w}") {
12088             AsmPieces.clear();
12089             const std::string &ConstraintsStr = IA->getConstraintString();
12090             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12091             std::sort(AsmPieces.begin(), AsmPieces.end());
12092             if (AsmPieces.size() == 4 &&
12093                 AsmPieces[0] == "~{cc}" &&
12094                 AsmPieces[1] == "~{dirflag}" &&
12095                 AsmPieces[2] == "~{flags}" &&
12096                 AsmPieces[3] == "~{fpsr}") {
12097               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12098               if (!Ty || Ty->getBitWidth() % 16 != 0)
12099                 return false;
12100               return IntrinsicLowering::LowerToByteSwap(CI);
12101             }
12102           }
12103         }
12104       }
12105     }
12106
12107     if (CI->getType()->isIntegerTy(64)) {
12108       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12109       if (Constraints.size() >= 2 &&
12110           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12111           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12112         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12113         SmallVector<StringRef, 4> Words;
12114         SplitString(AsmPieces[0], Words, " \t");
12115         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12116           Words.clear();
12117           SplitString(AsmPieces[1], Words, " \t");
12118           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12119             Words.clear();
12120             SplitString(AsmPieces[2], Words, " \t,");
12121             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12122                 Words[2] == "%edx") {
12123               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12124               if (!Ty || Ty->getBitWidth() % 16 != 0)
12125                 return false;
12126               return IntrinsicLowering::LowerToByteSwap(CI);
12127             }
12128           }
12129         }
12130       }
12131     }
12132     break;
12133   }
12134   return false;
12135 }
12136
12137
12138
12139 /// getConstraintType - Given a constraint letter, return the type of
12140 /// constraint it is for this target.
12141 X86TargetLowering::ConstraintType
12142 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12143   if (Constraint.size() == 1) {
12144     switch (Constraint[0]) {
12145     case 'R':
12146     case 'q':
12147     case 'Q':
12148     case 'f':
12149     case 't':
12150     case 'u':
12151     case 'y':
12152     case 'x':
12153     case 'Y':
12154       return C_RegisterClass;
12155     case 'a':
12156     case 'b':
12157     case 'c':
12158     case 'd':
12159     case 'S':
12160     case 'D':
12161     case 'A':
12162       return C_Register;
12163     case 'I':
12164     case 'J':
12165     case 'K':
12166     case 'L':
12167     case 'M':
12168     case 'N':
12169     case 'G':
12170     case 'C':
12171     case 'e':
12172     case 'Z':
12173       return C_Other;
12174     default:
12175       break;
12176     }
12177   }
12178   return TargetLowering::getConstraintType(Constraint);
12179 }
12180
12181 /// Examine constraint type and operand type and determine a weight value.
12182 /// This object must already have been set up with the operand type
12183 /// and the current alternative constraint selected.
12184 TargetLowering::ConstraintWeight
12185   X86TargetLowering::getSingleConstraintMatchWeight(
12186     AsmOperandInfo &info, const char *constraint) const {
12187   ConstraintWeight weight = CW_Invalid;
12188   Value *CallOperandVal = info.CallOperandVal;
12189     // If we don't have a value, we can't do a match,
12190     // but allow it at the lowest weight.
12191   if (CallOperandVal == NULL)
12192     return CW_Default;
12193   const Type *type = CallOperandVal->getType();
12194   // Look at the constraint type.
12195   switch (*constraint) {
12196   default:
12197     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12198   case 'R':
12199   case 'q':
12200   case 'Q':
12201   case 'a':
12202   case 'b':
12203   case 'c':
12204   case 'd':
12205   case 'S':
12206   case 'D':
12207   case 'A':
12208     if (CallOperandVal->getType()->isIntegerTy())
12209       weight = CW_SpecificReg;
12210     break;
12211   case 'f':
12212   case 't':
12213   case 'u':
12214       if (type->isFloatingPointTy())
12215         weight = CW_SpecificReg;
12216       break;
12217   case 'y':
12218       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12219         weight = CW_SpecificReg;
12220       break;
12221   case 'x':
12222   case 'Y':
12223     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12224       weight = CW_Register;
12225     break;
12226   case 'I':
12227     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12228       if (C->getZExtValue() <= 31)
12229         weight = CW_Constant;
12230     }
12231     break;
12232   case 'J':
12233     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12234       if (C->getZExtValue() <= 63)
12235         weight = CW_Constant;
12236     }
12237     break;
12238   case 'K':
12239     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12240       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12241         weight = CW_Constant;
12242     }
12243     break;
12244   case 'L':
12245     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12246       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12247         weight = CW_Constant;
12248     }
12249     break;
12250   case 'M':
12251     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12252       if (C->getZExtValue() <= 3)
12253         weight = CW_Constant;
12254     }
12255     break;
12256   case 'N':
12257     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12258       if (C->getZExtValue() <= 0xff)
12259         weight = CW_Constant;
12260     }
12261     break;
12262   case 'G':
12263   case 'C':
12264     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12265       weight = CW_Constant;
12266     }
12267     break;
12268   case 'e':
12269     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12270       if ((C->getSExtValue() >= -0x80000000LL) &&
12271           (C->getSExtValue() <= 0x7fffffffLL))
12272         weight = CW_Constant;
12273     }
12274     break;
12275   case 'Z':
12276     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12277       if (C->getZExtValue() <= 0xffffffff)
12278         weight = CW_Constant;
12279     }
12280     break;
12281   }
12282   return weight;
12283 }
12284
12285 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12286 /// with another that has more specific requirements based on the type of the
12287 /// corresponding operand.
12288 const char *X86TargetLowering::
12289 LowerXConstraint(EVT ConstraintVT) const {
12290   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12291   // 'f' like normal targets.
12292   if (ConstraintVT.isFloatingPoint()) {
12293     if (Subtarget->hasXMMInt())
12294       return "Y";
12295     if (Subtarget->hasXMM())
12296       return "x";
12297   }
12298
12299   return TargetLowering::LowerXConstraint(ConstraintVT);
12300 }
12301
12302 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12303 /// vector.  If it is invalid, don't add anything to Ops.
12304 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12305                                                      char Constraint,
12306                                                      std::vector<SDValue>&Ops,
12307                                                      SelectionDAG &DAG) const {
12308   SDValue Result(0, 0);
12309
12310   switch (Constraint) {
12311   default: break;
12312   case 'I':
12313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12314       if (C->getZExtValue() <= 31) {
12315         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12316         break;
12317       }
12318     }
12319     return;
12320   case 'J':
12321     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12322       if (C->getZExtValue() <= 63) {
12323         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12324         break;
12325       }
12326     }
12327     return;
12328   case 'K':
12329     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12330       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12331         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12332         break;
12333       }
12334     }
12335     return;
12336   case 'N':
12337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12338       if (C->getZExtValue() <= 255) {
12339         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12340         break;
12341       }
12342     }
12343     return;
12344   case 'e': {
12345     // 32-bit signed value
12346     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12347       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12348                                            C->getSExtValue())) {
12349         // Widen to 64 bits here to get it sign extended.
12350         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12351         break;
12352       }
12353     // FIXME gcc accepts some relocatable values here too, but only in certain
12354     // memory models; it's complicated.
12355     }
12356     return;
12357   }
12358   case 'Z': {
12359     // 32-bit unsigned value
12360     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12361       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12362                                            C->getZExtValue())) {
12363         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12364         break;
12365       }
12366     }
12367     // FIXME gcc accepts some relocatable values here too, but only in certain
12368     // memory models; it's complicated.
12369     return;
12370   }
12371   case 'i': {
12372     // Literal immediates are always ok.
12373     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12374       // Widen to 64 bits here to get it sign extended.
12375       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12376       break;
12377     }
12378
12379     // In any sort of PIC mode addresses need to be computed at runtime by
12380     // adding in a register or some sort of table lookup.  These can't
12381     // be used as immediates.
12382     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12383       return;
12384
12385     // If we are in non-pic codegen mode, we allow the address of a global (with
12386     // an optional displacement) to be used with 'i'.
12387     GlobalAddressSDNode *GA = 0;
12388     int64_t Offset = 0;
12389
12390     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12391     while (1) {
12392       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12393         Offset += GA->getOffset();
12394         break;
12395       } else if (Op.getOpcode() == ISD::ADD) {
12396         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12397           Offset += C->getZExtValue();
12398           Op = Op.getOperand(0);
12399           continue;
12400         }
12401       } else if (Op.getOpcode() == ISD::SUB) {
12402         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12403           Offset += -C->getZExtValue();
12404           Op = Op.getOperand(0);
12405           continue;
12406         }
12407       }
12408
12409       // Otherwise, this isn't something we can handle, reject it.
12410       return;
12411     }
12412
12413     const GlobalValue *GV = GA->getGlobal();
12414     // If we require an extra load to get this address, as in PIC mode, we
12415     // can't accept it.
12416     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12417                                                         getTargetMachine())))
12418       return;
12419
12420     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12421                                         GA->getValueType(0), Offset);
12422     break;
12423   }
12424   }
12425
12426   if (Result.getNode()) {
12427     Ops.push_back(Result);
12428     return;
12429   }
12430   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12431 }
12432
12433 std::vector<unsigned> X86TargetLowering::
12434 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12435                                   EVT VT) const {
12436   if (Constraint.size() == 1) {
12437     // FIXME: not handling fp-stack yet!
12438     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12439     default: break;  // Unknown constraint letter
12440     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12441       if (Subtarget->is64Bit()) {
12442         if (VT == MVT::i32)
12443           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12444                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12445                                        X86::R10D,X86::R11D,X86::R12D,
12446                                        X86::R13D,X86::R14D,X86::R15D,
12447                                        X86::EBP, X86::ESP, 0);
12448         else if (VT == MVT::i16)
12449           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12450                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12451                                        X86::R10W,X86::R11W,X86::R12W,
12452                                        X86::R13W,X86::R14W,X86::R15W,
12453                                        X86::BP,  X86::SP, 0);
12454         else if (VT == MVT::i8)
12455           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12456                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12457                                        X86::R10B,X86::R11B,X86::R12B,
12458                                        X86::R13B,X86::R14B,X86::R15B,
12459                                        X86::BPL, X86::SPL, 0);
12460
12461         else if (VT == MVT::i64)
12462           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12463                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12464                                        X86::R10, X86::R11, X86::R12,
12465                                        X86::R13, X86::R14, X86::R15,
12466                                        X86::RBP, X86::RSP, 0);
12467
12468         break;
12469       }
12470       // 32-bit fallthrough
12471     case 'Q':   // Q_REGS
12472       if (VT == MVT::i32)
12473         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12474       else if (VT == MVT::i16)
12475         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12476       else if (VT == MVT::i8)
12477         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12478       else if (VT == MVT::i64)
12479         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12480       break;
12481     }
12482   }
12483
12484   return std::vector<unsigned>();
12485 }
12486
12487 std::pair<unsigned, const TargetRegisterClass*>
12488 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12489                                                 EVT VT) const {
12490   // First, see if this is a constraint that directly corresponds to an LLVM
12491   // register class.
12492   if (Constraint.size() == 1) {
12493     // GCC Constraint Letters
12494     switch (Constraint[0]) {
12495     default: break;
12496     case 'r':   // GENERAL_REGS
12497     case 'l':   // INDEX_REGS
12498       if (VT == MVT::i8)
12499         return std::make_pair(0U, X86::GR8RegisterClass);
12500       if (VT == MVT::i16)
12501         return std::make_pair(0U, X86::GR16RegisterClass);
12502       if (VT == MVT::i32 || !Subtarget->is64Bit())
12503         return std::make_pair(0U, X86::GR32RegisterClass);
12504       return std::make_pair(0U, X86::GR64RegisterClass);
12505     case 'R':   // LEGACY_REGS
12506       if (VT == MVT::i8)
12507         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12508       if (VT == MVT::i16)
12509         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12510       if (VT == MVT::i32 || !Subtarget->is64Bit())
12511         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12512       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12513     case 'f':  // FP Stack registers.
12514       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12515       // value to the correct fpstack register class.
12516       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12517         return std::make_pair(0U, X86::RFP32RegisterClass);
12518       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12519         return std::make_pair(0U, X86::RFP64RegisterClass);
12520       return std::make_pair(0U, X86::RFP80RegisterClass);
12521     case 'y':   // MMX_REGS if MMX allowed.
12522       if (!Subtarget->hasMMX()) break;
12523       return std::make_pair(0U, X86::VR64RegisterClass);
12524     case 'Y':   // SSE_REGS if SSE2 allowed
12525       if (!Subtarget->hasXMMInt()) break;
12526       // FALL THROUGH.
12527     case 'x':   // SSE_REGS if SSE1 allowed
12528       if (!Subtarget->hasXMM()) break;
12529
12530       switch (VT.getSimpleVT().SimpleTy) {
12531       default: break;
12532       // Scalar SSE types.
12533       case MVT::f32:
12534       case MVT::i32:
12535         return std::make_pair(0U, X86::FR32RegisterClass);
12536       case MVT::f64:
12537       case MVT::i64:
12538         return std::make_pair(0U, X86::FR64RegisterClass);
12539       // Vector types.
12540       case MVT::v16i8:
12541       case MVT::v8i16:
12542       case MVT::v4i32:
12543       case MVT::v2i64:
12544       case MVT::v4f32:
12545       case MVT::v2f64:
12546         return std::make_pair(0U, X86::VR128RegisterClass);
12547       }
12548       break;
12549     }
12550   }
12551
12552   // Use the default implementation in TargetLowering to convert the register
12553   // constraint into a member of a register class.
12554   std::pair<unsigned, const TargetRegisterClass*> Res;
12555   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12556
12557   // Not found as a standard register?
12558   if (Res.second == 0) {
12559     // Map st(0) -> st(7) -> ST0
12560     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12561         tolower(Constraint[1]) == 's' &&
12562         tolower(Constraint[2]) == 't' &&
12563         Constraint[3] == '(' &&
12564         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12565         Constraint[5] == ')' &&
12566         Constraint[6] == '}') {
12567
12568       Res.first = X86::ST0+Constraint[4]-'0';
12569       Res.second = X86::RFP80RegisterClass;
12570       return Res;
12571     }
12572
12573     // GCC allows "st(0)" to be called just plain "st".
12574     if (StringRef("{st}").equals_lower(Constraint)) {
12575       Res.first = X86::ST0;
12576       Res.second = X86::RFP80RegisterClass;
12577       return Res;
12578     }
12579
12580     // flags -> EFLAGS
12581     if (StringRef("{flags}").equals_lower(Constraint)) {
12582       Res.first = X86::EFLAGS;
12583       Res.second = X86::CCRRegisterClass;
12584       return Res;
12585     }
12586
12587     // 'A' means EAX + EDX.
12588     if (Constraint == "A") {
12589       Res.first = X86::EAX;
12590       Res.second = X86::GR32_ADRegisterClass;
12591       return Res;
12592     }
12593     return Res;
12594   }
12595
12596   // Otherwise, check to see if this is a register class of the wrong value
12597   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12598   // turn into {ax},{dx}.
12599   if (Res.second->hasType(VT))
12600     return Res;   // Correct type already, nothing to do.
12601
12602   // All of the single-register GCC register classes map their values onto
12603   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12604   // really want an 8-bit or 32-bit register, map to the appropriate register
12605   // class and return the appropriate register.
12606   if (Res.second == X86::GR16RegisterClass) {
12607     if (VT == MVT::i8) {
12608       unsigned DestReg = 0;
12609       switch (Res.first) {
12610       default: break;
12611       case X86::AX: DestReg = X86::AL; break;
12612       case X86::DX: DestReg = X86::DL; break;
12613       case X86::CX: DestReg = X86::CL; break;
12614       case X86::BX: DestReg = X86::BL; break;
12615       }
12616       if (DestReg) {
12617         Res.first = DestReg;
12618         Res.second = X86::GR8RegisterClass;
12619       }
12620     } else if (VT == MVT::i32) {
12621       unsigned DestReg = 0;
12622       switch (Res.first) {
12623       default: break;
12624       case X86::AX: DestReg = X86::EAX; break;
12625       case X86::DX: DestReg = X86::EDX; break;
12626       case X86::CX: DestReg = X86::ECX; break;
12627       case X86::BX: DestReg = X86::EBX; break;
12628       case X86::SI: DestReg = X86::ESI; break;
12629       case X86::DI: DestReg = X86::EDI; break;
12630       case X86::BP: DestReg = X86::EBP; break;
12631       case X86::SP: DestReg = X86::ESP; break;
12632       }
12633       if (DestReg) {
12634         Res.first = DestReg;
12635         Res.second = X86::GR32RegisterClass;
12636       }
12637     } else if (VT == MVT::i64) {
12638       unsigned DestReg = 0;
12639       switch (Res.first) {
12640       default: break;
12641       case X86::AX: DestReg = X86::RAX; break;
12642       case X86::DX: DestReg = X86::RDX; break;
12643       case X86::CX: DestReg = X86::RCX; break;
12644       case X86::BX: DestReg = X86::RBX; break;
12645       case X86::SI: DestReg = X86::RSI; break;
12646       case X86::DI: DestReg = X86::RDI; break;
12647       case X86::BP: DestReg = X86::RBP; break;
12648       case X86::SP: DestReg = X86::RSP; break;
12649       }
12650       if (DestReg) {
12651         Res.first = DestReg;
12652         Res.second = X86::GR64RegisterClass;
12653       }
12654     }
12655   } else if (Res.second == X86::FR32RegisterClass ||
12656              Res.second == X86::FR64RegisterClass ||
12657              Res.second == X86::VR128RegisterClass) {
12658     // Handle references to XMM physical registers that got mapped into the
12659     // wrong class.  This can happen with constraints like {xmm0} where the
12660     // target independent register mapper will just pick the first match it can
12661     // find, ignoring the required type.
12662     if (VT == MVT::f32)
12663       Res.second = X86::FR32RegisterClass;
12664     else if (VT == MVT::f64)
12665       Res.second = X86::FR64RegisterClass;
12666     else if (X86::VR128RegisterClass->hasType(VT))
12667       Res.second = X86::VR128RegisterClass;
12668   }
12669
12670   return Res;
12671 }