Recommit 132404 with fixes. rdar://problem/5993888
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
75
76
77 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
78 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
79 /// simple subregister reference.  Idx is an index in the 128 bits we
80 /// want.  It need not be aligned to a 128-bit bounday.  That makes
81 /// lowering EXTRACT_VECTOR_ELT operations easier.
82 static SDValue Extract128BitVector(SDValue Vec,
83                                    SDValue Idx,
84                                    SelectionDAG &DAG,
85                                    DebugLoc dl) {
86   EVT VT = Vec.getValueType();
87   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
88
89   EVT ElVT = VT.getVectorElementType();
90
91   int Factor = VT.getSizeInBits() / 128;
92
93   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
94                                   ElVT,
95                                   VT.getVectorNumElements() / Factor);
96
97   // Extract from UNDEF is UNDEF.
98   if (Vec.getOpcode() == ISD::UNDEF)
99     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
100
101   if (isa<ConstantSDNode>(Idx)) {
102     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
103
104     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
105     // we can match to VEXTRACTF128.
106     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
107
108     // This is the index of the first element of the 128-bit chunk
109     // we want.
110     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
111                                  * ElemsPerChunk);
112
113     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
114
115     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
116                                  VecIdx);
117
118     return Result;
119   }
120
121   return SDValue();
122 }
123
124 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
125 /// sets things up to match to an AVX VINSERTF128 instruction or a
126 /// simple superregister reference.  Idx is an index in the 128 bits
127 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
128 /// lowering INSERT_VECTOR_ELT operations easier.
129 static SDValue Insert128BitVector(SDValue Result,
130                                   SDValue Vec,
131                                   SDValue Idx,
132                                   SelectionDAG &DAG,
133                                   DebugLoc dl) {
134   if (isa<ConstantSDNode>(Idx)) {
135     EVT VT = Vec.getValueType();
136     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
137
138     EVT ElVT = VT.getVectorElementType();
139
140     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
141
142     EVT ResultVT = Result.getValueType();
143
144     // Insert the relevant 128 bits.
145     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
146
147     // This is the index of the first element of the 128-bit chunk
148     // we want.
149     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
150                                  * ElemsPerChunk);
151
152     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
153
154     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                          VecIdx);
156     return Result;
157   }
158
159   return SDValue();
160 }
161
162 /// Given two vectors, concat them.
163 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
164   DebugLoc dl = Lower.getDebugLoc();
165
166   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
167
168   EVT VT = EVT::getVectorVT(*DAG.getContext(),
169                             Lower.getValueType().getVectorElementType(),
170                             Lower.getValueType().getVectorNumElements() * 2);
171
172   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
173   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
174
175   // Insert the upper subvector.
176   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
177                                    DAG.getConstant(
178                                      // This is half the length of the result
179                                      // vector.  Start inserting the upper 128
180                                      // bits here.
181                                      Lower.getValueType().getVectorNumElements(),
182                                      MVT::i32),
183                                    DAG, dl);
184
185   // Insert the lower subvector.
186   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
187   return Vec;
188 }
189
190 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
191   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
192   bool is64Bit = Subtarget->is64Bit();
193
194   if (Subtarget->isTargetEnvMacho()) {
195     if (is64Bit)
196       return new X8664_MachoTargetObjectFile();
197     return new TargetLoweringObjectFileMachO();
198   }
199
200   if (Subtarget->isTargetELF()) {
201     if (is64Bit)
202       return new X8664_ELFTargetObjectFile(TM);
203     return new X8632_ELFTargetObjectFile(TM);
204   }
205   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
206     return new TargetLoweringObjectFileCOFF();
207   llvm_unreachable("unknown subtarget type");
208 }
209
210 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
211   : TargetLowering(TM, createTLOF(TM)) {
212   Subtarget = &TM.getSubtarget<X86Subtarget>();
213   X86ScalarSSEf64 = Subtarget->hasXMMInt();
214   X86ScalarSSEf32 = Subtarget->hasXMM();
215   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
216
217   RegInfo = TM.getRegisterInfo();
218   TD = getTargetData();
219
220   // Set up the TargetLowering object.
221   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
222
223   // X86 is weird, it always uses i8 for shift amounts and setcc results.
224   setBooleanContents(ZeroOrOneBooleanContent);
225     
226   // For 64-bit since we have so many registers use the ILP scheduler, for
227   // 32-bit code use the register pressure specific scheduling.
228   if (Subtarget->is64Bit())
229     setSchedulingPreference(Sched::ILP);
230   else
231     setSchedulingPreference(Sched::RegPressure);
232   setStackPointerRegisterToSaveRestore(X86StackPtr);
233
234   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
235     // Setup Windows compiler runtime calls.
236     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
237     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
238     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
239     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
240     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
243     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
244   }
245
246   if (Subtarget->isTargetDarwin()) {
247     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
248     setUseUnderscoreSetJmp(false);
249     setUseUnderscoreLongJmp(false);
250   } else if (Subtarget->isTargetMingw()) {
251     // MS runtime is weird: it exports _setjmp, but longjmp!
252     setUseUnderscoreSetJmp(true);
253     setUseUnderscoreLongJmp(false);
254   } else {
255     setUseUnderscoreSetJmp(true);
256     setUseUnderscoreLongJmp(true);
257   }
258
259   // Set up the register classes.
260   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
261   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
262   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
263   if (Subtarget->is64Bit())
264     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
265
266   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
267
268   // We don't accept any truncstore of integer registers.
269   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
271   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
272   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
273   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
274   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
275
276   // SETOEQ and SETUNE require checking two conditions.
277   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
279   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
282   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
283
284   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
285   // operation.
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
288   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
289
290   if (Subtarget->is64Bit()) {
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
292     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
293   } else if (!UseSoftFloat) {
294     // We have an algorithm for SSE2->double, and we turn this into a
295     // 64-bit FILD followed by conditional FADD for other targets.
296     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
297     // We have an algorithm for SSE2, and we turn this into a 64-bit
298     // FILD for other targets.
299     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
300   }
301
302   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
303   // this operation.
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
305   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
306
307   if (!UseSoftFloat) {
308     // SSE has no i16 to fp conversion, only i32
309     if (X86ScalarSSEf32) {
310       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
311       // f32 and f64 cases are Legal, f80 case is not
312       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
313     } else {
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
315       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
316     }
317   } else {
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
319     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
320   }
321
322   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
323   // are Legal, f80 is custom lowered.
324   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
325   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
326
327   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
328   // this operation.
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
330   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
331
332   if (X86ScalarSSEf32) {
333     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
334     // f32 and f64 cases are Legal, f80 case is not
335     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
336   } else {
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
338     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
339   }
340
341   // Handle FP_TO_UINT by promoting the destination to a larger signed
342   // conversion.
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
345   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
346
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
349     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
350   } else if (!UseSoftFloat) {
351     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
352       // Expand FP_TO_UINT into a select.
353       // FIXME: We would like to use a Custom expander here eventually to do
354       // the optimal thing for SSE vs. the default expansion in the legalizer.
355       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
356     else
357       // With SSE3 we can use fisttpll to convert to a signed i64; without
358       // SSE, we're stuck with a fistpll.
359       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
360   }
361
362   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
363   if (!X86ScalarSSEf64) {
364     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
365     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
366     if (Subtarget->is64Bit()) {
367       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
368       // Without SSE, i64->f64 goes through memory.
369       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
370     }
371   }
372
373   // Scalar integer divide and remainder are lowered to use operations that
374   // produce two results, to match the available instructions. This exposes
375   // the two-result form to trivial CSE, which is able to combine x/y and x%y
376   // into a single instruction.
377   //
378   // Scalar integer multiply-high is also lowered to use two-result
379   // operations, to match the available instructions. However, plain multiply
380   // (low) operations are left as Legal, as there are single-result
381   // instructions for this in x86. Using the two-result multiply instructions
382   // when both high and low results are needed must be arranged by dagcombine.
383   for (unsigned i = 0, e = 4; i != e; ++i) {
384     MVT VT = IntVTs[i];
385     setOperationAction(ISD::MULHS, VT, Expand);
386     setOperationAction(ISD::MULHU, VT, Expand);
387     setOperationAction(ISD::SDIV, VT, Expand);
388     setOperationAction(ISD::UDIV, VT, Expand);
389     setOperationAction(ISD::SREM, VT, Expand);
390     setOperationAction(ISD::UREM, VT, Expand);
391
392     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
393     setOperationAction(ISD::ADDC, VT, Custom);
394     setOperationAction(ISD::ADDE, VT, Custom);
395     setOperationAction(ISD::SUBC, VT, Custom);
396     setOperationAction(ISD::SUBE, VT, Custom);
397   }
398
399   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
400   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
401   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
408   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
412   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
413
414   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
416   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
418   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
419   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
420   if (Subtarget->is64Bit()) {
421     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
422     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
423   }
424
425   if (Subtarget->hasPOPCNT()) {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
427   } else {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
430     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
433   }
434
435   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
436   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
437
438   // These should be promoted to a larger select which is supported.
439   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
440   // X86 wants to expand cmov itself.
441   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
453   if (Subtarget->is64Bit()) {
454     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
455     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
456   }
457   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
458
459   // Darwin ABI issue.
460   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
461   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
463   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
464   if (Subtarget->is64Bit())
465     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
466   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
467   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
470     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
471     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
472     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
473     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
474   }
475   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
476   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
478   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
479   if (Subtarget->is64Bit()) {
480     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
482     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
483   }
484
485   if (Subtarget->hasXMM())
486     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
487
488   // We may not have a libcall for MEMBARRIER so we should lower this.
489   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
490
491   // On X86 and X86-64, atomic operations are lowered to locked instructions.
492   // Locked instructions, in turn, have implicit fence semantics (all memory
493   // operations are flushed before issuing the locked instruction, and they
494   // are not buffered), so we can fold away the common pattern of
495   // fence-atomic-fence.
496   setShouldFoldAtomicFences(true);
497
498   // Expand certain atomics
499   for (unsigned i = 0, e = 4; i != e; ++i) {
500     MVT VT = IntVTs[i];
501     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
503   }
504
505   if (!Subtarget->is64Bit()) {
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   // FIXME - use subtarget debug flags
516   if (!Subtarget->isTargetDarwin() &&
517       !Subtarget->isTargetELF() &&
518       !Subtarget->isTargetCygMing()) {
519     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520   }
521
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
524   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
525   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
526   if (Subtarget->is64Bit()) {
527     setExceptionPointerRegister(X86::RAX);
528     setExceptionSelectorRegister(X86::RDX);
529   } else {
530     setExceptionPointerRegister(X86::EAX);
531     setExceptionSelectorRegister(X86::EDX);
532   }
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
534   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
535
536   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
537
538   setOperationAction(ISD::TRAP, MVT::Other, Legal);
539
540   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
541   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   if (Subtarget->is64Bit()) {
544     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
545     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
546   } else {
547     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
548     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
549   }
550
551   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
552   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
553   setOperationAction(ISD::DYNAMIC_STACKALLOC,
554                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
555                      (Subtarget->isTargetCOFF()
556                       && !Subtarget->isTargetEnvMacho()
557                       ? Custom : Expand));
558
559   if (!UseSoftFloat && X86ScalarSSEf64) {
560     // f32 and f64 use SSE.
561     // Set up the FP register classes.
562     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
563     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
564
565     // Use ANDPD to simulate FABS.
566     setOperationAction(ISD::FABS , MVT::f64, Custom);
567     setOperationAction(ISD::FABS , MVT::f32, Custom);
568
569     // Use XORP to simulate FNEG.
570     setOperationAction(ISD::FNEG , MVT::f64, Custom);
571     setOperationAction(ISD::FNEG , MVT::f32, Custom);
572
573     // Use ANDPD and ORPD to simulate FCOPYSIGN.
574     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
575     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576
577     // Lower this to FGETSIGNx86 plus an AND.
578     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
579     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
580
581     // We don't support sin/cos/fmod
582     setOperationAction(ISD::FSIN , MVT::f64, Expand);
583     setOperationAction(ISD::FCOS , MVT::f64, Expand);
584     setOperationAction(ISD::FSIN , MVT::f32, Expand);
585     setOperationAction(ISD::FCOS , MVT::f32, Expand);
586
587     // Expand FP immediates into loads from the stack, except for the special
588     // cases we handle.
589     addLegalFPImmediate(APFloat(+0.0)); // xorpd
590     addLegalFPImmediate(APFloat(+0.0f)); // xorps
591   } else if (!UseSoftFloat && X86ScalarSSEf32) {
592     // Use SSE for f32, x87 for f64.
593     // Set up the FP register classes.
594     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
595     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
596
597     // Use ANDPS to simulate FABS.
598     setOperationAction(ISD::FABS , MVT::f32, Custom);
599
600     // Use XORP to simulate FNEG.
601     setOperationAction(ISD::FNEG , MVT::f32, Custom);
602
603     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
604
605     // Use ANDPS and ORPS to simulate FCOPYSIGN.
606     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
607     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
608
609     // We don't support sin/cos/fmod
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Special cases we handle for FP constants.
614     addLegalFPImmediate(APFloat(+0.0f)); // xorps
615     addLegalFPImmediate(APFloat(+0.0)); // FLD0
616     addLegalFPImmediate(APFloat(+1.0)); // FLD1
617     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619
620     if (!UnsafeFPMath) {
621       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
622       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
623     }
624   } else if (!UseSoftFloat) {
625     // f32 and f64 in x87.
626     // Set up the FP register classes.
627     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
628     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
634
635     if (!UnsafeFPMath) {
636       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
637       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
638     }
639     addLegalFPImmediate(APFloat(+0.0)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
643     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
647   }
648
649   // Long double always uses X87.
650   if (!UseSoftFloat) {
651     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
652     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
653     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
654     {
655       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
656       addLegalFPImmediate(TmpFlt);  // FLD0
657       TmpFlt.changeSign();
658       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
659
660       bool ignored;
661       APFloat TmpFlt2(+1.0);
662       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
663                       &ignored);
664       addLegalFPImmediate(TmpFlt2);  // FLD1
665       TmpFlt2.changeSign();
666       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
667     }
668
669     if (!UnsafeFPMath) {
670       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
671       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
672     }
673   }
674
675   // Always use a library call for pow.
676   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
677   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
678   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
679
680   setOperationAction(ISD::FLOG, MVT::f80, Expand);
681   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
682   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
683   setOperationAction(ISD::FEXP, MVT::f80, Expand);
684   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
685
686   // First set operation action for all vector types to either promote
687   // (for widening) or expand (for scalarization). Then we will selectively
688   // turn on ones that can be effectively codegen'd.
689   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
690        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
691     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
706     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
708     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
709     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
741     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
745     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
746          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
747       setTruncStoreAction((MVT::SimpleValueType)VT,
748                           (MVT::SimpleValueType)InnerVT, Expand);
749     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
750     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
751     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
752   }
753
754   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
755   // with -msoft-float, disable use of MMX as well.
756   if (!UseSoftFloat && Subtarget->hasMMX()) {
757     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
758     // No operations on x86mmx supported, everything uses intrinsics.
759   }
760
761   // MMX-sized vectors (other than x86mmx) are expected to be expanded
762   // into smaller operations.
763   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
764   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
765   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
766   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
767   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
768   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
769   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
770   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
771   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
772   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
773   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
774   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
775   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
776   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
777   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
778   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
779   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
780   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
781   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
782   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
783   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
784   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
785   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
786   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
787   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
788   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
789   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
790   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
791   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
792
793   if (!UseSoftFloat && Subtarget->hasXMM()) {
794     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
795
796     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
797     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
798     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
799     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
800     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
801     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
802     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
803     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
804     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
805     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
806     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
807     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
808   }
809
810   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
811     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
812
813     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
814     // registers cannot be used even for integer operations.
815     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
816     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
817     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
818     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
819
820     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
821     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
822     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
823     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
825     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
826     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
827     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
828     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
829     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
830     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
831     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
832     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
833     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
834     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
835     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
836
837     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
838     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
839     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
840     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
841
842     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
843     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
846     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
847
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
849     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
850     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
851     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
852     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
853
854     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
855     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
856       EVT VT = (MVT::SimpleValueType)i;
857       // Do not attempt to custom lower non-power-of-2 vectors
858       if (!isPowerOf2_32(VT.getVectorNumElements()))
859         continue;
860       // Do not attempt to custom lower non-128-bit vectors
861       if (!VT.is128BitVector())
862         continue;
863       setOperationAction(ISD::BUILD_VECTOR,
864                          VT.getSimpleVT().SimpleTy, Custom);
865       setOperationAction(ISD::VECTOR_SHUFFLE,
866                          VT.getSimpleVT().SimpleTy, Custom);
867       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
868                          VT.getSimpleVT().SimpleTy, Custom);
869     }
870
871     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
873     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
876     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
877
878     if (Subtarget->is64Bit()) {
879       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
880       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
881     }
882
883     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
884     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
885       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
886       EVT VT = SVT;
887
888       // Do not attempt to promote non-128-bit vectors
889       if (!VT.is128BitVector())
890         continue;
891
892       setOperationAction(ISD::AND,    SVT, Promote);
893       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
894       setOperationAction(ISD::OR,     SVT, Promote);
895       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
896       setOperationAction(ISD::XOR,    SVT, Promote);
897       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
898       setOperationAction(ISD::LOAD,   SVT, Promote);
899       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
900       setOperationAction(ISD::SELECT, SVT, Promote);
901       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
902     }
903
904     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
905
906     // Custom lower v2i64 and v2f64 selects.
907     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
908     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
909     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
910     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
911
912     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
913     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
914   }
915
916   if (Subtarget->hasSSE41()) {
917     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
922     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
923     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
924     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
925     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
926     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
927
928     // FIXME: Do we need to handle scalar-to-vector here?
929     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
930
931     // Can turn SHL into an integer multiply.
932     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
933     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
934
935     // i8 and i16 vectors are custom , because the source register and source
936     // source memory operand types are not the same width.  f32 vectors are
937     // custom since the immediate controlling the insert encodes additional
938     // information.
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
943
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
945     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
948
949     if (Subtarget->is64Bit()) {
950       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
952     }
953   }
954
955   if (Subtarget->hasSSE2()) {
956     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
957     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
958     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
959
960     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
961     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
962     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
963
964     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
966   }
967
968   if (Subtarget->hasSSE42())
969     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
970
971   if (!UseSoftFloat && Subtarget->hasAVX()) {
972     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
973     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
974     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
975     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
976     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
977
978     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
980     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
982
983     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
989
990     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
991     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
992     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
993     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
995     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
996
997     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
998     // insert_vector_elt extract_subvector and extract_vector_elt for
999     // 256-bit types.
1000     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1001          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1002          ++i) {
1003       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1004       // Do not attempt to custom lower non-256-bit vectors
1005       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
1006           || (MVT(VT).getSizeInBits() < 256))
1007         continue;
1008       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1009       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1010       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1013     }
1014     // Custom-lower insert_subvector and extract_subvector based on
1015     // the result type.
1016     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1017          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1018          ++i) {
1019       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1020       // Do not attempt to custom lower non-256-bit vectors
1021       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1022         continue;
1023
1024       if (MVT(VT).getSizeInBits() == 128) {
1025         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1026       }
1027       else if (MVT(VT).getSizeInBits() == 256) {
1028         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1029       }
1030     }
1031
1032     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1033     // Don't promote loads because we need them for VPERM vector index versions.
1034
1035     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1036          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1037          VT++) {
1038       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1039           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1040         continue;
1041       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1042       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1043       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1044       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1045       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1046       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1047       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1048       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1049       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1050       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1051     }
1052   }
1053
1054   // We want to custom lower some of our intrinsics.
1055   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1056
1057
1058   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1059   // handle type legalization for these operations here.
1060   //
1061   // FIXME: We really should do custom legalization for addition and
1062   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1063   // than generic legalization for 64-bit multiplication-with-overflow, though.
1064   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1065     // Add/Sub/Mul with overflow operations are custom lowered.
1066     MVT VT = IntVTs[i];
1067     setOperationAction(ISD::SADDO, VT, Custom);
1068     setOperationAction(ISD::UADDO, VT, Custom);
1069     setOperationAction(ISD::SSUBO, VT, Custom);
1070     setOperationAction(ISD::USUBO, VT, Custom);
1071     setOperationAction(ISD::SMULO, VT, Custom);
1072     setOperationAction(ISD::UMULO, VT, Custom);
1073   }
1074
1075   // There are no 8-bit 3-address imul/mul instructions
1076   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1077   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1078
1079   if (!Subtarget->is64Bit()) {
1080     // These libcalls are not available in 32-bit.
1081     setLibcallName(RTLIB::SHL_I128, 0);
1082     setLibcallName(RTLIB::SRL_I128, 0);
1083     setLibcallName(RTLIB::SRA_I128, 0);
1084   }
1085
1086   // We have target-specific dag combine patterns for the following nodes:
1087   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1088   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1089   setTargetDAGCombine(ISD::BUILD_VECTOR);
1090   setTargetDAGCombine(ISD::SELECT);
1091   setTargetDAGCombine(ISD::SHL);
1092   setTargetDAGCombine(ISD::SRA);
1093   setTargetDAGCombine(ISD::SRL);
1094   setTargetDAGCombine(ISD::OR);
1095   setTargetDAGCombine(ISD::AND);
1096   setTargetDAGCombine(ISD::ADD);
1097   setTargetDAGCombine(ISD::SUB);
1098   setTargetDAGCombine(ISD::STORE);
1099   setTargetDAGCombine(ISD::ZERO_EXTEND);
1100   if (Subtarget->is64Bit())
1101     setTargetDAGCombine(ISD::MUL);
1102
1103   computeRegisterProperties();
1104
1105   // On Darwin, -Os means optimize for size without hurting performance,
1106   // do not reduce the limit.
1107   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1108   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1109   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1110   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1111   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1112   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1113   setPrefLoopAlignment(16);
1114   benefitFromCodePlacementOpt = true;
1115
1116   setPrefFunctionAlignment(4);
1117 }
1118
1119
1120 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1121   return MVT::i8;
1122 }
1123
1124
1125 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1126 /// the desired ByVal argument alignment.
1127 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1128   if (MaxAlign == 16)
1129     return;
1130   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1131     if (VTy->getBitWidth() == 128)
1132       MaxAlign = 16;
1133   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1134     unsigned EltAlign = 0;
1135     getMaxByValAlign(ATy->getElementType(), EltAlign);
1136     if (EltAlign > MaxAlign)
1137       MaxAlign = EltAlign;
1138   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1139     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1140       unsigned EltAlign = 0;
1141       getMaxByValAlign(STy->getElementType(i), EltAlign);
1142       if (EltAlign > MaxAlign)
1143         MaxAlign = EltAlign;
1144       if (MaxAlign == 16)
1145         break;
1146     }
1147   }
1148   return;
1149 }
1150
1151 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1152 /// function arguments in the caller parameter area. For X86, aggregates
1153 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1154 /// are at 4-byte boundaries.
1155 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1156   if (Subtarget->is64Bit()) {
1157     // Max of 8 and alignment of type.
1158     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1159     if (TyAlign > 8)
1160       return TyAlign;
1161     return 8;
1162   }
1163
1164   unsigned Align = 4;
1165   if (Subtarget->hasXMM())
1166     getMaxByValAlign(Ty, Align);
1167   return Align;
1168 }
1169
1170 /// getOptimalMemOpType - Returns the target specific optimal type for load
1171 /// and store operations as a result of memset, memcpy, and memmove
1172 /// lowering. If DstAlign is zero that means it's safe to destination
1173 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1174 /// means there isn't a need to check it against alignment requirement,
1175 /// probably because the source does not need to be loaded. If
1176 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1177 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1178 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1179 /// constant so it does not need to be loaded.
1180 /// It returns EVT::Other if the type should be determined using generic
1181 /// target-independent logic.
1182 EVT
1183 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1184                                        unsigned DstAlign, unsigned SrcAlign,
1185                                        bool NonScalarIntSafe,
1186                                        bool MemcpyStrSrc,
1187                                        MachineFunction &MF) const {
1188   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1189   // linux.  This is because the stack realignment code can't handle certain
1190   // cases like PR2962.  This should be removed when PR2962 is fixed.
1191   const Function *F = MF.getFunction();
1192   if (NonScalarIntSafe &&
1193       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1194     if (Size >= 16 &&
1195         (Subtarget->isUnalignedMemAccessFast() ||
1196          ((DstAlign == 0 || DstAlign >= 16) &&
1197           (SrcAlign == 0 || SrcAlign >= 16))) &&
1198         Subtarget->getStackAlignment() >= 16) {
1199       if (Subtarget->hasSSE2())
1200         return MVT::v4i32;
1201       if (Subtarget->hasSSE1())
1202         return MVT::v4f32;
1203     } else if (!MemcpyStrSrc && Size >= 8 &&
1204                !Subtarget->is64Bit() &&
1205                Subtarget->getStackAlignment() >= 8 &&
1206                Subtarget->hasXMMInt()) {
1207       // Do not use f64 to lower memcpy if source is string constant. It's
1208       // better to use i32 to avoid the loads.
1209       return MVT::f64;
1210     }
1211   }
1212   if (Subtarget->is64Bit() && Size >= 8)
1213     return MVT::i64;
1214   return MVT::i32;
1215 }
1216
1217 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1218 /// current function.  The returned value is a member of the
1219 /// MachineJumpTableInfo::JTEntryKind enum.
1220 unsigned X86TargetLowering::getJumpTableEncoding() const {
1221   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1222   // symbol.
1223   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1224       Subtarget->isPICStyleGOT())
1225     return MachineJumpTableInfo::EK_Custom32;
1226
1227   // Otherwise, use the normal jump table encoding heuristics.
1228   return TargetLowering::getJumpTableEncoding();
1229 }
1230
1231 const MCExpr *
1232 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1233                                              const MachineBasicBlock *MBB,
1234                                              unsigned uid,MCContext &Ctx) const{
1235   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1236          Subtarget->isPICStyleGOT());
1237   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1238   // entries.
1239   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1240                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1241 }
1242
1243 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1244 /// jumptable.
1245 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1246                                                     SelectionDAG &DAG) const {
1247   if (!Subtarget->is64Bit())
1248     // This doesn't have DebugLoc associated with it, but is not really the
1249     // same as a Register.
1250     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1251   return Table;
1252 }
1253
1254 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1255 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1256 /// MCExpr.
1257 const MCExpr *X86TargetLowering::
1258 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1259                              MCContext &Ctx) const {
1260   // X86-64 uses RIP relative addressing based on the jump table label.
1261   if (Subtarget->isPICStyleRIPRel())
1262     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1263
1264   // Otherwise, the reference is relative to the PIC base.
1265   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1266 }
1267
1268 // FIXME: Why this routine is here? Move to RegInfo!
1269 std::pair<const TargetRegisterClass*, uint8_t>
1270 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1271   const TargetRegisterClass *RRC = 0;
1272   uint8_t Cost = 1;
1273   switch (VT.getSimpleVT().SimpleTy) {
1274   default:
1275     return TargetLowering::findRepresentativeClass(VT);
1276   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1277     RRC = (Subtarget->is64Bit()
1278            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1279     break;
1280   case MVT::x86mmx:
1281     RRC = X86::VR64RegisterClass;
1282     break;
1283   case MVT::f32: case MVT::f64:
1284   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1285   case MVT::v4f32: case MVT::v2f64:
1286   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1287   case MVT::v4f64:
1288     RRC = X86::VR128RegisterClass;
1289     break;
1290   }
1291   return std::make_pair(RRC, Cost);
1292 }
1293
1294 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1295                                                unsigned &Offset) const {
1296   if (!Subtarget->isTargetLinux())
1297     return false;
1298
1299   if (Subtarget->is64Bit()) {
1300     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1301     Offset = 0x28;
1302     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1303       AddressSpace = 256;
1304     else
1305       AddressSpace = 257;
1306   } else {
1307     // %gs:0x14 on i386
1308     Offset = 0x14;
1309     AddressSpace = 256;
1310   }
1311   return true;
1312 }
1313
1314
1315 //===----------------------------------------------------------------------===//
1316 //               Return Value Calling Convention Implementation
1317 //===----------------------------------------------------------------------===//
1318
1319 #include "X86GenCallingConv.inc"
1320
1321 bool
1322 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1323                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1324                         LLVMContext &Context) const {
1325   SmallVector<CCValAssign, 16> RVLocs;
1326   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1327                  RVLocs, Context);
1328   return CCInfo.CheckReturn(Outs, RetCC_X86);
1329 }
1330
1331 SDValue
1332 X86TargetLowering::LowerReturn(SDValue Chain,
1333                                CallingConv::ID CallConv, bool isVarArg,
1334                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1335                                const SmallVectorImpl<SDValue> &OutVals,
1336                                DebugLoc dl, SelectionDAG &DAG) const {
1337   MachineFunction &MF = DAG.getMachineFunction();
1338   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1339
1340   SmallVector<CCValAssign, 16> RVLocs;
1341   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1342                  RVLocs, *DAG.getContext());
1343   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1344
1345   // Add the regs to the liveout set for the function.
1346   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1347   for (unsigned i = 0; i != RVLocs.size(); ++i)
1348     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1349       MRI.addLiveOut(RVLocs[i].getLocReg());
1350
1351   SDValue Flag;
1352
1353   SmallVector<SDValue, 6> RetOps;
1354   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1355   // Operand #1 = Bytes To Pop
1356   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1357                    MVT::i16));
1358
1359   // Copy the result values into the output registers.
1360   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1361     CCValAssign &VA = RVLocs[i];
1362     assert(VA.isRegLoc() && "Can only return in registers!");
1363     SDValue ValToCopy = OutVals[i];
1364     EVT ValVT = ValToCopy.getValueType();
1365
1366     // If this is x86-64, and we disabled SSE, we can't return FP values,
1367     // or SSE or MMX vectors.
1368     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1369          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1370           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1371       report_fatal_error("SSE register return with SSE disabled");
1372     }
1373     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1374     // llvm-gcc has never done it right and no one has noticed, so this
1375     // should be OK for now.
1376     if (ValVT == MVT::f64 &&
1377         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1378       report_fatal_error("SSE2 register return with SSE2 disabled");
1379
1380     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1381     // the RET instruction and handled by the FP Stackifier.
1382     if (VA.getLocReg() == X86::ST0 ||
1383         VA.getLocReg() == X86::ST1) {
1384       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1385       // change the value to the FP stack register class.
1386       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1387         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1388       RetOps.push_back(ValToCopy);
1389       // Don't emit a copytoreg.
1390       continue;
1391     }
1392
1393     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1394     // which is returned in RAX / RDX.
1395     if (Subtarget->is64Bit()) {
1396       if (ValVT == MVT::x86mmx) {
1397         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1398           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1399           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1400                                   ValToCopy);
1401           // If we don't have SSE2 available, convert to v4f32 so the generated
1402           // register is legal.
1403           if (!Subtarget->hasSSE2())
1404             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1405         }
1406       }
1407     }
1408
1409     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1410     Flag = Chain.getValue(1);
1411   }
1412
1413   // The x86-64 ABI for returning structs by value requires that we copy
1414   // the sret argument into %rax for the return. We saved the argument into
1415   // a virtual register in the entry block, so now we copy the value out
1416   // and into %rax.
1417   if (Subtarget->is64Bit() &&
1418       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1419     MachineFunction &MF = DAG.getMachineFunction();
1420     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1421     unsigned Reg = FuncInfo->getSRetReturnReg();
1422     assert(Reg &&
1423            "SRetReturnReg should have been set in LowerFormalArguments().");
1424     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1425
1426     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1427     Flag = Chain.getValue(1);
1428
1429     // RAX now acts like a return value.
1430     MRI.addLiveOut(X86::RAX);
1431   }
1432
1433   RetOps[0] = Chain;  // Update chain.
1434
1435   // Add the flag if we have it.
1436   if (Flag.getNode())
1437     RetOps.push_back(Flag);
1438
1439   return DAG.getNode(X86ISD::RET_FLAG, dl,
1440                      MVT::Other, &RetOps[0], RetOps.size());
1441 }
1442
1443 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1444   if (N->getNumValues() != 1)
1445     return false;
1446   if (!N->hasNUsesOfValue(1, 0))
1447     return false;
1448
1449   SDNode *Copy = *N->use_begin();
1450   if (Copy->getOpcode() != ISD::CopyToReg &&
1451       Copy->getOpcode() != ISD::FP_EXTEND)
1452     return false;
1453
1454   bool HasRet = false;
1455   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1456        UI != UE; ++UI) {
1457     if (UI->getOpcode() != X86ISD::RET_FLAG)
1458       return false;
1459     HasRet = true;
1460   }
1461
1462   return HasRet;
1463 }
1464
1465 EVT
1466 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1467                                             ISD::NodeType ExtendKind) const {
1468   MVT ReturnMVT;
1469   // TODO: Is this also valid on 32-bit?
1470   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1471     ReturnMVT = MVT::i8;
1472   else
1473     ReturnMVT = MVT::i32;
1474
1475   EVT MinVT = getRegisterType(Context, ReturnMVT);
1476   return VT.bitsLT(MinVT) ? MinVT : VT;
1477 }
1478
1479 /// LowerCallResult - Lower the result values of a call into the
1480 /// appropriate copies out of appropriate physical registers.
1481 ///
1482 SDValue
1483 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1484                                    CallingConv::ID CallConv, bool isVarArg,
1485                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1486                                    DebugLoc dl, SelectionDAG &DAG,
1487                                    SmallVectorImpl<SDValue> &InVals) const {
1488
1489   // Assign locations to each value returned by this call.
1490   SmallVector<CCValAssign, 16> RVLocs;
1491   bool Is64Bit = Subtarget->is64Bit();
1492   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1493                  RVLocs, *DAG.getContext());
1494   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1495
1496   // Copy all of the result registers out of their specified physreg.
1497   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1498     CCValAssign &VA = RVLocs[i];
1499     EVT CopyVT = VA.getValVT();
1500
1501     // If this is x86-64, and we disabled SSE, we can't return FP values
1502     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1503         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1504       report_fatal_error("SSE register return with SSE disabled");
1505     }
1506
1507     SDValue Val;
1508
1509     // If this is a call to a function that returns an fp value on the floating
1510     // point stack, we must guarantee the the value is popped from the stack, so
1511     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1512     // if the return value is not used. We use the FpGET_ST0 instructions
1513     // instead.
1514     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1515       // If we prefer to use the value in xmm registers, copy it out as f80 and
1516       // use a truncate to move it from fp stack reg to xmm reg.
1517       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1518       bool isST0 = VA.getLocReg() == X86::ST0;
1519       unsigned Opc = 0;
1520       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1521       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1522       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1523       SDValue Ops[] = { Chain, InFlag };
1524       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1525                                          Ops, 2), 1);
1526       Val = Chain.getValue(0);
1527
1528       // Round the f80 to the right size, which also moves it to the appropriate
1529       // xmm register.
1530       if (CopyVT != VA.getValVT())
1531         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1532                           // This truncation won't change the value.
1533                           DAG.getIntPtrConstant(1));
1534     } else {
1535       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1536                                  CopyVT, InFlag).getValue(1);
1537       Val = Chain.getValue(0);
1538     }
1539     InFlag = Chain.getValue(2);
1540     InVals.push_back(Val);
1541   }
1542
1543   return Chain;
1544 }
1545
1546
1547 //===----------------------------------------------------------------------===//
1548 //                C & StdCall & Fast Calling Convention implementation
1549 //===----------------------------------------------------------------------===//
1550 //  StdCall calling convention seems to be standard for many Windows' API
1551 //  routines and around. It differs from C calling convention just a little:
1552 //  callee should clean up the stack, not caller. Symbols should be also
1553 //  decorated in some fancy way :) It doesn't support any vector arguments.
1554 //  For info on fast calling convention see Fast Calling Convention (tail call)
1555 //  implementation LowerX86_32FastCCCallTo.
1556
1557 /// CallIsStructReturn - Determines whether a call uses struct return
1558 /// semantics.
1559 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1560   if (Outs.empty())
1561     return false;
1562
1563   return Outs[0].Flags.isSRet();
1564 }
1565
1566 /// ArgsAreStructReturn - Determines whether a function uses struct
1567 /// return semantics.
1568 static bool
1569 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1570   if (Ins.empty())
1571     return false;
1572
1573   return Ins[0].Flags.isSRet();
1574 }
1575
1576 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1577 /// by "Src" to address "Dst" with size and alignment information specified by
1578 /// the specific parameter attribute. The copy will be passed as a byval
1579 /// function parameter.
1580 static SDValue
1581 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1582                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1583                           DebugLoc dl) {
1584   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1585
1586   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1587                        /*isVolatile*/false, /*AlwaysInline=*/true,
1588                        MachinePointerInfo(), MachinePointerInfo());
1589 }
1590
1591 /// IsTailCallConvention - Return true if the calling convention is one that
1592 /// supports tail call optimization.
1593 static bool IsTailCallConvention(CallingConv::ID CC) {
1594   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1595 }
1596
1597 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1598   if (!CI->isTailCall())
1599     return false;
1600
1601   CallSite CS(CI);
1602   CallingConv::ID CalleeCC = CS.getCallingConv();
1603   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1604     return false;
1605
1606   return true;
1607 }
1608
1609 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1610 /// a tailcall target by changing its ABI.
1611 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1612   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1613 }
1614
1615 SDValue
1616 X86TargetLowering::LowerMemArgument(SDValue Chain,
1617                                     CallingConv::ID CallConv,
1618                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1619                                     DebugLoc dl, SelectionDAG &DAG,
1620                                     const CCValAssign &VA,
1621                                     MachineFrameInfo *MFI,
1622                                     unsigned i) const {
1623   // Create the nodes corresponding to a load from this parameter slot.
1624   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1625   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1626   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1627   EVT ValVT;
1628
1629   // If value is passed by pointer we have address passed instead of the value
1630   // itself.
1631   if (VA.getLocInfo() == CCValAssign::Indirect)
1632     ValVT = VA.getLocVT();
1633   else
1634     ValVT = VA.getValVT();
1635
1636   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1637   // changed with more analysis.
1638   // In case of tail call optimization mark all arguments mutable. Since they
1639   // could be overwritten by lowering of arguments in case of a tail call.
1640   if (Flags.isByVal()) {
1641     unsigned Bytes = Flags.getByValSize();
1642     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1643     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1644     return DAG.getFrameIndex(FI, getPointerTy());
1645   } else {
1646     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1647                                     VA.getLocMemOffset(), isImmutable);
1648     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1649     return DAG.getLoad(ValVT, dl, Chain, FIN,
1650                        MachinePointerInfo::getFixedStack(FI),
1651                        false, false, 0);
1652   }
1653 }
1654
1655 SDValue
1656 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1657                                         CallingConv::ID CallConv,
1658                                         bool isVarArg,
1659                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1660                                         DebugLoc dl,
1661                                         SelectionDAG &DAG,
1662                                         SmallVectorImpl<SDValue> &InVals)
1663                                           const {
1664   MachineFunction &MF = DAG.getMachineFunction();
1665   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1666
1667   const Function* Fn = MF.getFunction();
1668   if (Fn->hasExternalLinkage() &&
1669       Subtarget->isTargetCygMing() &&
1670       Fn->getName() == "main")
1671     FuncInfo->setForceFramePointer(true);
1672
1673   MachineFrameInfo *MFI = MF.getFrameInfo();
1674   bool Is64Bit = Subtarget->is64Bit();
1675   bool IsWin64 = Subtarget->isTargetWin64();
1676
1677   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1678          "Var args not supported with calling convention fastcc or ghc");
1679
1680   // Assign locations to all of the incoming arguments.
1681   SmallVector<CCValAssign, 16> ArgLocs;
1682   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1683                  ArgLocs, *DAG.getContext());
1684
1685   // Allocate shadow area for Win64
1686   if (IsWin64) {
1687     CCInfo.AllocateStack(32, 8);
1688   }
1689
1690   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1691
1692   unsigned LastVal = ~0U;
1693   SDValue ArgValue;
1694   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1695     CCValAssign &VA = ArgLocs[i];
1696     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1697     // places.
1698     assert(VA.getValNo() != LastVal &&
1699            "Don't support value assigned to multiple locs yet");
1700     LastVal = VA.getValNo();
1701
1702     if (VA.isRegLoc()) {
1703       EVT RegVT = VA.getLocVT();
1704       TargetRegisterClass *RC = NULL;
1705       if (RegVT == MVT::i32)
1706         RC = X86::GR32RegisterClass;
1707       else if (Is64Bit && RegVT == MVT::i64)
1708         RC = X86::GR64RegisterClass;
1709       else if (RegVT == MVT::f32)
1710         RC = X86::FR32RegisterClass;
1711       else if (RegVT == MVT::f64)
1712         RC = X86::FR64RegisterClass;
1713       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1714         RC = X86::VR256RegisterClass;
1715       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1716         RC = X86::VR128RegisterClass;
1717       else if (RegVT == MVT::x86mmx)
1718         RC = X86::VR64RegisterClass;
1719       else
1720         llvm_unreachable("Unknown argument type!");
1721
1722       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1723       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1724
1725       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1726       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1727       // right size.
1728       if (VA.getLocInfo() == CCValAssign::SExt)
1729         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1730                                DAG.getValueType(VA.getValVT()));
1731       else if (VA.getLocInfo() == CCValAssign::ZExt)
1732         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1733                                DAG.getValueType(VA.getValVT()));
1734       else if (VA.getLocInfo() == CCValAssign::BCvt)
1735         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1736
1737       if (VA.isExtInLoc()) {
1738         // Handle MMX values passed in XMM regs.
1739         if (RegVT.isVector()) {
1740           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1741                                  ArgValue);
1742         } else
1743           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1744       }
1745     } else {
1746       assert(VA.isMemLoc());
1747       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1748     }
1749
1750     // If value is passed via pointer - do a load.
1751     if (VA.getLocInfo() == CCValAssign::Indirect)
1752       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1753                              MachinePointerInfo(), false, false, 0);
1754
1755     InVals.push_back(ArgValue);
1756   }
1757
1758   // The x86-64 ABI for returning structs by value requires that we copy
1759   // the sret argument into %rax for the return. Save the argument into
1760   // a virtual register so that we can access it from the return points.
1761   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1762     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1763     unsigned Reg = FuncInfo->getSRetReturnReg();
1764     if (!Reg) {
1765       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1766       FuncInfo->setSRetReturnReg(Reg);
1767     }
1768     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1769     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1770   }
1771
1772   unsigned StackSize = CCInfo.getNextStackOffset();
1773   // Align stack specially for tail calls.
1774   if (FuncIsMadeTailCallSafe(CallConv))
1775     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1776
1777   // If the function takes variable number of arguments, make a frame index for
1778   // the start of the first vararg value... for expansion of llvm.va_start.
1779   if (isVarArg) {
1780     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1781                     CallConv != CallingConv::X86_ThisCall)) {
1782       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1783     }
1784     if (Is64Bit) {
1785       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1786
1787       // FIXME: We should really autogenerate these arrays
1788       static const unsigned GPR64ArgRegsWin64[] = {
1789         X86::RCX, X86::RDX, X86::R8,  X86::R9
1790       };
1791       static const unsigned GPR64ArgRegs64Bit[] = {
1792         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1793       };
1794       static const unsigned XMMArgRegs64Bit[] = {
1795         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1796         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1797       };
1798       const unsigned *GPR64ArgRegs;
1799       unsigned NumXMMRegs = 0;
1800
1801       if (IsWin64) {
1802         // The XMM registers which might contain var arg parameters are shadowed
1803         // in their paired GPR.  So we only need to save the GPR to their home
1804         // slots.
1805         TotalNumIntRegs = 4;
1806         GPR64ArgRegs = GPR64ArgRegsWin64;
1807       } else {
1808         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1809         GPR64ArgRegs = GPR64ArgRegs64Bit;
1810
1811         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1812       }
1813       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1814                                                        TotalNumIntRegs);
1815
1816       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1817       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1818              "SSE register cannot be used when SSE is disabled!");
1819       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1820              "SSE register cannot be used when SSE is disabled!");
1821       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1822         // Kernel mode asks for SSE to be disabled, so don't push them
1823         // on the stack.
1824         TotalNumXMMRegs = 0;
1825
1826       if (IsWin64) {
1827         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1828         // Get to the caller-allocated home save location.  Add 8 to account
1829         // for the return address.
1830         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1831         FuncInfo->setRegSaveFrameIndex(
1832           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1833         // Fixup to set vararg frame on shadow area (4 x i64).
1834         if (NumIntRegs < 4)
1835           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1836       } else {
1837         // For X86-64, if there are vararg parameters that are passed via
1838         // registers, then we must store them to their spots on the stack so they
1839         // may be loaded by deferencing the result of va_next.
1840         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1841         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1842         FuncInfo->setRegSaveFrameIndex(
1843           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1844                                false));
1845       }
1846
1847       // Store the integer parameter registers.
1848       SmallVector<SDValue, 8> MemOps;
1849       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1850                                         getPointerTy());
1851       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1852       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1853         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1854                                   DAG.getIntPtrConstant(Offset));
1855         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1856                                      X86::GR64RegisterClass);
1857         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1858         SDValue Store =
1859           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1860                        MachinePointerInfo::getFixedStack(
1861                          FuncInfo->getRegSaveFrameIndex(), Offset),
1862                        false, false, 0);
1863         MemOps.push_back(Store);
1864         Offset += 8;
1865       }
1866
1867       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1868         // Now store the XMM (fp + vector) parameter registers.
1869         SmallVector<SDValue, 11> SaveXMMOps;
1870         SaveXMMOps.push_back(Chain);
1871
1872         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1873         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1874         SaveXMMOps.push_back(ALVal);
1875
1876         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1877                                FuncInfo->getRegSaveFrameIndex()));
1878         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1879                                FuncInfo->getVarArgsFPOffset()));
1880
1881         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1882           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1883                                        X86::VR128RegisterClass);
1884           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1885           SaveXMMOps.push_back(Val);
1886         }
1887         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1888                                      MVT::Other,
1889                                      &SaveXMMOps[0], SaveXMMOps.size()));
1890       }
1891
1892       if (!MemOps.empty())
1893         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1894                             &MemOps[0], MemOps.size());
1895     }
1896   }
1897
1898   // Some CCs need callee pop.
1899   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1900     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1901   } else {
1902     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1903     // If this is an sret function, the return should pop the hidden pointer.
1904     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1905       FuncInfo->setBytesToPopOnReturn(4);
1906   }
1907
1908   if (!Is64Bit) {
1909     // RegSaveFrameIndex is X86-64 only.
1910     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1911     if (CallConv == CallingConv::X86_FastCall ||
1912         CallConv == CallingConv::X86_ThisCall)
1913       // fastcc functions can't have varargs.
1914       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1915   }
1916
1917   return Chain;
1918 }
1919
1920 SDValue
1921 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1922                                     SDValue StackPtr, SDValue Arg,
1923                                     DebugLoc dl, SelectionDAG &DAG,
1924                                     const CCValAssign &VA,
1925                                     ISD::ArgFlagsTy Flags) const {
1926   unsigned LocMemOffset = VA.getLocMemOffset();
1927   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1928   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1929   if (Flags.isByVal())
1930     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1931
1932   return DAG.getStore(Chain, dl, Arg, PtrOff,
1933                       MachinePointerInfo::getStack(LocMemOffset),
1934                       false, false, 0);
1935 }
1936
1937 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1938 /// optimization is performed and it is required.
1939 SDValue
1940 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1941                                            SDValue &OutRetAddr, SDValue Chain,
1942                                            bool IsTailCall, bool Is64Bit,
1943                                            int FPDiff, DebugLoc dl) const {
1944   // Adjust the Return address stack slot.
1945   EVT VT = getPointerTy();
1946   OutRetAddr = getReturnAddressFrameIndex(DAG);
1947
1948   // Load the "old" Return address.
1949   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1950                            false, false, 0);
1951   return SDValue(OutRetAddr.getNode(), 1);
1952 }
1953
1954 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1955 /// optimization is performed and it is required (FPDiff!=0).
1956 static SDValue
1957 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1958                          SDValue Chain, SDValue RetAddrFrIdx,
1959                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1960   // Store the return address to the appropriate stack slot.
1961   if (!FPDiff) return Chain;
1962   // Calculate the new stack slot for the return address.
1963   int SlotSize = Is64Bit ? 8 : 4;
1964   int NewReturnAddrFI =
1965     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1966   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1967   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1968   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1969                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1970                        false, false, 0);
1971   return Chain;
1972 }
1973
1974 SDValue
1975 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1976                              CallingConv::ID CallConv, bool isVarArg,
1977                              bool &isTailCall,
1978                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1979                              const SmallVectorImpl<SDValue> &OutVals,
1980                              const SmallVectorImpl<ISD::InputArg> &Ins,
1981                              DebugLoc dl, SelectionDAG &DAG,
1982                              SmallVectorImpl<SDValue> &InVals) const {
1983   MachineFunction &MF = DAG.getMachineFunction();
1984   bool Is64Bit        = Subtarget->is64Bit();
1985   bool IsWin64        = Subtarget->isTargetWin64();
1986   bool IsStructRet    = CallIsStructReturn(Outs);
1987   bool IsSibcall      = false;
1988
1989   if (isTailCall) {
1990     // Check if it's really possible to do a tail call.
1991     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1992                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1993                                                    Outs, OutVals, Ins, DAG);
1994
1995     // Sibcalls are automatically detected tailcalls which do not require
1996     // ABI changes.
1997     if (!GuaranteedTailCallOpt && isTailCall)
1998       IsSibcall = true;
1999
2000     if (isTailCall)
2001       ++NumTailCalls;
2002   }
2003
2004   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2005          "Var args not supported with calling convention fastcc or ghc");
2006
2007   // Analyze operands of the call, assigning locations to each operand.
2008   SmallVector<CCValAssign, 16> ArgLocs;
2009   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2010                  ArgLocs, *DAG.getContext());
2011
2012   // Allocate shadow area for Win64
2013   if (IsWin64) {
2014     CCInfo.AllocateStack(32, 8);
2015   }
2016
2017   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2018
2019   // Get a count of how many bytes are to be pushed on the stack.
2020   unsigned NumBytes = CCInfo.getNextStackOffset();
2021   if (IsSibcall)
2022     // This is a sibcall. The memory operands are available in caller's
2023     // own caller's stack.
2024     NumBytes = 0;
2025   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2026     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2027
2028   int FPDiff = 0;
2029   if (isTailCall && !IsSibcall) {
2030     // Lower arguments at fp - stackoffset + fpdiff.
2031     unsigned NumBytesCallerPushed =
2032       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2033     FPDiff = NumBytesCallerPushed - NumBytes;
2034
2035     // Set the delta of movement of the returnaddr stackslot.
2036     // But only set if delta is greater than previous delta.
2037     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2038       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2039   }
2040
2041   if (!IsSibcall)
2042     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2043
2044   SDValue RetAddrFrIdx;
2045   // Load return address for tail calls.
2046   if (isTailCall && FPDiff)
2047     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2048                                     Is64Bit, FPDiff, dl);
2049
2050   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2051   SmallVector<SDValue, 8> MemOpChains;
2052   SDValue StackPtr;
2053
2054   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2055   // of tail call optimization arguments are handle later.
2056   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2057     CCValAssign &VA = ArgLocs[i];
2058     EVT RegVT = VA.getLocVT();
2059     SDValue Arg = OutVals[i];
2060     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2061     bool isByVal = Flags.isByVal();
2062
2063     // Promote the value if needed.
2064     switch (VA.getLocInfo()) {
2065     default: llvm_unreachable("Unknown loc info!");
2066     case CCValAssign::Full: break;
2067     case CCValAssign::SExt:
2068       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2069       break;
2070     case CCValAssign::ZExt:
2071       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2072       break;
2073     case CCValAssign::AExt:
2074       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2075         // Special case: passing MMX values in XMM registers.
2076         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2077         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2078         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2079       } else
2080         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2081       break;
2082     case CCValAssign::BCvt:
2083       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2084       break;
2085     case CCValAssign::Indirect: {
2086       // Store the argument.
2087       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2088       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2089       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2090                            MachinePointerInfo::getFixedStack(FI),
2091                            false, false, 0);
2092       Arg = SpillSlot;
2093       break;
2094     }
2095     }
2096
2097     if (VA.isRegLoc()) {
2098       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2099       if (isVarArg && IsWin64) {
2100         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2101         // shadow reg if callee is a varargs function.
2102         unsigned ShadowReg = 0;
2103         switch (VA.getLocReg()) {
2104         case X86::XMM0: ShadowReg = X86::RCX; break;
2105         case X86::XMM1: ShadowReg = X86::RDX; break;
2106         case X86::XMM2: ShadowReg = X86::R8; break;
2107         case X86::XMM3: ShadowReg = X86::R9; break;
2108         }
2109         if (ShadowReg)
2110           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2111       }
2112     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2113       assert(VA.isMemLoc());
2114       if (StackPtr.getNode() == 0)
2115         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2116       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2117                                              dl, DAG, VA, Flags));
2118     }
2119   }
2120
2121   if (!MemOpChains.empty())
2122     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2123                         &MemOpChains[0], MemOpChains.size());
2124
2125   // Build a sequence of copy-to-reg nodes chained together with token chain
2126   // and flag operands which copy the outgoing args into registers.
2127   SDValue InFlag;
2128   // Tail call byval lowering might overwrite argument registers so in case of
2129   // tail call optimization the copies to registers are lowered later.
2130   if (!isTailCall)
2131     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2132       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2133                                RegsToPass[i].second, InFlag);
2134       InFlag = Chain.getValue(1);
2135     }
2136
2137   if (Subtarget->isPICStyleGOT()) {
2138     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2139     // GOT pointer.
2140     if (!isTailCall) {
2141       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2142                                DAG.getNode(X86ISD::GlobalBaseReg,
2143                                            DebugLoc(), getPointerTy()),
2144                                InFlag);
2145       InFlag = Chain.getValue(1);
2146     } else {
2147       // If we are tail calling and generating PIC/GOT style code load the
2148       // address of the callee into ECX. The value in ecx is used as target of
2149       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2150       // for tail calls on PIC/GOT architectures. Normally we would just put the
2151       // address of GOT into ebx and then call target@PLT. But for tail calls
2152       // ebx would be restored (since ebx is callee saved) before jumping to the
2153       // target@PLT.
2154
2155       // Note: The actual moving to ECX is done further down.
2156       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2157       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2158           !G->getGlobal()->hasProtectedVisibility())
2159         Callee = LowerGlobalAddress(Callee, DAG);
2160       else if (isa<ExternalSymbolSDNode>(Callee))
2161         Callee = LowerExternalSymbol(Callee, DAG);
2162     }
2163   }
2164
2165   if (Is64Bit && isVarArg && !IsWin64) {
2166     // From AMD64 ABI document:
2167     // For calls that may call functions that use varargs or stdargs
2168     // (prototype-less calls or calls to functions containing ellipsis (...) in
2169     // the declaration) %al is used as hidden argument to specify the number
2170     // of SSE registers used. The contents of %al do not need to match exactly
2171     // the number of registers, but must be an ubound on the number of SSE
2172     // registers used and is in the range 0 - 8 inclusive.
2173
2174     // Count the number of XMM registers allocated.
2175     static const unsigned XMMArgRegs[] = {
2176       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2177       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2178     };
2179     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2180     assert((Subtarget->hasXMM() || !NumXMMRegs)
2181            && "SSE registers cannot be used when SSE is disabled");
2182
2183     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2184                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2185     InFlag = Chain.getValue(1);
2186   }
2187
2188
2189   // For tail calls lower the arguments to the 'real' stack slot.
2190   if (isTailCall) {
2191     // Force all the incoming stack arguments to be loaded from the stack
2192     // before any new outgoing arguments are stored to the stack, because the
2193     // outgoing stack slots may alias the incoming argument stack slots, and
2194     // the alias isn't otherwise explicit. This is slightly more conservative
2195     // than necessary, because it means that each store effectively depends
2196     // on every argument instead of just those arguments it would clobber.
2197     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2198
2199     SmallVector<SDValue, 8> MemOpChains2;
2200     SDValue FIN;
2201     int FI = 0;
2202     // Do not flag preceding copytoreg stuff together with the following stuff.
2203     InFlag = SDValue();
2204     if (GuaranteedTailCallOpt) {
2205       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2206         CCValAssign &VA = ArgLocs[i];
2207         if (VA.isRegLoc())
2208           continue;
2209         assert(VA.isMemLoc());
2210         SDValue Arg = OutVals[i];
2211         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2212         // Create frame index.
2213         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2214         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2215         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2216         FIN = DAG.getFrameIndex(FI, getPointerTy());
2217
2218         if (Flags.isByVal()) {
2219           // Copy relative to framepointer.
2220           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2221           if (StackPtr.getNode() == 0)
2222             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2223                                           getPointerTy());
2224           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2225
2226           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2227                                                            ArgChain,
2228                                                            Flags, DAG, dl));
2229         } else {
2230           // Store relative to framepointer.
2231           MemOpChains2.push_back(
2232             DAG.getStore(ArgChain, dl, Arg, FIN,
2233                          MachinePointerInfo::getFixedStack(FI),
2234                          false, false, 0));
2235         }
2236       }
2237     }
2238
2239     if (!MemOpChains2.empty())
2240       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2241                           &MemOpChains2[0], MemOpChains2.size());
2242
2243     // Copy arguments to their registers.
2244     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2245       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2246                                RegsToPass[i].second, InFlag);
2247       InFlag = Chain.getValue(1);
2248     }
2249     InFlag =SDValue();
2250
2251     // Store the return address to the appropriate stack slot.
2252     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2253                                      FPDiff, dl);
2254   }
2255
2256   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2257     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2258     // In the 64-bit large code model, we have to make all calls
2259     // through a register, since the call instruction's 32-bit
2260     // pc-relative offset may not be large enough to hold the whole
2261     // address.
2262   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2263     // If the callee is a GlobalAddress node (quite common, every direct call
2264     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2265     // it.
2266
2267     // We should use extra load for direct calls to dllimported functions in
2268     // non-JIT mode.
2269     const GlobalValue *GV = G->getGlobal();
2270     if (!GV->hasDLLImportLinkage()) {
2271       unsigned char OpFlags = 0;
2272
2273       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2274       // external symbols most go through the PLT in PIC mode.  If the symbol
2275       // has hidden or protected visibility, or if it is static or local, then
2276       // we don't need to use the PLT - we can directly call it.
2277       if (Subtarget->isTargetELF() &&
2278           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2279           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2280         OpFlags = X86II::MO_PLT;
2281       } else if (Subtarget->isPICStyleStubAny() &&
2282                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2283                  (!Subtarget->getTargetTriple().isMacOSX() ||
2284                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2285         // PC-relative references to external symbols should go through $stub,
2286         // unless we're building with the leopard linker or later, which
2287         // automatically synthesizes these stubs.
2288         OpFlags = X86II::MO_DARWIN_STUB;
2289       }
2290
2291       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2292                                           G->getOffset(), OpFlags);
2293     }
2294   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2295     unsigned char OpFlags = 0;
2296
2297     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2298     // external symbols should go through the PLT.
2299     if (Subtarget->isTargetELF() &&
2300         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2301       OpFlags = X86II::MO_PLT;
2302     } else if (Subtarget->isPICStyleStubAny() &&
2303                (!Subtarget->getTargetTriple().isMacOSX() ||
2304                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2305       // PC-relative references to external symbols should go through $stub,
2306       // unless we're building with the leopard linker or later, which
2307       // automatically synthesizes these stubs.
2308       OpFlags = X86II::MO_DARWIN_STUB;
2309     }
2310
2311     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2312                                          OpFlags);
2313   }
2314
2315   // Returns a chain & a flag for retval copy to use.
2316   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2317   SmallVector<SDValue, 8> Ops;
2318
2319   if (!IsSibcall && isTailCall) {
2320     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2321                            DAG.getIntPtrConstant(0, true), InFlag);
2322     InFlag = Chain.getValue(1);
2323   }
2324
2325   Ops.push_back(Chain);
2326   Ops.push_back(Callee);
2327
2328   if (isTailCall)
2329     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2330
2331   // Add argument registers to the end of the list so that they are known live
2332   // into the call.
2333   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2334     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2335                                   RegsToPass[i].second.getValueType()));
2336
2337   // Add an implicit use GOT pointer in EBX.
2338   if (!isTailCall && Subtarget->isPICStyleGOT())
2339     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2340
2341   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2342   if (Is64Bit && isVarArg && !IsWin64)
2343     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2344
2345   if (InFlag.getNode())
2346     Ops.push_back(InFlag);
2347
2348   if (isTailCall) {
2349     // We used to do:
2350     //// If this is the first return lowered for this function, add the regs
2351     //// to the liveout set for the function.
2352     // This isn't right, although it's probably harmless on x86; liveouts
2353     // should be computed from returns not tail calls.  Consider a void
2354     // function making a tail call to a function returning int.
2355     return DAG.getNode(X86ISD::TC_RETURN, dl,
2356                        NodeTys, &Ops[0], Ops.size());
2357   }
2358
2359   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2360   InFlag = Chain.getValue(1);
2361
2362   // Create the CALLSEQ_END node.
2363   unsigned NumBytesForCalleeToPush;
2364   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2365     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2366   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2367     // If this is a call to a struct-return function, the callee
2368     // pops the hidden struct pointer, so we have to push it back.
2369     // This is common for Darwin/X86, Linux & Mingw32 targets.
2370     NumBytesForCalleeToPush = 4;
2371   else
2372     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2373
2374   // Returns a flag for retval copy to use.
2375   if (!IsSibcall) {
2376     Chain = DAG.getCALLSEQ_END(Chain,
2377                                DAG.getIntPtrConstant(NumBytes, true),
2378                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2379                                                      true),
2380                                InFlag);
2381     InFlag = Chain.getValue(1);
2382   }
2383
2384   // Handle result values, copying them out of physregs into vregs that we
2385   // return.
2386   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2387                          Ins, dl, DAG, InVals);
2388 }
2389
2390
2391 //===----------------------------------------------------------------------===//
2392 //                Fast Calling Convention (tail call) implementation
2393 //===----------------------------------------------------------------------===//
2394
2395 //  Like std call, callee cleans arguments, convention except that ECX is
2396 //  reserved for storing the tail called function address. Only 2 registers are
2397 //  free for argument passing (inreg). Tail call optimization is performed
2398 //  provided:
2399 //                * tailcallopt is enabled
2400 //                * caller/callee are fastcc
2401 //  On X86_64 architecture with GOT-style position independent code only local
2402 //  (within module) calls are supported at the moment.
2403 //  To keep the stack aligned according to platform abi the function
2404 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2405 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2406 //  If a tail called function callee has more arguments than the caller the
2407 //  caller needs to make sure that there is room to move the RETADDR to. This is
2408 //  achieved by reserving an area the size of the argument delta right after the
2409 //  original REtADDR, but before the saved framepointer or the spilled registers
2410 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2411 //  stack layout:
2412 //    arg1
2413 //    arg2
2414 //    RETADDR
2415 //    [ new RETADDR
2416 //      move area ]
2417 //    (possible EBP)
2418 //    ESI
2419 //    EDI
2420 //    local1 ..
2421
2422 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2423 /// for a 16 byte align requirement.
2424 unsigned
2425 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2426                                                SelectionDAG& DAG) const {
2427   MachineFunction &MF = DAG.getMachineFunction();
2428   const TargetMachine &TM = MF.getTarget();
2429   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2430   unsigned StackAlignment = TFI.getStackAlignment();
2431   uint64_t AlignMask = StackAlignment - 1;
2432   int64_t Offset = StackSize;
2433   uint64_t SlotSize = TD->getPointerSize();
2434   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2435     // Number smaller than 12 so just add the difference.
2436     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2437   } else {
2438     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2439     Offset = ((~AlignMask) & Offset) + StackAlignment +
2440       (StackAlignment-SlotSize);
2441   }
2442   return Offset;
2443 }
2444
2445 /// MatchingStackOffset - Return true if the given stack call argument is
2446 /// already available in the same position (relatively) of the caller's
2447 /// incoming argument stack.
2448 static
2449 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2450                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2451                          const X86InstrInfo *TII) {
2452   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2453   int FI = INT_MAX;
2454   if (Arg.getOpcode() == ISD::CopyFromReg) {
2455     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2456     if (!TargetRegisterInfo::isVirtualRegister(VR))
2457       return false;
2458     MachineInstr *Def = MRI->getVRegDef(VR);
2459     if (!Def)
2460       return false;
2461     if (!Flags.isByVal()) {
2462       if (!TII->isLoadFromStackSlot(Def, FI))
2463         return false;
2464     } else {
2465       unsigned Opcode = Def->getOpcode();
2466       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2467           Def->getOperand(1).isFI()) {
2468         FI = Def->getOperand(1).getIndex();
2469         Bytes = Flags.getByValSize();
2470       } else
2471         return false;
2472     }
2473   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2474     if (Flags.isByVal())
2475       // ByVal argument is passed in as a pointer but it's now being
2476       // dereferenced. e.g.
2477       // define @foo(%struct.X* %A) {
2478       //   tail call @bar(%struct.X* byval %A)
2479       // }
2480       return false;
2481     SDValue Ptr = Ld->getBasePtr();
2482     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2483     if (!FINode)
2484       return false;
2485     FI = FINode->getIndex();
2486   } else
2487     return false;
2488
2489   assert(FI != INT_MAX);
2490   if (!MFI->isFixedObjectIndex(FI))
2491     return false;
2492   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2493 }
2494
2495 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2496 /// for tail call optimization. Targets which want to do tail call
2497 /// optimization should implement this function.
2498 bool
2499 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2500                                                      CallingConv::ID CalleeCC,
2501                                                      bool isVarArg,
2502                                                      bool isCalleeStructRet,
2503                                                      bool isCallerStructRet,
2504                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2505                                     const SmallVectorImpl<SDValue> &OutVals,
2506                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2507                                                      SelectionDAG& DAG) const {
2508   if (!IsTailCallConvention(CalleeCC) &&
2509       CalleeCC != CallingConv::C)
2510     return false;
2511
2512   // If -tailcallopt is specified, make fastcc functions tail-callable.
2513   const MachineFunction &MF = DAG.getMachineFunction();
2514   const Function *CallerF = DAG.getMachineFunction().getFunction();
2515   CallingConv::ID CallerCC = CallerF->getCallingConv();
2516   bool CCMatch = CallerCC == CalleeCC;
2517
2518   if (GuaranteedTailCallOpt) {
2519     if (IsTailCallConvention(CalleeCC) && CCMatch)
2520       return true;
2521     return false;
2522   }
2523
2524   // Look for obvious safe cases to perform tail call optimization that do not
2525   // require ABI changes. This is what gcc calls sibcall.
2526
2527   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2528   // emit a special epilogue.
2529   if (RegInfo->needsStackRealignment(MF))
2530     return false;
2531
2532   // Also avoid sibcall optimization if either caller or callee uses struct
2533   // return semantics.
2534   if (isCalleeStructRet || isCallerStructRet)
2535     return false;
2536
2537   // Do not sibcall optimize vararg calls unless all arguments are passed via
2538   // registers.
2539   if (isVarArg && !Outs.empty()) {
2540
2541     // Optimizing for varargs on Win64 is unlikely to be safe without
2542     // additional testing.
2543     if (Subtarget->isTargetWin64())
2544       return false;
2545
2546     SmallVector<CCValAssign, 16> ArgLocs;
2547     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2548                    ArgLocs, *DAG.getContext());
2549
2550     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2551     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2552       if (!ArgLocs[i].isRegLoc())
2553         return false;
2554   }
2555
2556   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2557   // Therefore if it's not used by the call it is not safe to optimize this into
2558   // a sibcall.
2559   bool Unused = false;
2560   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2561     if (!Ins[i].Used) {
2562       Unused = true;
2563       break;
2564     }
2565   }
2566   if (Unused) {
2567     SmallVector<CCValAssign, 16> RVLocs;
2568     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2569                    RVLocs, *DAG.getContext());
2570     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2571     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2572       CCValAssign &VA = RVLocs[i];
2573       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2574         return false;
2575     }
2576   }
2577
2578   // If the calling conventions do not match, then we'd better make sure the
2579   // results are returned in the same way as what the caller expects.
2580   if (!CCMatch) {
2581     SmallVector<CCValAssign, 16> RVLocs1;
2582     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2583                     RVLocs1, *DAG.getContext());
2584     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2585
2586     SmallVector<CCValAssign, 16> RVLocs2;
2587     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2588                     RVLocs2, *DAG.getContext());
2589     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2590
2591     if (RVLocs1.size() != RVLocs2.size())
2592       return false;
2593     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2594       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2595         return false;
2596       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2597         return false;
2598       if (RVLocs1[i].isRegLoc()) {
2599         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2600           return false;
2601       } else {
2602         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2603           return false;
2604       }
2605     }
2606   }
2607
2608   // If the callee takes no arguments then go on to check the results of the
2609   // call.
2610   if (!Outs.empty()) {
2611     // Check if stack adjustment is needed. For now, do not do this if any
2612     // argument is passed on the stack.
2613     SmallVector<CCValAssign, 16> ArgLocs;
2614     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2615                    ArgLocs, *DAG.getContext());
2616
2617     // Allocate shadow area for Win64
2618     if (Subtarget->isTargetWin64()) {
2619       CCInfo.AllocateStack(32, 8);
2620     }
2621
2622     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2623     if (CCInfo.getNextStackOffset()) {
2624       MachineFunction &MF = DAG.getMachineFunction();
2625       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2626         return false;
2627
2628       // Check if the arguments are already laid out in the right way as
2629       // the caller's fixed stack objects.
2630       MachineFrameInfo *MFI = MF.getFrameInfo();
2631       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2632       const X86InstrInfo *TII =
2633         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2634       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2635         CCValAssign &VA = ArgLocs[i];
2636         SDValue Arg = OutVals[i];
2637         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2638         if (VA.getLocInfo() == CCValAssign::Indirect)
2639           return false;
2640         if (!VA.isRegLoc()) {
2641           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2642                                    MFI, MRI, TII))
2643             return false;
2644         }
2645       }
2646     }
2647
2648     // If the tailcall address may be in a register, then make sure it's
2649     // possible to register allocate for it. In 32-bit, the call address can
2650     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2651     // callee-saved registers are restored. These happen to be the same
2652     // registers used to pass 'inreg' arguments so watch out for those.
2653     if (!Subtarget->is64Bit() &&
2654         !isa<GlobalAddressSDNode>(Callee) &&
2655         !isa<ExternalSymbolSDNode>(Callee)) {
2656       unsigned NumInRegs = 0;
2657       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2658         CCValAssign &VA = ArgLocs[i];
2659         if (!VA.isRegLoc())
2660           continue;
2661         unsigned Reg = VA.getLocReg();
2662         switch (Reg) {
2663         default: break;
2664         case X86::EAX: case X86::EDX: case X86::ECX:
2665           if (++NumInRegs == 3)
2666             return false;
2667           break;
2668         }
2669       }
2670     }
2671   }
2672
2673   // An stdcall caller is expected to clean up its arguments; the callee
2674   // isn't going to do that.
2675   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2676     return false;
2677
2678   return true;
2679 }
2680
2681 FastISel *
2682 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2683   return X86::createFastISel(funcInfo);
2684 }
2685
2686
2687 //===----------------------------------------------------------------------===//
2688 //                           Other Lowering Hooks
2689 //===----------------------------------------------------------------------===//
2690
2691 static bool MayFoldLoad(SDValue Op) {
2692   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2693 }
2694
2695 static bool MayFoldIntoStore(SDValue Op) {
2696   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2697 }
2698
2699 static bool isTargetShuffle(unsigned Opcode) {
2700   switch(Opcode) {
2701   default: return false;
2702   case X86ISD::PSHUFD:
2703   case X86ISD::PSHUFHW:
2704   case X86ISD::PSHUFLW:
2705   case X86ISD::SHUFPD:
2706   case X86ISD::PALIGN:
2707   case X86ISD::SHUFPS:
2708   case X86ISD::MOVLHPS:
2709   case X86ISD::MOVLHPD:
2710   case X86ISD::MOVHLPS:
2711   case X86ISD::MOVLPS:
2712   case X86ISD::MOVLPD:
2713   case X86ISD::MOVSHDUP:
2714   case X86ISD::MOVSLDUP:
2715   case X86ISD::MOVDDUP:
2716   case X86ISD::MOVSS:
2717   case X86ISD::MOVSD:
2718   case X86ISD::UNPCKLPS:
2719   case X86ISD::UNPCKLPD:
2720   case X86ISD::VUNPCKLPS:
2721   case X86ISD::VUNPCKLPD:
2722   case X86ISD::VUNPCKLPSY:
2723   case X86ISD::VUNPCKLPDY:
2724   case X86ISD::PUNPCKLWD:
2725   case X86ISD::PUNPCKLBW:
2726   case X86ISD::PUNPCKLDQ:
2727   case X86ISD::PUNPCKLQDQ:
2728   case X86ISD::UNPCKHPS:
2729   case X86ISD::UNPCKHPD:
2730   case X86ISD::PUNPCKHWD:
2731   case X86ISD::PUNPCKHBW:
2732   case X86ISD::PUNPCKHDQ:
2733   case X86ISD::PUNPCKHQDQ:
2734     return true;
2735   }
2736   return false;
2737 }
2738
2739 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2740                                                SDValue V1, SelectionDAG &DAG) {
2741   switch(Opc) {
2742   default: llvm_unreachable("Unknown x86 shuffle node");
2743   case X86ISD::MOVSHDUP:
2744   case X86ISD::MOVSLDUP:
2745   case X86ISD::MOVDDUP:
2746     return DAG.getNode(Opc, dl, VT, V1);
2747   }
2748
2749   return SDValue();
2750 }
2751
2752 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2753                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2754   switch(Opc) {
2755   default: llvm_unreachable("Unknown x86 shuffle node");
2756   case X86ISD::PSHUFD:
2757   case X86ISD::PSHUFHW:
2758   case X86ISD::PSHUFLW:
2759     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2760   }
2761
2762   return SDValue();
2763 }
2764
2765 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2766                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2767   switch(Opc) {
2768   default: llvm_unreachable("Unknown x86 shuffle node");
2769   case X86ISD::PALIGN:
2770   case X86ISD::SHUFPD:
2771   case X86ISD::SHUFPS:
2772     return DAG.getNode(Opc, dl, VT, V1, V2,
2773                        DAG.getConstant(TargetMask, MVT::i8));
2774   }
2775   return SDValue();
2776 }
2777
2778 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2779                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2780   switch(Opc) {
2781   default: llvm_unreachable("Unknown x86 shuffle node");
2782   case X86ISD::MOVLHPS:
2783   case X86ISD::MOVLHPD:
2784   case X86ISD::MOVHLPS:
2785   case X86ISD::MOVLPS:
2786   case X86ISD::MOVLPD:
2787   case X86ISD::MOVSS:
2788   case X86ISD::MOVSD:
2789   case X86ISD::UNPCKLPS:
2790   case X86ISD::UNPCKLPD:
2791   case X86ISD::VUNPCKLPS:
2792   case X86ISD::VUNPCKLPD:
2793   case X86ISD::VUNPCKLPSY:
2794   case X86ISD::VUNPCKLPDY:
2795   case X86ISD::PUNPCKLWD:
2796   case X86ISD::PUNPCKLBW:
2797   case X86ISD::PUNPCKLDQ:
2798   case X86ISD::PUNPCKLQDQ:
2799   case X86ISD::UNPCKHPS:
2800   case X86ISD::UNPCKHPD:
2801   case X86ISD::PUNPCKHWD:
2802   case X86ISD::PUNPCKHBW:
2803   case X86ISD::PUNPCKHDQ:
2804   case X86ISD::PUNPCKHQDQ:
2805     return DAG.getNode(Opc, dl, VT, V1, V2);
2806   }
2807   return SDValue();
2808 }
2809
2810 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2811   MachineFunction &MF = DAG.getMachineFunction();
2812   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2813   int ReturnAddrIndex = FuncInfo->getRAIndex();
2814
2815   if (ReturnAddrIndex == 0) {
2816     // Set up a frame object for the return address.
2817     uint64_t SlotSize = TD->getPointerSize();
2818     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2819                                                            false);
2820     FuncInfo->setRAIndex(ReturnAddrIndex);
2821   }
2822
2823   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2824 }
2825
2826
2827 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2828                                        bool hasSymbolicDisplacement) {
2829   // Offset should fit into 32 bit immediate field.
2830   if (!isInt<32>(Offset))
2831     return false;
2832
2833   // If we don't have a symbolic displacement - we don't have any extra
2834   // restrictions.
2835   if (!hasSymbolicDisplacement)
2836     return true;
2837
2838   // FIXME: Some tweaks might be needed for medium code model.
2839   if (M != CodeModel::Small && M != CodeModel::Kernel)
2840     return false;
2841
2842   // For small code model we assume that latest object is 16MB before end of 31
2843   // bits boundary. We may also accept pretty large negative constants knowing
2844   // that all objects are in the positive half of address space.
2845   if (M == CodeModel::Small && Offset < 16*1024*1024)
2846     return true;
2847
2848   // For kernel code model we know that all object resist in the negative half
2849   // of 32bits address space. We may not accept negative offsets, since they may
2850   // be just off and we may accept pretty large positive ones.
2851   if (M == CodeModel::Kernel && Offset > 0)
2852     return true;
2853
2854   return false;
2855 }
2856
2857 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2858 /// specific condition code, returning the condition code and the LHS/RHS of the
2859 /// comparison to make.
2860 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2861                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2862   if (!isFP) {
2863     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2864       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2865         // X > -1   -> X == 0, jump !sign.
2866         RHS = DAG.getConstant(0, RHS.getValueType());
2867         return X86::COND_NS;
2868       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2869         // X < 0   -> X == 0, jump on sign.
2870         return X86::COND_S;
2871       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2872         // X < 1   -> X <= 0
2873         RHS = DAG.getConstant(0, RHS.getValueType());
2874         return X86::COND_LE;
2875       }
2876     }
2877
2878     switch (SetCCOpcode) {
2879     default: llvm_unreachable("Invalid integer condition!");
2880     case ISD::SETEQ:  return X86::COND_E;
2881     case ISD::SETGT:  return X86::COND_G;
2882     case ISD::SETGE:  return X86::COND_GE;
2883     case ISD::SETLT:  return X86::COND_L;
2884     case ISD::SETLE:  return X86::COND_LE;
2885     case ISD::SETNE:  return X86::COND_NE;
2886     case ISD::SETULT: return X86::COND_B;
2887     case ISD::SETUGT: return X86::COND_A;
2888     case ISD::SETULE: return X86::COND_BE;
2889     case ISD::SETUGE: return X86::COND_AE;
2890     }
2891   }
2892
2893   // First determine if it is required or is profitable to flip the operands.
2894
2895   // If LHS is a foldable load, but RHS is not, flip the condition.
2896   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2897       !ISD::isNON_EXTLoad(RHS.getNode())) {
2898     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2899     std::swap(LHS, RHS);
2900   }
2901
2902   switch (SetCCOpcode) {
2903   default: break;
2904   case ISD::SETOLT:
2905   case ISD::SETOLE:
2906   case ISD::SETUGT:
2907   case ISD::SETUGE:
2908     std::swap(LHS, RHS);
2909     break;
2910   }
2911
2912   // On a floating point condition, the flags are set as follows:
2913   // ZF  PF  CF   op
2914   //  0 | 0 | 0 | X > Y
2915   //  0 | 0 | 1 | X < Y
2916   //  1 | 0 | 0 | X == Y
2917   //  1 | 1 | 1 | unordered
2918   switch (SetCCOpcode) {
2919   default: llvm_unreachable("Condcode should be pre-legalized away");
2920   case ISD::SETUEQ:
2921   case ISD::SETEQ:   return X86::COND_E;
2922   case ISD::SETOLT:              // flipped
2923   case ISD::SETOGT:
2924   case ISD::SETGT:   return X86::COND_A;
2925   case ISD::SETOLE:              // flipped
2926   case ISD::SETOGE:
2927   case ISD::SETGE:   return X86::COND_AE;
2928   case ISD::SETUGT:              // flipped
2929   case ISD::SETULT:
2930   case ISD::SETLT:   return X86::COND_B;
2931   case ISD::SETUGE:              // flipped
2932   case ISD::SETULE:
2933   case ISD::SETLE:   return X86::COND_BE;
2934   case ISD::SETONE:
2935   case ISD::SETNE:   return X86::COND_NE;
2936   case ISD::SETUO:   return X86::COND_P;
2937   case ISD::SETO:    return X86::COND_NP;
2938   case ISD::SETOEQ:
2939   case ISD::SETUNE:  return X86::COND_INVALID;
2940   }
2941 }
2942
2943 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2944 /// code. Current x86 isa includes the following FP cmov instructions:
2945 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2946 static bool hasFPCMov(unsigned X86CC) {
2947   switch (X86CC) {
2948   default:
2949     return false;
2950   case X86::COND_B:
2951   case X86::COND_BE:
2952   case X86::COND_E:
2953   case X86::COND_P:
2954   case X86::COND_A:
2955   case X86::COND_AE:
2956   case X86::COND_NE:
2957   case X86::COND_NP:
2958     return true;
2959   }
2960 }
2961
2962 /// isFPImmLegal - Returns true if the target can instruction select the
2963 /// specified FP immediate natively. If false, the legalizer will
2964 /// materialize the FP immediate as a load from a constant pool.
2965 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2966   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2967     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2968       return true;
2969   }
2970   return false;
2971 }
2972
2973 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2974 /// the specified range (L, H].
2975 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2976   return (Val < 0) || (Val >= Low && Val < Hi);
2977 }
2978
2979 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2980 /// specified value.
2981 static bool isUndefOrEqual(int Val, int CmpVal) {
2982   if (Val < 0 || Val == CmpVal)
2983     return true;
2984   return false;
2985 }
2986
2987 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2988 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2989 /// the second operand.
2990 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2991   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2992     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2993   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2994     return (Mask[0] < 2 && Mask[1] < 2);
2995   return false;
2996 }
2997
2998 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2999   SmallVector<int, 8> M;
3000   N->getMask(M);
3001   return ::isPSHUFDMask(M, N->getValueType(0));
3002 }
3003
3004 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3005 /// is suitable for input to PSHUFHW.
3006 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3007   if (VT != MVT::v8i16)
3008     return false;
3009
3010   // Lower quadword copied in order or undef.
3011   for (int i = 0; i != 4; ++i)
3012     if (Mask[i] >= 0 && Mask[i] != i)
3013       return false;
3014
3015   // Upper quadword shuffled.
3016   for (int i = 4; i != 8; ++i)
3017     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3018       return false;
3019
3020   return true;
3021 }
3022
3023 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3024   SmallVector<int, 8> M;
3025   N->getMask(M);
3026   return ::isPSHUFHWMask(M, N->getValueType(0));
3027 }
3028
3029 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3030 /// is suitable for input to PSHUFLW.
3031 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3032   if (VT != MVT::v8i16)
3033     return false;
3034
3035   // Upper quadword copied in order.
3036   for (int i = 4; i != 8; ++i)
3037     if (Mask[i] >= 0 && Mask[i] != i)
3038       return false;
3039
3040   // Lower quadword shuffled.
3041   for (int i = 0; i != 4; ++i)
3042     if (Mask[i] >= 4)
3043       return false;
3044
3045   return true;
3046 }
3047
3048 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3049   SmallVector<int, 8> M;
3050   N->getMask(M);
3051   return ::isPSHUFLWMask(M, N->getValueType(0));
3052 }
3053
3054 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3055 /// is suitable for input to PALIGNR.
3056 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3057                           bool hasSSSE3) {
3058   int i, e = VT.getVectorNumElements();
3059
3060   // Do not handle v2i64 / v2f64 shuffles with palignr.
3061   if (e < 4 || !hasSSSE3)
3062     return false;
3063
3064   for (i = 0; i != e; ++i)
3065     if (Mask[i] >= 0)
3066       break;
3067
3068   // All undef, not a palignr.
3069   if (i == e)
3070     return false;
3071
3072   // Determine if it's ok to perform a palignr with only the LHS, since we
3073   // don't have access to the actual shuffle elements to see if RHS is undef.
3074   bool Unary = Mask[i] < (int)e;
3075   bool NeedsUnary = false;
3076
3077   int s = Mask[i] - i;
3078
3079   // Check the rest of the elements to see if they are consecutive.
3080   for (++i; i != e; ++i) {
3081     int m = Mask[i];
3082     if (m < 0)
3083       continue;
3084
3085     Unary = Unary && (m < (int)e);
3086     NeedsUnary = NeedsUnary || (m < s);
3087
3088     if (NeedsUnary && !Unary)
3089       return false;
3090     if (Unary && m != ((s+i) & (e-1)))
3091       return false;
3092     if (!Unary && m != (s+i))
3093       return false;
3094   }
3095   return true;
3096 }
3097
3098 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3099   SmallVector<int, 8> M;
3100   N->getMask(M);
3101   return ::isPALIGNRMask(M, N->getValueType(0), true);
3102 }
3103
3104 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3105 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3106 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3107   int NumElems = VT.getVectorNumElements();
3108   if (NumElems != 2 && NumElems != 4)
3109     return false;
3110
3111   int Half = NumElems / 2;
3112   for (int i = 0; i < Half; ++i)
3113     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3114       return false;
3115   for (int i = Half; i < NumElems; ++i)
3116     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3117       return false;
3118
3119   return true;
3120 }
3121
3122 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3123   SmallVector<int, 8> M;
3124   N->getMask(M);
3125   return ::isSHUFPMask(M, N->getValueType(0));
3126 }
3127
3128 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3129 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3130 /// half elements to come from vector 1 (which would equal the dest.) and
3131 /// the upper half to come from vector 2.
3132 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3133   int NumElems = VT.getVectorNumElements();
3134
3135   if (NumElems != 2 && NumElems != 4)
3136     return false;
3137
3138   int Half = NumElems / 2;
3139   for (int i = 0; i < Half; ++i)
3140     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3141       return false;
3142   for (int i = Half; i < NumElems; ++i)
3143     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3144       return false;
3145   return true;
3146 }
3147
3148 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3149   SmallVector<int, 8> M;
3150   N->getMask(M);
3151   return isCommutedSHUFPMask(M, N->getValueType(0));
3152 }
3153
3154 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3155 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3156 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3157   if (N->getValueType(0).getVectorNumElements() != 4)
3158     return false;
3159
3160   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3161   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3162          isUndefOrEqual(N->getMaskElt(1), 7) &&
3163          isUndefOrEqual(N->getMaskElt(2), 2) &&
3164          isUndefOrEqual(N->getMaskElt(3), 3);
3165 }
3166
3167 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3168 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3169 /// <2, 3, 2, 3>
3170 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3171   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3172
3173   if (NumElems != 4)
3174     return false;
3175
3176   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3177   isUndefOrEqual(N->getMaskElt(1), 3) &&
3178   isUndefOrEqual(N->getMaskElt(2), 2) &&
3179   isUndefOrEqual(N->getMaskElt(3), 3);
3180 }
3181
3182 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3183 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3184 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3185   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3186
3187   if (NumElems != 2 && NumElems != 4)
3188     return false;
3189
3190   for (unsigned i = 0; i < NumElems/2; ++i)
3191     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3192       return false;
3193
3194   for (unsigned i = NumElems/2; i < NumElems; ++i)
3195     if (!isUndefOrEqual(N->getMaskElt(i), i))
3196       return false;
3197
3198   return true;
3199 }
3200
3201 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3202 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3203 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3204   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3205
3206   if ((NumElems != 2 && NumElems != 4)
3207       || N->getValueType(0).getSizeInBits() > 128)
3208     return false;
3209
3210   for (unsigned i = 0; i < NumElems/2; ++i)
3211     if (!isUndefOrEqual(N->getMaskElt(i), i))
3212       return false;
3213
3214   for (unsigned i = 0; i < NumElems/2; ++i)
3215     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3216       return false;
3217
3218   return true;
3219 }
3220
3221 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3222 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3223 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3224                          bool V2IsSplat = false) {
3225   int NumElts = VT.getVectorNumElements();
3226   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3227     return false;
3228
3229   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3230   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3231   // sections.
3232   unsigned NumSections = VT.getSizeInBits() / 128;
3233   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3234   unsigned NumSectionElts = NumElts / NumSections;
3235
3236   unsigned Start = 0;
3237   unsigned End = NumSectionElts;
3238   for (unsigned s = 0; s < NumSections; ++s) {
3239     for (unsigned i = Start, j = s * NumSectionElts;
3240          i != End;
3241          i += 2, ++j) {
3242       int BitI  = Mask[i];
3243       int BitI1 = Mask[i+1];
3244       if (!isUndefOrEqual(BitI, j))
3245         return false;
3246       if (V2IsSplat) {
3247         if (!isUndefOrEqual(BitI1, NumElts))
3248           return false;
3249       } else {
3250         if (!isUndefOrEqual(BitI1, j + NumElts))
3251           return false;
3252       }
3253     }
3254     // Process the next 128 bits.
3255     Start += NumSectionElts;
3256     End += NumSectionElts;
3257   }
3258
3259   return true;
3260 }
3261
3262 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3263   SmallVector<int, 8> M;
3264   N->getMask(M);
3265   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3266 }
3267
3268 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3269 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3270 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3271                          bool V2IsSplat = false) {
3272   int NumElts = VT.getVectorNumElements();
3273   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3274     return false;
3275
3276   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3277     int BitI  = Mask[i];
3278     int BitI1 = Mask[i+1];
3279     if (!isUndefOrEqual(BitI, j + NumElts/2))
3280       return false;
3281     if (V2IsSplat) {
3282       if (isUndefOrEqual(BitI1, NumElts))
3283         return false;
3284     } else {
3285       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3286         return false;
3287     }
3288   }
3289   return true;
3290 }
3291
3292 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3293   SmallVector<int, 8> M;
3294   N->getMask(M);
3295   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3296 }
3297
3298 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3299 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3300 /// <0, 0, 1, 1>
3301 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3302   int NumElems = VT.getVectorNumElements();
3303   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3304     return false;
3305
3306   // Handle vector lengths > 128 bits.  Define a "section" as a set of
3307   // 128 bits.  AVX defines UNPCK* to operate independently on 128-bit
3308   // sections.
3309   unsigned NumSections = VT.getSizeInBits() / 128;
3310   if (NumSections == 0 ) NumSections = 1;  // Handle MMX
3311   unsigned NumSectionElts = NumElems / NumSections;
3312
3313   for (unsigned s = 0; s < NumSections; ++s) {
3314     for (unsigned i = s * NumSectionElts, j = s * NumSectionElts;
3315          i != NumSectionElts * (s + 1);
3316          i += 2, ++j) {
3317       int BitI  = Mask[i];
3318       int BitI1 = Mask[i+1];
3319
3320       if (!isUndefOrEqual(BitI, j))
3321         return false;
3322       if (!isUndefOrEqual(BitI1, j))
3323         return false;
3324     }
3325   }
3326
3327   return true;
3328 }
3329
3330 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3331   SmallVector<int, 8> M;
3332   N->getMask(M);
3333   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3334 }
3335
3336 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3337 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3338 /// <2, 2, 3, 3>
3339 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3340   int NumElems = VT.getVectorNumElements();
3341   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3342     return false;
3343
3344   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3345     int BitI  = Mask[i];
3346     int BitI1 = Mask[i+1];
3347     if (!isUndefOrEqual(BitI, j))
3348       return false;
3349     if (!isUndefOrEqual(BitI1, j))
3350       return false;
3351   }
3352   return true;
3353 }
3354
3355 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3356   SmallVector<int, 8> M;
3357   N->getMask(M);
3358   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3359 }
3360
3361 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3362 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3363 /// MOVSD, and MOVD, i.e. setting the lowest element.
3364 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3365   if (VT.getVectorElementType().getSizeInBits() < 32)
3366     return false;
3367
3368   int NumElts = VT.getVectorNumElements();
3369
3370   if (!isUndefOrEqual(Mask[0], NumElts))
3371     return false;
3372
3373   for (int i = 1; i < NumElts; ++i)
3374     if (!isUndefOrEqual(Mask[i], i))
3375       return false;
3376
3377   return true;
3378 }
3379
3380 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3381   SmallVector<int, 8> M;
3382   N->getMask(M);
3383   return ::isMOVLMask(M, N->getValueType(0));
3384 }
3385
3386 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3387 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3388 /// element of vector 2 and the other elements to come from vector 1 in order.
3389 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3390                                bool V2IsSplat = false, bool V2IsUndef = false) {
3391   int NumOps = VT.getVectorNumElements();
3392   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3393     return false;
3394
3395   if (!isUndefOrEqual(Mask[0], 0))
3396     return false;
3397
3398   for (int i = 1; i < NumOps; ++i)
3399     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3400           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3401           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3402       return false;
3403
3404   return true;
3405 }
3406
3407 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3408                            bool V2IsUndef = false) {
3409   SmallVector<int, 8> M;
3410   N->getMask(M);
3411   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3412 }
3413
3414 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3415 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3416 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3417   if (N->getValueType(0).getVectorNumElements() != 4)
3418     return false;
3419
3420   // Expect 1, 1, 3, 3
3421   for (unsigned i = 0; i < 2; ++i) {
3422     int Elt = N->getMaskElt(i);
3423     if (Elt >= 0 && Elt != 1)
3424       return false;
3425   }
3426
3427   bool HasHi = false;
3428   for (unsigned i = 2; i < 4; ++i) {
3429     int Elt = N->getMaskElt(i);
3430     if (Elt >= 0 && Elt != 3)
3431       return false;
3432     if (Elt == 3)
3433       HasHi = true;
3434   }
3435   // Don't use movshdup if it can be done with a shufps.
3436   // FIXME: verify that matching u, u, 3, 3 is what we want.
3437   return HasHi;
3438 }
3439
3440 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3442 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3443   if (N->getValueType(0).getVectorNumElements() != 4)
3444     return false;
3445
3446   // Expect 0, 0, 2, 2
3447   for (unsigned i = 0; i < 2; ++i)
3448     if (N->getMaskElt(i) > 0)
3449       return false;
3450
3451   bool HasHi = false;
3452   for (unsigned i = 2; i < 4; ++i) {
3453     int Elt = N->getMaskElt(i);
3454     if (Elt >= 0 && Elt != 2)
3455       return false;
3456     if (Elt == 2)
3457       HasHi = true;
3458   }
3459   // Don't use movsldup if it can be done with a shufps.
3460   return HasHi;
3461 }
3462
3463 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3465 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3466   int e = N->getValueType(0).getVectorNumElements() / 2;
3467
3468   for (int i = 0; i < e; ++i)
3469     if (!isUndefOrEqual(N->getMaskElt(i), i))
3470       return false;
3471   for (int i = 0; i < e; ++i)
3472     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3473       return false;
3474   return true;
3475 }
3476
3477 /// isVEXTRACTF128Index - Return true if the specified
3478 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3479 /// suitable for input to VEXTRACTF128.
3480 bool X86::isVEXTRACTF128Index(SDNode *N) {
3481   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3482     return false;
3483
3484   // The index should be aligned on a 128-bit boundary.
3485   uint64_t Index =
3486     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3487
3488   unsigned VL = N->getValueType(0).getVectorNumElements();
3489   unsigned VBits = N->getValueType(0).getSizeInBits();
3490   unsigned ElSize = VBits / VL;
3491   bool Result = (Index * ElSize) % 128 == 0;
3492
3493   return Result;
3494 }
3495
3496 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3497 /// operand specifies a subvector insert that is suitable for input to
3498 /// VINSERTF128.
3499 bool X86::isVINSERTF128Index(SDNode *N) {
3500   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3501     return false;
3502
3503   // The index should be aligned on a 128-bit boundary.
3504   uint64_t Index =
3505     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3506
3507   unsigned VL = N->getValueType(0).getVectorNumElements();
3508   unsigned VBits = N->getValueType(0).getSizeInBits();
3509   unsigned ElSize = VBits / VL;
3510   bool Result = (Index * ElSize) % 128 == 0;
3511
3512   return Result;
3513 }
3514
3515 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3516 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3517 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3518   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3519   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3520
3521   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3522   unsigned Mask = 0;
3523   for (int i = 0; i < NumOperands; ++i) {
3524     int Val = SVOp->getMaskElt(NumOperands-i-1);
3525     if (Val < 0) Val = 0;
3526     if (Val >= NumOperands) Val -= NumOperands;
3527     Mask |= Val;
3528     if (i != NumOperands - 1)
3529       Mask <<= Shift;
3530   }
3531   return Mask;
3532 }
3533
3534 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3535 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3536 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3537   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3538   unsigned Mask = 0;
3539   // 8 nodes, but we only care about the last 4.
3540   for (unsigned i = 7; i >= 4; --i) {
3541     int Val = SVOp->getMaskElt(i);
3542     if (Val >= 0)
3543       Mask |= (Val - 4);
3544     if (i != 4)
3545       Mask <<= 2;
3546   }
3547   return Mask;
3548 }
3549
3550 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3551 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3552 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3553   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3554   unsigned Mask = 0;
3555   // 8 nodes, but we only care about the first 4.
3556   for (int i = 3; i >= 0; --i) {
3557     int Val = SVOp->getMaskElt(i);
3558     if (Val >= 0)
3559       Mask |= Val;
3560     if (i != 0)
3561       Mask <<= 2;
3562   }
3563   return Mask;
3564 }
3565
3566 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3567 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3568 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3569   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3570   EVT VVT = N->getValueType(0);
3571   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3572   int Val = 0;
3573
3574   unsigned i, e;
3575   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3576     Val = SVOp->getMaskElt(i);
3577     if (Val >= 0)
3578       break;
3579   }
3580   return (Val - i) * EltSize;
3581 }
3582
3583 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3584 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3585 /// instructions.
3586 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3587   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3588     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3589
3590   uint64_t Index =
3591     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3592
3593   EVT VecVT = N->getOperand(0).getValueType();
3594   EVT ElVT = VecVT.getVectorElementType();
3595
3596   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3597
3598   return Index / NumElemsPerChunk;
3599 }
3600
3601 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3602 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3603 /// instructions.
3604 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3605   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3606     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3607
3608   uint64_t Index =
3609     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3610
3611   EVT VecVT = N->getValueType(0);
3612   EVT ElVT = VecVT.getVectorElementType();
3613
3614   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3615
3616   return Index / NumElemsPerChunk;
3617 }
3618
3619 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3620 /// constant +0.0.
3621 bool X86::isZeroNode(SDValue Elt) {
3622   return ((isa<ConstantSDNode>(Elt) &&
3623            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3624           (isa<ConstantFPSDNode>(Elt) &&
3625            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3626 }
3627
3628 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3629 /// their permute mask.
3630 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3631                                     SelectionDAG &DAG) {
3632   EVT VT = SVOp->getValueType(0);
3633   unsigned NumElems = VT.getVectorNumElements();
3634   SmallVector<int, 8> MaskVec;
3635
3636   for (unsigned i = 0; i != NumElems; ++i) {
3637     int idx = SVOp->getMaskElt(i);
3638     if (idx < 0)
3639       MaskVec.push_back(idx);
3640     else if (idx < (int)NumElems)
3641       MaskVec.push_back(idx + NumElems);
3642     else
3643       MaskVec.push_back(idx - NumElems);
3644   }
3645   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3646                               SVOp->getOperand(0), &MaskVec[0]);
3647 }
3648
3649 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3650 /// the two vector operands have swapped position.
3651 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3652   unsigned NumElems = VT.getVectorNumElements();
3653   for (unsigned i = 0; i != NumElems; ++i) {
3654     int idx = Mask[i];
3655     if (idx < 0)
3656       continue;
3657     else if (idx < (int)NumElems)
3658       Mask[i] = idx + NumElems;
3659     else
3660       Mask[i] = idx - NumElems;
3661   }
3662 }
3663
3664 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3665 /// match movhlps. The lower half elements should come from upper half of
3666 /// V1 (and in order), and the upper half elements should come from the upper
3667 /// half of V2 (and in order).
3668 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3669   if (Op->getValueType(0).getVectorNumElements() != 4)
3670     return false;
3671   for (unsigned i = 0, e = 2; i != e; ++i)
3672     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3673       return false;
3674   for (unsigned i = 2; i != 4; ++i)
3675     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3676       return false;
3677   return true;
3678 }
3679
3680 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3681 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3682 /// required.
3683 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3684   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3685     return false;
3686   N = N->getOperand(0).getNode();
3687   if (!ISD::isNON_EXTLoad(N))
3688     return false;
3689   if (LD)
3690     *LD = cast<LoadSDNode>(N);
3691   return true;
3692 }
3693
3694 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3695 /// match movlp{s|d}. The lower half elements should come from lower half of
3696 /// V1 (and in order), and the upper half elements should come from the upper
3697 /// half of V2 (and in order). And since V1 will become the source of the
3698 /// MOVLP, it must be either a vector load or a scalar load to vector.
3699 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3700                                ShuffleVectorSDNode *Op) {
3701   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3702     return false;
3703   // Is V2 is a vector load, don't do this transformation. We will try to use
3704   // load folding shufps op.
3705   if (ISD::isNON_EXTLoad(V2))
3706     return false;
3707
3708   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3709
3710   if (NumElems != 2 && NumElems != 4)
3711     return false;
3712   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3713     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3714       return false;
3715   for (unsigned i = NumElems/2; i != NumElems; ++i)
3716     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3717       return false;
3718   return true;
3719 }
3720
3721 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3722 /// all the same.
3723 static bool isSplatVector(SDNode *N) {
3724   if (N->getOpcode() != ISD::BUILD_VECTOR)
3725     return false;
3726
3727   SDValue SplatValue = N->getOperand(0);
3728   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3729     if (N->getOperand(i) != SplatValue)
3730       return false;
3731   return true;
3732 }
3733
3734 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3735 /// to an zero vector.
3736 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3737 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3738   SDValue V1 = N->getOperand(0);
3739   SDValue V2 = N->getOperand(1);
3740   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3741   for (unsigned i = 0; i != NumElems; ++i) {
3742     int Idx = N->getMaskElt(i);
3743     if (Idx >= (int)NumElems) {
3744       unsigned Opc = V2.getOpcode();
3745       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3746         continue;
3747       if (Opc != ISD::BUILD_VECTOR ||
3748           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3749         return false;
3750     } else if (Idx >= 0) {
3751       unsigned Opc = V1.getOpcode();
3752       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3753         continue;
3754       if (Opc != ISD::BUILD_VECTOR ||
3755           !X86::isZeroNode(V1.getOperand(Idx)))
3756         return false;
3757     }
3758   }
3759   return true;
3760 }
3761
3762 /// getZeroVector - Returns a vector of specified type with all zero elements.
3763 ///
3764 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3765                              DebugLoc dl) {
3766   assert(VT.isVector() && "Expected a vector type");
3767
3768   // Always build SSE zero vectors as <4 x i32> bitcasted
3769   // to their dest type. This ensures they get CSE'd.
3770   SDValue Vec;
3771   if (VT.getSizeInBits() == 128) {  // SSE
3772     if (HasSSE2) {  // SSE2
3773       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3774       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3775     } else { // SSE1
3776       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3777       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3778     }
3779   } else if (VT.getSizeInBits() == 256) { // AVX
3780     // 256-bit logic and arithmetic instructions in AVX are
3781     // all floating-point, no support for integer ops. Default
3782     // to emitting fp zeroed vectors then.
3783     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3784     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3785     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3786   }
3787   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3788 }
3789
3790 /// getOnesVector - Returns a vector of specified type with all bits set.
3791 ///
3792 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3793   assert(VT.isVector() && "Expected a vector type");
3794
3795   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3796   // type.  This ensures they get CSE'd.
3797   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3798   SDValue Vec;
3799   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3800   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3801 }
3802
3803
3804 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3805 /// that point to V2 points to its first element.
3806 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3807   EVT VT = SVOp->getValueType(0);
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   bool Changed = false;
3811   SmallVector<int, 8> MaskVec;
3812   SVOp->getMask(MaskVec);
3813
3814   for (unsigned i = 0; i != NumElems; ++i) {
3815     if (MaskVec[i] > (int)NumElems) {
3816       MaskVec[i] = NumElems;
3817       Changed = true;
3818     }
3819   }
3820   if (Changed)
3821     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3822                                 SVOp->getOperand(1), &MaskVec[0]);
3823   return SDValue(SVOp, 0);
3824 }
3825
3826 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3827 /// operation of specified width.
3828 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3829                        SDValue V2) {
3830   unsigned NumElems = VT.getVectorNumElements();
3831   SmallVector<int, 8> Mask;
3832   Mask.push_back(NumElems);
3833   for (unsigned i = 1; i != NumElems; ++i)
3834     Mask.push_back(i);
3835   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3836 }
3837
3838 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3839 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3840                           SDValue V2) {
3841   unsigned NumElems = VT.getVectorNumElements();
3842   SmallVector<int, 8> Mask;
3843   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3844     Mask.push_back(i);
3845     Mask.push_back(i + NumElems);
3846   }
3847   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3848 }
3849
3850 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3851 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3852                           SDValue V2) {
3853   unsigned NumElems = VT.getVectorNumElements();
3854   unsigned Half = NumElems/2;
3855   SmallVector<int, 8> Mask;
3856   for (unsigned i = 0; i != Half; ++i) {
3857     Mask.push_back(i + Half);
3858     Mask.push_back(i + NumElems + Half);
3859   }
3860   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3861 }
3862
3863 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3864 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3865   EVT PVT = MVT::v4f32;
3866   EVT VT = SV->getValueType(0);
3867   DebugLoc dl = SV->getDebugLoc();
3868   SDValue V1 = SV->getOperand(0);
3869   int NumElems = VT.getVectorNumElements();
3870   int EltNo = SV->getSplatIndex();
3871
3872   // unpack elements to the correct location
3873   while (NumElems > 4) {
3874     if (EltNo < NumElems/2) {
3875       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3876     } else {
3877       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3878       EltNo -= NumElems/2;
3879     }
3880     NumElems >>= 1;
3881   }
3882
3883   // Perform the splat.
3884   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3885   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3886   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3887   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3888 }
3889
3890 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3891 /// vector of zero or undef vector.  This produces a shuffle where the low
3892 /// element of V2 is swizzled into the zero/undef vector, landing at element
3893 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3894 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3895                                              bool isZero, bool HasSSE2,
3896                                              SelectionDAG &DAG) {
3897   EVT VT = V2.getValueType();
3898   SDValue V1 = isZero
3899     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3900   unsigned NumElems = VT.getVectorNumElements();
3901   SmallVector<int, 16> MaskVec;
3902   for (unsigned i = 0; i != NumElems; ++i)
3903     // If this is the insertion idx, put the low elt of V2 here.
3904     MaskVec.push_back(i == Idx ? NumElems : i);
3905   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3906 }
3907
3908 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3909 /// element of the result of the vector shuffle.
3910 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3911                                    unsigned Depth) {
3912   if (Depth == 6)
3913     return SDValue();  // Limit search depth.
3914
3915   SDValue V = SDValue(N, 0);
3916   EVT VT = V.getValueType();
3917   unsigned Opcode = V.getOpcode();
3918
3919   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3920   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3921     Index = SV->getMaskElt(Index);
3922
3923     if (Index < 0)
3924       return DAG.getUNDEF(VT.getVectorElementType());
3925
3926     int NumElems = VT.getVectorNumElements();
3927     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3928     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3929   }
3930
3931   // Recurse into target specific vector shuffles to find scalars.
3932   if (isTargetShuffle(Opcode)) {
3933     int NumElems = VT.getVectorNumElements();
3934     SmallVector<unsigned, 16> ShuffleMask;
3935     SDValue ImmN;
3936
3937     switch(Opcode) {
3938     case X86ISD::SHUFPS:
3939     case X86ISD::SHUFPD:
3940       ImmN = N->getOperand(N->getNumOperands()-1);
3941       DecodeSHUFPSMask(NumElems,
3942                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3943                        ShuffleMask);
3944       break;
3945     case X86ISD::PUNPCKHBW:
3946     case X86ISD::PUNPCKHWD:
3947     case X86ISD::PUNPCKHDQ:
3948     case X86ISD::PUNPCKHQDQ:
3949       DecodePUNPCKHMask(NumElems, ShuffleMask);
3950       break;
3951     case X86ISD::UNPCKHPS:
3952     case X86ISD::UNPCKHPD:
3953       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3954       break;
3955     case X86ISD::PUNPCKLBW:
3956     case X86ISD::PUNPCKLWD:
3957     case X86ISD::PUNPCKLDQ:
3958     case X86ISD::PUNPCKLQDQ:
3959       DecodePUNPCKLMask(VT, ShuffleMask);
3960       break;
3961     case X86ISD::UNPCKLPS:
3962     case X86ISD::UNPCKLPD:
3963     case X86ISD::VUNPCKLPS:
3964     case X86ISD::VUNPCKLPD:
3965     case X86ISD::VUNPCKLPSY:
3966     case X86ISD::VUNPCKLPDY:
3967       DecodeUNPCKLPMask(VT, ShuffleMask);
3968       break;
3969     case X86ISD::MOVHLPS:
3970       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3971       break;
3972     case X86ISD::MOVLHPS:
3973       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3974       break;
3975     case X86ISD::PSHUFD:
3976       ImmN = N->getOperand(N->getNumOperands()-1);
3977       DecodePSHUFMask(NumElems,
3978                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3979                       ShuffleMask);
3980       break;
3981     case X86ISD::PSHUFHW:
3982       ImmN = N->getOperand(N->getNumOperands()-1);
3983       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3984                         ShuffleMask);
3985       break;
3986     case X86ISD::PSHUFLW:
3987       ImmN = N->getOperand(N->getNumOperands()-1);
3988       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3989                         ShuffleMask);
3990       break;
3991     case X86ISD::MOVSS:
3992     case X86ISD::MOVSD: {
3993       // The index 0 always comes from the first element of the second source,
3994       // this is why MOVSS and MOVSD are used in the first place. The other
3995       // elements come from the other positions of the first source vector.
3996       unsigned OpNum = (Index == 0) ? 1 : 0;
3997       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3998                                  Depth+1);
3999     }
4000     default:
4001       assert("not implemented for target shuffle node");
4002       return SDValue();
4003     }
4004
4005     Index = ShuffleMask[Index];
4006     if (Index < 0)
4007       return DAG.getUNDEF(VT.getVectorElementType());
4008
4009     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4010     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4011                                Depth+1);
4012   }
4013
4014   // Actual nodes that may contain scalar elements
4015   if (Opcode == ISD::BITCAST) {
4016     V = V.getOperand(0);
4017     EVT SrcVT = V.getValueType();
4018     unsigned NumElems = VT.getVectorNumElements();
4019
4020     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4021       return SDValue();
4022   }
4023
4024   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4025     return (Index == 0) ? V.getOperand(0)
4026                           : DAG.getUNDEF(VT.getVectorElementType());
4027
4028   if (V.getOpcode() == ISD::BUILD_VECTOR)
4029     return V.getOperand(Index);
4030
4031   return SDValue();
4032 }
4033
4034 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4035 /// shuffle operation which come from a consecutively from a zero. The
4036 /// search can start in two different directions, from left or right.
4037 static
4038 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4039                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4040   int i = 0;
4041
4042   while (i < NumElems) {
4043     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4044     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4045     if (!(Elt.getNode() &&
4046          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4047       break;
4048     ++i;
4049   }
4050
4051   return i;
4052 }
4053
4054 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4055 /// MaskE correspond consecutively to elements from one of the vector operands,
4056 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4057 static
4058 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4059                               int OpIdx, int NumElems, unsigned &OpNum) {
4060   bool SeenV1 = false;
4061   bool SeenV2 = false;
4062
4063   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4064     int Idx = SVOp->getMaskElt(i);
4065     // Ignore undef indicies
4066     if (Idx < 0)
4067       continue;
4068
4069     if (Idx < NumElems)
4070       SeenV1 = true;
4071     else
4072       SeenV2 = true;
4073
4074     // Only accept consecutive elements from the same vector
4075     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4076       return false;
4077   }
4078
4079   OpNum = SeenV1 ? 0 : 1;
4080   return true;
4081 }
4082
4083 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4084 /// logical left shift of a vector.
4085 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4086                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4087   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4088   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4089               false /* check zeros from right */, DAG);
4090   unsigned OpSrc;
4091
4092   if (!NumZeros)
4093     return false;
4094
4095   // Considering the elements in the mask that are not consecutive zeros,
4096   // check if they consecutively come from only one of the source vectors.
4097   //
4098   //               V1 = {X, A, B, C}     0
4099   //                         \  \  \    /
4100   //   vector_shuffle V1, V2 <1, 2, 3, X>
4101   //
4102   if (!isShuffleMaskConsecutive(SVOp,
4103             0,                   // Mask Start Index
4104             NumElems-NumZeros-1, // Mask End Index
4105             NumZeros,            // Where to start looking in the src vector
4106             NumElems,            // Number of elements in vector
4107             OpSrc))              // Which source operand ?
4108     return false;
4109
4110   isLeft = false;
4111   ShAmt = NumZeros;
4112   ShVal = SVOp->getOperand(OpSrc);
4113   return true;
4114 }
4115
4116 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4117 /// logical left shift of a vector.
4118 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4119                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4120   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4121   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4122               true /* check zeros from left */, DAG);
4123   unsigned OpSrc;
4124
4125   if (!NumZeros)
4126     return false;
4127
4128   // Considering the elements in the mask that are not consecutive zeros,
4129   // check if they consecutively come from only one of the source vectors.
4130   //
4131   //                           0    { A, B, X, X } = V2
4132   //                          / \    /  /
4133   //   vector_shuffle V1, V2 <X, X, 4, 5>
4134   //
4135   if (!isShuffleMaskConsecutive(SVOp,
4136             NumZeros,     // Mask Start Index
4137             NumElems-1,   // Mask End Index
4138             0,            // Where to start looking in the src vector
4139             NumElems,     // Number of elements in vector
4140             OpSrc))       // Which source operand ?
4141     return false;
4142
4143   isLeft = true;
4144   ShAmt = NumZeros;
4145   ShVal = SVOp->getOperand(OpSrc);
4146   return true;
4147 }
4148
4149 /// isVectorShift - Returns true if the shuffle can be implemented as a
4150 /// logical left or right shift of a vector.
4151 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4152                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4153   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4154       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4155     return true;
4156
4157   return false;
4158 }
4159
4160 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4161 ///
4162 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4163                                        unsigned NumNonZero, unsigned NumZero,
4164                                        SelectionDAG &DAG,
4165                                        const TargetLowering &TLI) {
4166   if (NumNonZero > 8)
4167     return SDValue();
4168
4169   DebugLoc dl = Op.getDebugLoc();
4170   SDValue V(0, 0);
4171   bool First = true;
4172   for (unsigned i = 0; i < 16; ++i) {
4173     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4174     if (ThisIsNonZero && First) {
4175       if (NumZero)
4176         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4177       else
4178         V = DAG.getUNDEF(MVT::v8i16);
4179       First = false;
4180     }
4181
4182     if ((i & 1) != 0) {
4183       SDValue ThisElt(0, 0), LastElt(0, 0);
4184       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4185       if (LastIsNonZero) {
4186         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4187                               MVT::i16, Op.getOperand(i-1));
4188       }
4189       if (ThisIsNonZero) {
4190         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4191         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4192                               ThisElt, DAG.getConstant(8, MVT::i8));
4193         if (LastIsNonZero)
4194           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4195       } else
4196         ThisElt = LastElt;
4197
4198       if (ThisElt.getNode())
4199         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4200                         DAG.getIntPtrConstant(i/2));
4201     }
4202   }
4203
4204   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4205 }
4206
4207 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4208 ///
4209 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4210                                      unsigned NumNonZero, unsigned NumZero,
4211                                      SelectionDAG &DAG,
4212                                      const TargetLowering &TLI) {
4213   if (NumNonZero > 4)
4214     return SDValue();
4215
4216   DebugLoc dl = Op.getDebugLoc();
4217   SDValue V(0, 0);
4218   bool First = true;
4219   for (unsigned i = 0; i < 8; ++i) {
4220     bool isNonZero = (NonZeros & (1 << i)) != 0;
4221     if (isNonZero) {
4222       if (First) {
4223         if (NumZero)
4224           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4225         else
4226           V = DAG.getUNDEF(MVT::v8i16);
4227         First = false;
4228       }
4229       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4230                       MVT::v8i16, V, Op.getOperand(i),
4231                       DAG.getIntPtrConstant(i));
4232     }
4233   }
4234
4235   return V;
4236 }
4237
4238 /// getVShift - Return a vector logical shift node.
4239 ///
4240 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4241                          unsigned NumBits, SelectionDAG &DAG,
4242                          const TargetLowering &TLI, DebugLoc dl) {
4243   EVT ShVT = MVT::v2i64;
4244   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4245   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4246   return DAG.getNode(ISD::BITCAST, dl, VT,
4247                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4248                              DAG.getConstant(NumBits,
4249                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4250 }
4251
4252 SDValue
4253 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4254                                           SelectionDAG &DAG) const {
4255
4256   // Check if the scalar load can be widened into a vector load. And if
4257   // the address is "base + cst" see if the cst can be "absorbed" into
4258   // the shuffle mask.
4259   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4260     SDValue Ptr = LD->getBasePtr();
4261     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4262       return SDValue();
4263     EVT PVT = LD->getValueType(0);
4264     if (PVT != MVT::i32 && PVT != MVT::f32)
4265       return SDValue();
4266
4267     int FI = -1;
4268     int64_t Offset = 0;
4269     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4270       FI = FINode->getIndex();
4271       Offset = 0;
4272     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4273                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4274       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4275       Offset = Ptr.getConstantOperandVal(1);
4276       Ptr = Ptr.getOperand(0);
4277     } else {
4278       return SDValue();
4279     }
4280
4281     SDValue Chain = LD->getChain();
4282     // Make sure the stack object alignment is at least 16.
4283     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4284     if (DAG.InferPtrAlignment(Ptr) < 16) {
4285       if (MFI->isFixedObjectIndex(FI)) {
4286         // Can't change the alignment. FIXME: It's possible to compute
4287         // the exact stack offset and reference FI + adjust offset instead.
4288         // If someone *really* cares about this. That's the way to implement it.
4289         return SDValue();
4290       } else {
4291         MFI->setObjectAlignment(FI, 16);
4292       }
4293     }
4294
4295     // (Offset % 16) must be multiple of 4. Then address is then
4296     // Ptr + (Offset & ~15).
4297     if (Offset < 0)
4298       return SDValue();
4299     if ((Offset % 16) & 3)
4300       return SDValue();
4301     int64_t StartOffset = Offset & ~15;
4302     if (StartOffset)
4303       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4304                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4305
4306     int EltNo = (Offset - StartOffset) >> 2;
4307     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4308     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4309     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4310                              LD->getPointerInfo().getWithOffset(StartOffset),
4311                              false, false, 0);
4312     // Canonicalize it to a v4i32 shuffle.
4313     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4314     return DAG.getNode(ISD::BITCAST, dl, VT,
4315                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4316                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4317   }
4318
4319   return SDValue();
4320 }
4321
4322 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4323 /// vector of type 'VT', see if the elements can be replaced by a single large
4324 /// load which has the same value as a build_vector whose operands are 'elts'.
4325 ///
4326 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4327 ///
4328 /// FIXME: we'd also like to handle the case where the last elements are zero
4329 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4330 /// There's even a handy isZeroNode for that purpose.
4331 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4332                                         DebugLoc &DL, SelectionDAG &DAG) {
4333   EVT EltVT = VT.getVectorElementType();
4334   unsigned NumElems = Elts.size();
4335
4336   LoadSDNode *LDBase = NULL;
4337   unsigned LastLoadedElt = -1U;
4338
4339   // For each element in the initializer, see if we've found a load or an undef.
4340   // If we don't find an initial load element, or later load elements are
4341   // non-consecutive, bail out.
4342   for (unsigned i = 0; i < NumElems; ++i) {
4343     SDValue Elt = Elts[i];
4344
4345     if (!Elt.getNode() ||
4346         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4347       return SDValue();
4348     if (!LDBase) {
4349       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4350         return SDValue();
4351       LDBase = cast<LoadSDNode>(Elt.getNode());
4352       LastLoadedElt = i;
4353       continue;
4354     }
4355     if (Elt.getOpcode() == ISD::UNDEF)
4356       continue;
4357
4358     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4359     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4360       return SDValue();
4361     LastLoadedElt = i;
4362   }
4363
4364   // If we have found an entire vector of loads and undefs, then return a large
4365   // load of the entire vector width starting at the base pointer.  If we found
4366   // consecutive loads for the low half, generate a vzext_load node.
4367   if (LastLoadedElt == NumElems - 1) {
4368     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4369       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4370                          LDBase->getPointerInfo(),
4371                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4372     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4373                        LDBase->getPointerInfo(),
4374                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4375                        LDBase->getAlignment());
4376   } else if (NumElems == 4 && LastLoadedElt == 1) {
4377     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4378     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4379     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4380                                               Ops, 2, MVT::i32,
4381                                               LDBase->getMemOperand());
4382     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4383   }
4384   return SDValue();
4385 }
4386
4387 SDValue
4388 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4389   DebugLoc dl = Op.getDebugLoc();
4390
4391   EVT VT = Op.getValueType();
4392   EVT ExtVT = VT.getVectorElementType();
4393
4394   unsigned NumElems = Op.getNumOperands();
4395
4396   // For AVX-length vectors, build the individual 128-bit pieces and
4397   // use shuffles to put them in place.
4398   if (VT.getSizeInBits() > 256 &&
4399       Subtarget->hasAVX() &&
4400       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4401     SmallVector<SDValue, 8> V;
4402     V.resize(NumElems);
4403     for (unsigned i = 0; i < NumElems; ++i) {
4404       V[i] = Op.getOperand(i);
4405     }
4406
4407     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4408
4409     // Build the lower subvector.
4410     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4411     // Build the upper subvector.
4412     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4413                                 NumElems/2);
4414
4415     return ConcatVectors(Lower, Upper, DAG);
4416   }
4417
4418   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4419   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4420   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4421   // is present, so AllOnes is ignored.
4422   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4423       (Op.getValueType().getSizeInBits() != 256 &&
4424        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4425     // Canonicalize this to <4 x i32> (SSE) to
4426     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4427     // eliminated on x86-32 hosts.
4428     if (Op.getValueType() == MVT::v4i32)
4429       return Op;
4430
4431     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4432       return getOnesVector(Op.getValueType(), DAG, dl);
4433     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4434   }
4435
4436   unsigned EVTBits = ExtVT.getSizeInBits();
4437
4438   unsigned NumZero  = 0;
4439   unsigned NumNonZero = 0;
4440   unsigned NonZeros = 0;
4441   bool IsAllConstants = true;
4442   SmallSet<SDValue, 8> Values;
4443   for (unsigned i = 0; i < NumElems; ++i) {
4444     SDValue Elt = Op.getOperand(i);
4445     if (Elt.getOpcode() == ISD::UNDEF)
4446       continue;
4447     Values.insert(Elt);
4448     if (Elt.getOpcode() != ISD::Constant &&
4449         Elt.getOpcode() != ISD::ConstantFP)
4450       IsAllConstants = false;
4451     if (X86::isZeroNode(Elt))
4452       NumZero++;
4453     else {
4454       NonZeros |= (1 << i);
4455       NumNonZero++;
4456     }
4457   }
4458
4459   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4460   if (NumNonZero == 0)
4461     return DAG.getUNDEF(VT);
4462
4463   // Special case for single non-zero, non-undef, element.
4464   if (NumNonZero == 1) {
4465     unsigned Idx = CountTrailingZeros_32(NonZeros);
4466     SDValue Item = Op.getOperand(Idx);
4467
4468     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4469     // the value are obviously zero, truncate the value to i32 and do the
4470     // insertion that way.  Only do this if the value is non-constant or if the
4471     // value is a constant being inserted into element 0.  It is cheaper to do
4472     // a constant pool load than it is to do a movd + shuffle.
4473     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4474         (!IsAllConstants || Idx == 0)) {
4475       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4476         // Handle SSE only.
4477         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4478         EVT VecVT = MVT::v4i32;
4479         unsigned VecElts = 4;
4480
4481         // Truncate the value (which may itself be a constant) to i32, and
4482         // convert it to a vector with movd (S2V+shuffle to zero extend).
4483         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4484         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4485         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4486                                            Subtarget->hasSSE2(), DAG);
4487
4488         // Now we have our 32-bit value zero extended in the low element of
4489         // a vector.  If Idx != 0, swizzle it into place.
4490         if (Idx != 0) {
4491           SmallVector<int, 4> Mask;
4492           Mask.push_back(Idx);
4493           for (unsigned i = 1; i != VecElts; ++i)
4494             Mask.push_back(i);
4495           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4496                                       DAG.getUNDEF(Item.getValueType()),
4497                                       &Mask[0]);
4498         }
4499         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4500       }
4501     }
4502
4503     // If we have a constant or non-constant insertion into the low element of
4504     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4505     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4506     // depending on what the source datatype is.
4507     if (Idx == 0) {
4508       if (NumZero == 0) {
4509         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4510       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4511           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4512         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4513         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4514         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4515                                            DAG);
4516       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4517         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4518         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4519         EVT MiddleVT = MVT::v4i32;
4520         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4521         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4522                                            Subtarget->hasSSE2(), DAG);
4523         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4524       }
4525     }
4526
4527     // Is it a vector logical left shift?
4528     if (NumElems == 2 && Idx == 1 &&
4529         X86::isZeroNode(Op.getOperand(0)) &&
4530         !X86::isZeroNode(Op.getOperand(1))) {
4531       unsigned NumBits = VT.getSizeInBits();
4532       return getVShift(true, VT,
4533                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4534                                    VT, Op.getOperand(1)),
4535                        NumBits/2, DAG, *this, dl);
4536     }
4537
4538     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4539       return SDValue();
4540
4541     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4542     // is a non-constant being inserted into an element other than the low one,
4543     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4544     // movd/movss) to move this into the low element, then shuffle it into
4545     // place.
4546     if (EVTBits == 32) {
4547       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4548
4549       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4550       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4551                                          Subtarget->hasSSE2(), DAG);
4552       SmallVector<int, 8> MaskVec;
4553       for (unsigned i = 0; i < NumElems; i++)
4554         MaskVec.push_back(i == Idx ? 0 : 1);
4555       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4556     }
4557   }
4558
4559   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4560   if (Values.size() == 1) {
4561     if (EVTBits == 32) {
4562       // Instead of a shuffle like this:
4563       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4564       // Check if it's possible to issue this instead.
4565       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4566       unsigned Idx = CountTrailingZeros_32(NonZeros);
4567       SDValue Item = Op.getOperand(Idx);
4568       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4569         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4570     }
4571     return SDValue();
4572   }
4573
4574   // A vector full of immediates; various special cases are already
4575   // handled, so this is best done with a single constant-pool load.
4576   if (IsAllConstants)
4577     return SDValue();
4578
4579   // Let legalizer expand 2-wide build_vectors.
4580   if (EVTBits == 64) {
4581     if (NumNonZero == 1) {
4582       // One half is zero or undef.
4583       unsigned Idx = CountTrailingZeros_32(NonZeros);
4584       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4585                                  Op.getOperand(Idx));
4586       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4587                                          Subtarget->hasSSE2(), DAG);
4588     }
4589     return SDValue();
4590   }
4591
4592   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4593   if (EVTBits == 8 && NumElems == 16) {
4594     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4595                                         *this);
4596     if (V.getNode()) return V;
4597   }
4598
4599   if (EVTBits == 16 && NumElems == 8) {
4600     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4601                                       *this);
4602     if (V.getNode()) return V;
4603   }
4604
4605   // If element VT is == 32 bits, turn it into a number of shuffles.
4606   SmallVector<SDValue, 8> V;
4607   V.resize(NumElems);
4608   if (NumElems == 4 && NumZero > 0) {
4609     for (unsigned i = 0; i < 4; ++i) {
4610       bool isZero = !(NonZeros & (1 << i));
4611       if (isZero)
4612         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4613       else
4614         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4615     }
4616
4617     for (unsigned i = 0; i < 2; ++i) {
4618       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4619         default: break;
4620         case 0:
4621           V[i] = V[i*2];  // Must be a zero vector.
4622           break;
4623         case 1:
4624           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4625           break;
4626         case 2:
4627           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4628           break;
4629         case 3:
4630           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4631           break;
4632       }
4633     }
4634
4635     SmallVector<int, 8> MaskVec;
4636     bool Reverse = (NonZeros & 0x3) == 2;
4637     for (unsigned i = 0; i < 2; ++i)
4638       MaskVec.push_back(Reverse ? 1-i : i);
4639     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4640     for (unsigned i = 0; i < 2; ++i)
4641       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4642     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4643   }
4644
4645   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4646     // Check for a build vector of consecutive loads.
4647     for (unsigned i = 0; i < NumElems; ++i)
4648       V[i] = Op.getOperand(i);
4649
4650     // Check for elements which are consecutive loads.
4651     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4652     if (LD.getNode())
4653       return LD;
4654
4655     // For SSE 4.1, use insertps to put the high elements into the low element.
4656     if (getSubtarget()->hasSSE41()) {
4657       SDValue Result;
4658       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4659         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4660       else
4661         Result = DAG.getUNDEF(VT);
4662
4663       for (unsigned i = 1; i < NumElems; ++i) {
4664         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4665         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4666                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4667       }
4668       return Result;
4669     }
4670
4671     // Otherwise, expand into a number of unpckl*, start by extending each of
4672     // our (non-undef) elements to the full vector width with the element in the
4673     // bottom slot of the vector (which generates no code for SSE).
4674     for (unsigned i = 0; i < NumElems; ++i) {
4675       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4676         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4677       else
4678         V[i] = DAG.getUNDEF(VT);
4679     }
4680
4681     // Next, we iteratively mix elements, e.g. for v4f32:
4682     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4683     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4684     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4685     unsigned EltStride = NumElems >> 1;
4686     while (EltStride != 0) {
4687       for (unsigned i = 0; i < EltStride; ++i) {
4688         // If V[i+EltStride] is undef and this is the first round of mixing,
4689         // then it is safe to just drop this shuffle: V[i] is already in the
4690         // right place, the one element (since it's the first round) being
4691         // inserted as undef can be dropped.  This isn't safe for successive
4692         // rounds because they will permute elements within both vectors.
4693         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4694             EltStride == NumElems/2)
4695           continue;
4696
4697         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4698       }
4699       EltStride >>= 1;
4700     }
4701     return V[0];
4702   }
4703   return SDValue();
4704 }
4705
4706 SDValue
4707 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4708   // We support concatenate two MMX registers and place them in a MMX
4709   // register.  This is better than doing a stack convert.
4710   DebugLoc dl = Op.getDebugLoc();
4711   EVT ResVT = Op.getValueType();
4712   assert(Op.getNumOperands() == 2);
4713   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4714          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4715   int Mask[2];
4716   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4717   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4718   InVec = Op.getOperand(1);
4719   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4720     unsigned NumElts = ResVT.getVectorNumElements();
4721     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4722     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4723                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4724   } else {
4725     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4726     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4727     Mask[0] = 0; Mask[1] = 2;
4728     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4729   }
4730   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4731 }
4732
4733 // v8i16 shuffles - Prefer shuffles in the following order:
4734 // 1. [all]   pshuflw, pshufhw, optional move
4735 // 2. [ssse3] 1 x pshufb
4736 // 3. [ssse3] 2 x pshufb + 1 x por
4737 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4738 SDValue
4739 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4740                                             SelectionDAG &DAG) const {
4741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4742   SDValue V1 = SVOp->getOperand(0);
4743   SDValue V2 = SVOp->getOperand(1);
4744   DebugLoc dl = SVOp->getDebugLoc();
4745   SmallVector<int, 8> MaskVals;
4746
4747   // Determine if more than 1 of the words in each of the low and high quadwords
4748   // of the result come from the same quadword of one of the two inputs.  Undef
4749   // mask values count as coming from any quadword, for better codegen.
4750   SmallVector<unsigned, 4> LoQuad(4);
4751   SmallVector<unsigned, 4> HiQuad(4);
4752   BitVector InputQuads(4);
4753   for (unsigned i = 0; i < 8; ++i) {
4754     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4755     int EltIdx = SVOp->getMaskElt(i);
4756     MaskVals.push_back(EltIdx);
4757     if (EltIdx < 0) {
4758       ++Quad[0];
4759       ++Quad[1];
4760       ++Quad[2];
4761       ++Quad[3];
4762       continue;
4763     }
4764     ++Quad[EltIdx / 4];
4765     InputQuads.set(EltIdx / 4);
4766   }
4767
4768   int BestLoQuad = -1;
4769   unsigned MaxQuad = 1;
4770   for (unsigned i = 0; i < 4; ++i) {
4771     if (LoQuad[i] > MaxQuad) {
4772       BestLoQuad = i;
4773       MaxQuad = LoQuad[i];
4774     }
4775   }
4776
4777   int BestHiQuad = -1;
4778   MaxQuad = 1;
4779   for (unsigned i = 0; i < 4; ++i) {
4780     if (HiQuad[i] > MaxQuad) {
4781       BestHiQuad = i;
4782       MaxQuad = HiQuad[i];
4783     }
4784   }
4785
4786   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4787   // of the two input vectors, shuffle them into one input vector so only a
4788   // single pshufb instruction is necessary. If There are more than 2 input
4789   // quads, disable the next transformation since it does not help SSSE3.
4790   bool V1Used = InputQuads[0] || InputQuads[1];
4791   bool V2Used = InputQuads[2] || InputQuads[3];
4792   if (Subtarget->hasSSSE3()) {
4793     if (InputQuads.count() == 2 && V1Used && V2Used) {
4794       BestLoQuad = InputQuads.find_first();
4795       BestHiQuad = InputQuads.find_next(BestLoQuad);
4796     }
4797     if (InputQuads.count() > 2) {
4798       BestLoQuad = -1;
4799       BestHiQuad = -1;
4800     }
4801   }
4802
4803   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4804   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4805   // words from all 4 input quadwords.
4806   SDValue NewV;
4807   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4808     SmallVector<int, 8> MaskV;
4809     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4810     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4811     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4812                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4813                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4814     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4815
4816     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4817     // source words for the shuffle, to aid later transformations.
4818     bool AllWordsInNewV = true;
4819     bool InOrder[2] = { true, true };
4820     for (unsigned i = 0; i != 8; ++i) {
4821       int idx = MaskVals[i];
4822       if (idx != (int)i)
4823         InOrder[i/4] = false;
4824       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4825         continue;
4826       AllWordsInNewV = false;
4827       break;
4828     }
4829
4830     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4831     if (AllWordsInNewV) {
4832       for (int i = 0; i != 8; ++i) {
4833         int idx = MaskVals[i];
4834         if (idx < 0)
4835           continue;
4836         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4837         if ((idx != i) && idx < 4)
4838           pshufhw = false;
4839         if ((idx != i) && idx > 3)
4840           pshuflw = false;
4841       }
4842       V1 = NewV;
4843       V2Used = false;
4844       BestLoQuad = 0;
4845       BestHiQuad = 1;
4846     }
4847
4848     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4849     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4850     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4851       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4852       unsigned TargetMask = 0;
4853       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4854                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4855       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4856                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4857       V1 = NewV.getOperand(0);
4858       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4859     }
4860   }
4861
4862   // If we have SSSE3, and all words of the result are from 1 input vector,
4863   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4864   // is present, fall back to case 4.
4865   if (Subtarget->hasSSSE3()) {
4866     SmallVector<SDValue,16> pshufbMask;
4867
4868     // If we have elements from both input vectors, set the high bit of the
4869     // shuffle mask element to zero out elements that come from V2 in the V1
4870     // mask, and elements that come from V1 in the V2 mask, so that the two
4871     // results can be OR'd together.
4872     bool TwoInputs = V1Used && V2Used;
4873     for (unsigned i = 0; i != 8; ++i) {
4874       int EltIdx = MaskVals[i] * 2;
4875       if (TwoInputs && (EltIdx >= 16)) {
4876         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4877         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4878         continue;
4879       }
4880       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4881       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4882     }
4883     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4884     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4885                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4886                                  MVT::v16i8, &pshufbMask[0], 16));
4887     if (!TwoInputs)
4888       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4889
4890     // Calculate the shuffle mask for the second input, shuffle it, and
4891     // OR it with the first shuffled input.
4892     pshufbMask.clear();
4893     for (unsigned i = 0; i != 8; ++i) {
4894       int EltIdx = MaskVals[i] * 2;
4895       if (EltIdx < 16) {
4896         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4897         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4898         continue;
4899       }
4900       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4901       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4902     }
4903     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4904     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4905                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4906                                  MVT::v16i8, &pshufbMask[0], 16));
4907     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4908     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4909   }
4910
4911   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4912   // and update MaskVals with new element order.
4913   BitVector InOrder(8);
4914   if (BestLoQuad >= 0) {
4915     SmallVector<int, 8> MaskV;
4916     for (int i = 0; i != 4; ++i) {
4917       int idx = MaskVals[i];
4918       if (idx < 0) {
4919         MaskV.push_back(-1);
4920         InOrder.set(i);
4921       } else if ((idx / 4) == BestLoQuad) {
4922         MaskV.push_back(idx & 3);
4923         InOrder.set(i);
4924       } else {
4925         MaskV.push_back(-1);
4926       }
4927     }
4928     for (unsigned i = 4; i != 8; ++i)
4929       MaskV.push_back(i);
4930     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4931                                 &MaskV[0]);
4932
4933     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4934       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4935                                NewV.getOperand(0),
4936                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4937                                DAG);
4938   }
4939
4940   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4941   // and update MaskVals with the new element order.
4942   if (BestHiQuad >= 0) {
4943     SmallVector<int, 8> MaskV;
4944     for (unsigned i = 0; i != 4; ++i)
4945       MaskV.push_back(i);
4946     for (unsigned i = 4; i != 8; ++i) {
4947       int idx = MaskVals[i];
4948       if (idx < 0) {
4949         MaskV.push_back(-1);
4950         InOrder.set(i);
4951       } else if ((idx / 4) == BestHiQuad) {
4952         MaskV.push_back((idx & 3) + 4);
4953         InOrder.set(i);
4954       } else {
4955         MaskV.push_back(-1);
4956       }
4957     }
4958     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4959                                 &MaskV[0]);
4960
4961     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4962       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4963                               NewV.getOperand(0),
4964                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4965                               DAG);
4966   }
4967
4968   // In case BestHi & BestLo were both -1, which means each quadword has a word
4969   // from each of the four input quadwords, calculate the InOrder bitvector now
4970   // before falling through to the insert/extract cleanup.
4971   if (BestLoQuad == -1 && BestHiQuad == -1) {
4972     NewV = V1;
4973     for (int i = 0; i != 8; ++i)
4974       if (MaskVals[i] < 0 || MaskVals[i] == i)
4975         InOrder.set(i);
4976   }
4977
4978   // The other elements are put in the right place using pextrw and pinsrw.
4979   for (unsigned i = 0; i != 8; ++i) {
4980     if (InOrder[i])
4981       continue;
4982     int EltIdx = MaskVals[i];
4983     if (EltIdx < 0)
4984       continue;
4985     SDValue ExtOp = (EltIdx < 8)
4986     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4987                   DAG.getIntPtrConstant(EltIdx))
4988     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4989                   DAG.getIntPtrConstant(EltIdx - 8));
4990     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4991                        DAG.getIntPtrConstant(i));
4992   }
4993   return NewV;
4994 }
4995
4996 // v16i8 shuffles - Prefer shuffles in the following order:
4997 // 1. [ssse3] 1 x pshufb
4998 // 2. [ssse3] 2 x pshufb + 1 x por
4999 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5000 static
5001 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5002                                  SelectionDAG &DAG,
5003                                  const X86TargetLowering &TLI) {
5004   SDValue V1 = SVOp->getOperand(0);
5005   SDValue V2 = SVOp->getOperand(1);
5006   DebugLoc dl = SVOp->getDebugLoc();
5007   SmallVector<int, 16> MaskVals;
5008   SVOp->getMask(MaskVals);
5009
5010   // If we have SSSE3, case 1 is generated when all result bytes come from
5011   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5012   // present, fall back to case 3.
5013   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5014   bool V1Only = true;
5015   bool V2Only = true;
5016   for (unsigned i = 0; i < 16; ++i) {
5017     int EltIdx = MaskVals[i];
5018     if (EltIdx < 0)
5019       continue;
5020     if (EltIdx < 16)
5021       V2Only = false;
5022     else
5023       V1Only = false;
5024   }
5025
5026   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5027   if (TLI.getSubtarget()->hasSSSE3()) {
5028     SmallVector<SDValue,16> pshufbMask;
5029
5030     // If all result elements are from one input vector, then only translate
5031     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5032     //
5033     // Otherwise, we have elements from both input vectors, and must zero out
5034     // elements that come from V2 in the first mask, and V1 in the second mask
5035     // so that we can OR them together.
5036     bool TwoInputs = !(V1Only || V2Only);
5037     for (unsigned i = 0; i != 16; ++i) {
5038       int EltIdx = MaskVals[i];
5039       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5040         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5041         continue;
5042       }
5043       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5044     }
5045     // If all the elements are from V2, assign it to V1 and return after
5046     // building the first pshufb.
5047     if (V2Only)
5048       V1 = V2;
5049     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5050                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5051                                  MVT::v16i8, &pshufbMask[0], 16));
5052     if (!TwoInputs)
5053       return V1;
5054
5055     // Calculate the shuffle mask for the second input, shuffle it, and
5056     // OR it with the first shuffled input.
5057     pshufbMask.clear();
5058     for (unsigned i = 0; i != 16; ++i) {
5059       int EltIdx = MaskVals[i];
5060       if (EltIdx < 16) {
5061         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5062         continue;
5063       }
5064       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5065     }
5066     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5067                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5068                                  MVT::v16i8, &pshufbMask[0], 16));
5069     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5070   }
5071
5072   // No SSSE3 - Calculate in place words and then fix all out of place words
5073   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5074   // the 16 different words that comprise the two doublequadword input vectors.
5075   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5076   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5077   SDValue NewV = V2Only ? V2 : V1;
5078   for (int i = 0; i != 8; ++i) {
5079     int Elt0 = MaskVals[i*2];
5080     int Elt1 = MaskVals[i*2+1];
5081
5082     // This word of the result is all undef, skip it.
5083     if (Elt0 < 0 && Elt1 < 0)
5084       continue;
5085
5086     // This word of the result is already in the correct place, skip it.
5087     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5088       continue;
5089     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5090       continue;
5091
5092     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5093     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5094     SDValue InsElt;
5095
5096     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5097     // using a single extract together, load it and store it.
5098     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5099       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5100                            DAG.getIntPtrConstant(Elt1 / 2));
5101       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5102                         DAG.getIntPtrConstant(i));
5103       continue;
5104     }
5105
5106     // If Elt1 is defined, extract it from the appropriate source.  If the
5107     // source byte is not also odd, shift the extracted word left 8 bits
5108     // otherwise clear the bottom 8 bits if we need to do an or.
5109     if (Elt1 >= 0) {
5110       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5111                            DAG.getIntPtrConstant(Elt1 / 2));
5112       if ((Elt1 & 1) == 0)
5113         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5114                              DAG.getConstant(8,
5115                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5116       else if (Elt0 >= 0)
5117         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5118                              DAG.getConstant(0xFF00, MVT::i16));
5119     }
5120     // If Elt0 is defined, extract it from the appropriate source.  If the
5121     // source byte is not also even, shift the extracted word right 8 bits. If
5122     // Elt1 was also defined, OR the extracted values together before
5123     // inserting them in the result.
5124     if (Elt0 >= 0) {
5125       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5126                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5127       if ((Elt0 & 1) != 0)
5128         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5129                               DAG.getConstant(8,
5130                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5131       else if (Elt1 >= 0)
5132         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5133                              DAG.getConstant(0x00FF, MVT::i16));
5134       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5135                          : InsElt0;
5136     }
5137     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5138                        DAG.getIntPtrConstant(i));
5139   }
5140   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5141 }
5142
5143 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5144 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5145 /// done when every pair / quad of shuffle mask elements point to elements in
5146 /// the right sequence. e.g.
5147 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5148 static
5149 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5150                                  SelectionDAG &DAG, DebugLoc dl) {
5151   EVT VT = SVOp->getValueType(0);
5152   SDValue V1 = SVOp->getOperand(0);
5153   SDValue V2 = SVOp->getOperand(1);
5154   unsigned NumElems = VT.getVectorNumElements();
5155   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5156   EVT NewVT;
5157   switch (VT.getSimpleVT().SimpleTy) {
5158   default: assert(false && "Unexpected!");
5159   case MVT::v4f32: NewVT = MVT::v2f64; break;
5160   case MVT::v4i32: NewVT = MVT::v2i64; break;
5161   case MVT::v8i16: NewVT = MVT::v4i32; break;
5162   case MVT::v16i8: NewVT = MVT::v4i32; break;
5163   }
5164
5165   int Scale = NumElems / NewWidth;
5166   SmallVector<int, 8> MaskVec;
5167   for (unsigned i = 0; i < NumElems; i += Scale) {
5168     int StartIdx = -1;
5169     for (int j = 0; j < Scale; ++j) {
5170       int EltIdx = SVOp->getMaskElt(i+j);
5171       if (EltIdx < 0)
5172         continue;
5173       if (StartIdx == -1)
5174         StartIdx = EltIdx - (EltIdx % Scale);
5175       if (EltIdx != StartIdx + j)
5176         return SDValue();
5177     }
5178     if (StartIdx == -1)
5179       MaskVec.push_back(-1);
5180     else
5181       MaskVec.push_back(StartIdx / Scale);
5182   }
5183
5184   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5185   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5186   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5187 }
5188
5189 /// getVZextMovL - Return a zero-extending vector move low node.
5190 ///
5191 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5192                             SDValue SrcOp, SelectionDAG &DAG,
5193                             const X86Subtarget *Subtarget, DebugLoc dl) {
5194   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5195     LoadSDNode *LD = NULL;
5196     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5197       LD = dyn_cast<LoadSDNode>(SrcOp);
5198     if (!LD) {
5199       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5200       // instead.
5201       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5202       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5203           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5204           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5205           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5206         // PR2108
5207         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5208         return DAG.getNode(ISD::BITCAST, dl, VT,
5209                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5210                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5211                                                    OpVT,
5212                                                    SrcOp.getOperand(0)
5213                                                           .getOperand(0))));
5214       }
5215     }
5216   }
5217
5218   return DAG.getNode(ISD::BITCAST, dl, VT,
5219                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5220                                  DAG.getNode(ISD::BITCAST, dl,
5221                                              OpVT, SrcOp)));
5222 }
5223
5224 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5225 /// shuffles.
5226 static SDValue
5227 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5228   SDValue V1 = SVOp->getOperand(0);
5229   SDValue V2 = SVOp->getOperand(1);
5230   DebugLoc dl = SVOp->getDebugLoc();
5231   EVT VT = SVOp->getValueType(0);
5232
5233   SmallVector<std::pair<int, int>, 8> Locs;
5234   Locs.resize(4);
5235   SmallVector<int, 8> Mask1(4U, -1);
5236   SmallVector<int, 8> PermMask;
5237   SVOp->getMask(PermMask);
5238
5239   unsigned NumHi = 0;
5240   unsigned NumLo = 0;
5241   for (unsigned i = 0; i != 4; ++i) {
5242     int Idx = PermMask[i];
5243     if (Idx < 0) {
5244       Locs[i] = std::make_pair(-1, -1);
5245     } else {
5246       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5247       if (Idx < 4) {
5248         Locs[i] = std::make_pair(0, NumLo);
5249         Mask1[NumLo] = Idx;
5250         NumLo++;
5251       } else {
5252         Locs[i] = std::make_pair(1, NumHi);
5253         if (2+NumHi < 4)
5254           Mask1[2+NumHi] = Idx;
5255         NumHi++;
5256       }
5257     }
5258   }
5259
5260   if (NumLo <= 2 && NumHi <= 2) {
5261     // If no more than two elements come from either vector. This can be
5262     // implemented with two shuffles. First shuffle gather the elements.
5263     // The second shuffle, which takes the first shuffle as both of its
5264     // vector operands, put the elements into the right order.
5265     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5266
5267     SmallVector<int, 8> Mask2(4U, -1);
5268
5269     for (unsigned i = 0; i != 4; ++i) {
5270       if (Locs[i].first == -1)
5271         continue;
5272       else {
5273         unsigned Idx = (i < 2) ? 0 : 4;
5274         Idx += Locs[i].first * 2 + Locs[i].second;
5275         Mask2[i] = Idx;
5276       }
5277     }
5278
5279     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5280   } else if (NumLo == 3 || NumHi == 3) {
5281     // Otherwise, we must have three elements from one vector, call it X, and
5282     // one element from the other, call it Y.  First, use a shufps to build an
5283     // intermediate vector with the one element from Y and the element from X
5284     // that will be in the same half in the final destination (the indexes don't
5285     // matter). Then, use a shufps to build the final vector, taking the half
5286     // containing the element from Y from the intermediate, and the other half
5287     // from X.
5288     if (NumHi == 3) {
5289       // Normalize it so the 3 elements come from V1.
5290       CommuteVectorShuffleMask(PermMask, VT);
5291       std::swap(V1, V2);
5292     }
5293
5294     // Find the element from V2.
5295     unsigned HiIndex;
5296     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5297       int Val = PermMask[HiIndex];
5298       if (Val < 0)
5299         continue;
5300       if (Val >= 4)
5301         break;
5302     }
5303
5304     Mask1[0] = PermMask[HiIndex];
5305     Mask1[1] = -1;
5306     Mask1[2] = PermMask[HiIndex^1];
5307     Mask1[3] = -1;
5308     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5309
5310     if (HiIndex >= 2) {
5311       Mask1[0] = PermMask[0];
5312       Mask1[1] = PermMask[1];
5313       Mask1[2] = HiIndex & 1 ? 6 : 4;
5314       Mask1[3] = HiIndex & 1 ? 4 : 6;
5315       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5316     } else {
5317       Mask1[0] = HiIndex & 1 ? 2 : 0;
5318       Mask1[1] = HiIndex & 1 ? 0 : 2;
5319       Mask1[2] = PermMask[2];
5320       Mask1[3] = PermMask[3];
5321       if (Mask1[2] >= 0)
5322         Mask1[2] += 4;
5323       if (Mask1[3] >= 0)
5324         Mask1[3] += 4;
5325       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5326     }
5327   }
5328
5329   // Break it into (shuffle shuffle_hi, shuffle_lo).
5330   Locs.clear();
5331   Locs.resize(4);
5332   SmallVector<int,8> LoMask(4U, -1);
5333   SmallVector<int,8> HiMask(4U, -1);
5334
5335   SmallVector<int,8> *MaskPtr = &LoMask;
5336   unsigned MaskIdx = 0;
5337   unsigned LoIdx = 0;
5338   unsigned HiIdx = 2;
5339   for (unsigned i = 0; i != 4; ++i) {
5340     if (i == 2) {
5341       MaskPtr = &HiMask;
5342       MaskIdx = 1;
5343       LoIdx = 0;
5344       HiIdx = 2;
5345     }
5346     int Idx = PermMask[i];
5347     if (Idx < 0) {
5348       Locs[i] = std::make_pair(-1, -1);
5349     } else if (Idx < 4) {
5350       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5351       (*MaskPtr)[LoIdx] = Idx;
5352       LoIdx++;
5353     } else {
5354       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5355       (*MaskPtr)[HiIdx] = Idx;
5356       HiIdx++;
5357     }
5358   }
5359
5360   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5361   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5362   SmallVector<int, 8> MaskOps;
5363   for (unsigned i = 0; i != 4; ++i) {
5364     if (Locs[i].first == -1) {
5365       MaskOps.push_back(-1);
5366     } else {
5367       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5368       MaskOps.push_back(Idx);
5369     }
5370   }
5371   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5372 }
5373
5374 static bool MayFoldVectorLoad(SDValue V) {
5375   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5376     V = V.getOperand(0);
5377   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5378     V = V.getOperand(0);
5379   if (MayFoldLoad(V))
5380     return true;
5381   return false;
5382 }
5383
5384 // FIXME: the version above should always be used. Since there's
5385 // a bug where several vector shuffles can't be folded because the
5386 // DAG is not updated during lowering and a node claims to have two
5387 // uses while it only has one, use this version, and let isel match
5388 // another instruction if the load really happens to have more than
5389 // one use. Remove this version after this bug get fixed.
5390 // rdar://8434668, PR8156
5391 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5392   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5393     V = V.getOperand(0);
5394   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5395     V = V.getOperand(0);
5396   if (ISD::isNormalLoad(V.getNode()))
5397     return true;
5398   return false;
5399 }
5400
5401 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5402 /// a vector extract, and if both can be later optimized into a single load.
5403 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5404 /// here because otherwise a target specific shuffle node is going to be
5405 /// emitted for this shuffle, and the optimization not done.
5406 /// FIXME: This is probably not the best approach, but fix the problem
5407 /// until the right path is decided.
5408 static
5409 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5410                                          const TargetLowering &TLI) {
5411   EVT VT = V.getValueType();
5412   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5413
5414   // Be sure that the vector shuffle is present in a pattern like this:
5415   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5416   if (!V.hasOneUse())
5417     return false;
5418
5419   SDNode *N = *V.getNode()->use_begin();
5420   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5421     return false;
5422
5423   SDValue EltNo = N->getOperand(1);
5424   if (!isa<ConstantSDNode>(EltNo))
5425     return false;
5426
5427   // If the bit convert changed the number of elements, it is unsafe
5428   // to examine the mask.
5429   bool HasShuffleIntoBitcast = false;
5430   if (V.getOpcode() == ISD::BITCAST) {
5431     EVT SrcVT = V.getOperand(0).getValueType();
5432     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5433       return false;
5434     V = V.getOperand(0);
5435     HasShuffleIntoBitcast = true;
5436   }
5437
5438   // Select the input vector, guarding against out of range extract vector.
5439   unsigned NumElems = VT.getVectorNumElements();
5440   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5441   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5442   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5443
5444   // Skip one more bit_convert if necessary
5445   if (V.getOpcode() == ISD::BITCAST)
5446     V = V.getOperand(0);
5447
5448   if (ISD::isNormalLoad(V.getNode())) {
5449     // Is the original load suitable?
5450     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5451
5452     // FIXME: avoid the multi-use bug that is preventing lots of
5453     // of foldings to be detected, this is still wrong of course, but
5454     // give the temporary desired behavior, and if it happens that
5455     // the load has real more uses, during isel it will not fold, and
5456     // will generate poor code.
5457     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5458       return false;
5459
5460     if (!HasShuffleIntoBitcast)
5461       return true;
5462
5463     // If there's a bitcast before the shuffle, check if the load type and
5464     // alignment is valid.
5465     unsigned Align = LN0->getAlignment();
5466     unsigned NewAlign =
5467       TLI.getTargetData()->getABITypeAlignment(
5468                                     VT.getTypeForEVT(*DAG.getContext()));
5469
5470     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5471       return false;
5472   }
5473
5474   return true;
5475 }
5476
5477 static
5478 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5479   EVT VT = Op.getValueType();
5480
5481   // Canonizalize to v2f64.
5482   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5483   return DAG.getNode(ISD::BITCAST, dl, VT,
5484                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5485                                           V1, DAG));
5486 }
5487
5488 static
5489 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5490                         bool HasSSE2) {
5491   SDValue V1 = Op.getOperand(0);
5492   SDValue V2 = Op.getOperand(1);
5493   EVT VT = Op.getValueType();
5494
5495   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5496
5497   if (HasSSE2 && VT == MVT::v2f64)
5498     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5499
5500   // v4f32 or v4i32
5501   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5502 }
5503
5504 static
5505 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5506   SDValue V1 = Op.getOperand(0);
5507   SDValue V2 = Op.getOperand(1);
5508   EVT VT = Op.getValueType();
5509
5510   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5511          "unsupported shuffle type");
5512
5513   if (V2.getOpcode() == ISD::UNDEF)
5514     V2 = V1;
5515
5516   // v4i32 or v4f32
5517   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5518 }
5519
5520 static
5521 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5522   SDValue V1 = Op.getOperand(0);
5523   SDValue V2 = Op.getOperand(1);
5524   EVT VT = Op.getValueType();
5525   unsigned NumElems = VT.getVectorNumElements();
5526
5527   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5528   // operand of these instructions is only memory, so check if there's a
5529   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5530   // same masks.
5531   bool CanFoldLoad = false;
5532
5533   // Trivial case, when V2 comes from a load.
5534   if (MayFoldVectorLoad(V2))
5535     CanFoldLoad = true;
5536
5537   // When V1 is a load, it can be folded later into a store in isel, example:
5538   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5539   //    turns into:
5540   //  (MOVLPSmr addr:$src1, VR128:$src2)
5541   // So, recognize this potential and also use MOVLPS or MOVLPD
5542   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5543     CanFoldLoad = true;
5544
5545   // Both of them can't be memory operations though.
5546   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
5547     CanFoldLoad = false;
5548
5549   if (CanFoldLoad) {
5550     if (HasSSE2 && NumElems == 2)
5551       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5552
5553     if (NumElems == 4)
5554       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5555   }
5556
5557   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5558   // movl and movlp will both match v2i64, but v2i64 is never matched by
5559   // movl earlier because we make it strict to avoid messing with the movlp load
5560   // folding logic (see the code above getMOVLP call). Match it here then,
5561   // this is horrible, but will stay like this until we move all shuffle
5562   // matching to x86 specific nodes. Note that for the 1st condition all
5563   // types are matched with movsd.
5564   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5565     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5566   else if (HasSSE2)
5567     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5568
5569
5570   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5571
5572   // Invert the operand order and use SHUFPS to match it.
5573   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5574                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5575 }
5576
5577 static inline unsigned getUNPCKLOpcode(EVT VT, const X86Subtarget *Subtarget) {
5578   switch(VT.getSimpleVT().SimpleTy) {
5579   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5580   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5581   case MVT::v4f32:
5582     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPS : X86ISD::UNPCKLPS;
5583   case MVT::v2f64:
5584     return Subtarget->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5585   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
5586   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
5587   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5588   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5589   default:
5590     llvm_unreachable("Unknown type for unpckl");
5591   }
5592   return 0;
5593 }
5594
5595 static inline unsigned getUNPCKHOpcode(EVT VT) {
5596   switch(VT.getSimpleVT().SimpleTy) {
5597   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5598   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5599   case MVT::v4f32: return X86ISD::UNPCKHPS;
5600   case MVT::v2f64: return X86ISD::UNPCKHPD;
5601   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5602   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5603   default:
5604     llvm_unreachable("Unknown type for unpckh");
5605   }
5606   return 0;
5607 }
5608
5609 static
5610 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5611                                const TargetLowering &TLI,
5612                                const X86Subtarget *Subtarget) {
5613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5614   EVT VT = Op.getValueType();
5615   DebugLoc dl = Op.getDebugLoc();
5616   SDValue V1 = Op.getOperand(0);
5617   SDValue V2 = Op.getOperand(1);
5618
5619   if (isZeroShuffle(SVOp))
5620     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5621
5622   // Handle splat operations
5623   if (SVOp->isSplat()) {
5624     // Special case, this is the only place now where it's
5625     // allowed to return a vector_shuffle operation without
5626     // using a target specific node, because *hopefully* it
5627     // will be optimized away by the dag combiner.
5628     if (VT.getVectorNumElements() <= 4 &&
5629         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5630       return Op;
5631
5632     // Handle splats by matching through known masks
5633     if (VT.getVectorNumElements() <= 4)
5634       return SDValue();
5635
5636     // Canonicalize all of the remaining to v4f32.
5637     return PromoteSplat(SVOp, DAG);
5638   }
5639
5640   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5641   // do it!
5642   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5643     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5644     if (NewOp.getNode())
5645       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5646   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5647     // FIXME: Figure out a cleaner way to do this.
5648     // Try to make use of movq to zero out the top part.
5649     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5650       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5651       if (NewOp.getNode()) {
5652         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5653           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5654                               DAG, Subtarget, dl);
5655       }
5656     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5657       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5658       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5659         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5660                             DAG, Subtarget, dl);
5661     }
5662   }
5663   return SDValue();
5664 }
5665
5666 SDValue
5667 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5668   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5669   SDValue V1 = Op.getOperand(0);
5670   SDValue V2 = Op.getOperand(1);
5671   EVT VT = Op.getValueType();
5672   DebugLoc dl = Op.getDebugLoc();
5673   unsigned NumElems = VT.getVectorNumElements();
5674   bool isMMX = VT.getSizeInBits() == 64;
5675   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5676   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5677   bool V1IsSplat = false;
5678   bool V2IsSplat = false;
5679   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5680   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5681   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5682   MachineFunction &MF = DAG.getMachineFunction();
5683   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5684
5685   // Shuffle operations on MMX not supported.
5686   if (isMMX)
5687     return Op;
5688
5689   // Vector shuffle lowering takes 3 steps:
5690   //
5691   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5692   //    narrowing and commutation of operands should be handled.
5693   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5694   //    shuffle nodes.
5695   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5696   //    so the shuffle can be broken into other shuffles and the legalizer can
5697   //    try the lowering again.
5698   //
5699   // The general ideia is that no vector_shuffle operation should be left to
5700   // be matched during isel, all of them must be converted to a target specific
5701   // node here.
5702
5703   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5704   // narrowing and commutation of operands should be handled. The actual code
5705   // doesn't include all of those, work in progress...
5706   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5707   if (NewOp.getNode())
5708     return NewOp;
5709
5710   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5711   // unpckh_undef). Only use pshufd if speed is more important than size.
5712   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5713     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5714       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()), dl, VT, V1, V1, DAG);
5715   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5716     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5717       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5718
5719   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5720       RelaxedMayFoldVectorLoad(V1))
5721     return getMOVDDup(Op, dl, V1, DAG);
5722
5723   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5724     return getMOVHighToLow(Op, dl, DAG);
5725
5726   // Use to match splats
5727   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5728       (VT == MVT::v2f64 || VT == MVT::v2i64))
5729     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5730
5731   if (X86::isPSHUFDMask(SVOp)) {
5732     // The actual implementation will match the mask in the if above and then
5733     // during isel it can match several different instructions, not only pshufd
5734     // as its name says, sad but true, emulate the behavior for now...
5735     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5736         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5737
5738     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5739
5740     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5741       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5742
5743     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5744       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5745                                   TargetMask, DAG);
5746
5747     if (VT == MVT::v4f32)
5748       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5749                                   TargetMask, DAG);
5750   }
5751
5752   // Check if this can be converted into a logical shift.
5753   bool isLeft = false;
5754   unsigned ShAmt = 0;
5755   SDValue ShVal;
5756   bool isShift = getSubtarget()->hasSSE2() &&
5757     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5758   if (isShift && ShVal.hasOneUse()) {
5759     // If the shifted value has multiple uses, it may be cheaper to use
5760     // v_set0 + movlhps or movhlps, etc.
5761     EVT EltVT = VT.getVectorElementType();
5762     ShAmt *= EltVT.getSizeInBits();
5763     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5764   }
5765
5766   if (X86::isMOVLMask(SVOp)) {
5767     if (V1IsUndef)
5768       return V2;
5769     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5770       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5771     if (!X86::isMOVLPMask(SVOp)) {
5772       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5773         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5774
5775       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5776         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5777     }
5778   }
5779
5780   // FIXME: fold these into legal mask.
5781   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5782     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5783
5784   if (X86::isMOVHLPSMask(SVOp))
5785     return getMOVHighToLow(Op, dl, DAG);
5786
5787   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5788     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5789
5790   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5791     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5792
5793   if (X86::isMOVLPMask(SVOp))
5794     return getMOVLP(Op, dl, DAG, HasSSE2);
5795
5796   if (ShouldXformToMOVHLPS(SVOp) ||
5797       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5798     return CommuteVectorShuffle(SVOp, DAG);
5799
5800   if (isShift) {
5801     // No better options. Use a vshl / vsrl.
5802     EVT EltVT = VT.getVectorElementType();
5803     ShAmt *= EltVT.getSizeInBits();
5804     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5805   }
5806
5807   bool Commuted = false;
5808   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5809   // 1,1,1,1 -> v8i16 though.
5810   V1IsSplat = isSplatVector(V1.getNode());
5811   V2IsSplat = isSplatVector(V2.getNode());
5812
5813   // Canonicalize the splat or undef, if present, to be on the RHS.
5814   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5815     Op = CommuteVectorShuffle(SVOp, DAG);
5816     SVOp = cast<ShuffleVectorSDNode>(Op);
5817     V1 = SVOp->getOperand(0);
5818     V2 = SVOp->getOperand(1);
5819     std::swap(V1IsSplat, V2IsSplat);
5820     std::swap(V1IsUndef, V2IsUndef);
5821     Commuted = true;
5822   }
5823
5824   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5825     // Shuffling low element of v1 into undef, just return v1.
5826     if (V2IsUndef)
5827       return V1;
5828     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5829     // the instruction selector will not match, so get a canonical MOVL with
5830     // swapped operands to undo the commute.
5831     return getMOVL(DAG, dl, VT, V2, V1);
5832   }
5833
5834   if (X86::isUNPCKLMask(SVOp))
5835     return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5836                                 dl, VT, V1, V2, DAG);
5837
5838   if (X86::isUNPCKHMask(SVOp))
5839     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5840
5841   if (V2IsSplat) {
5842     // Normalize mask so all entries that point to V2 points to its first
5843     // element then try to match unpck{h|l} again. If match, return a
5844     // new vector_shuffle with the corrected mask.
5845     SDValue NewMask = NormalizeMask(SVOp, DAG);
5846     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5847     if (NSVOp != SVOp) {
5848       if (X86::isUNPCKLMask(NSVOp, true)) {
5849         return NewMask;
5850       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5851         return NewMask;
5852       }
5853     }
5854   }
5855
5856   if (Commuted) {
5857     // Commute is back and try unpck* again.
5858     // FIXME: this seems wrong.
5859     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5860     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5861
5862     if (X86::isUNPCKLMask(NewSVOp))
5863       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5864                                   dl, VT, V2, V1, DAG);
5865
5866     if (X86::isUNPCKHMask(NewSVOp))
5867       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5868   }
5869
5870   // Normalize the node to match x86 shuffle ops if needed
5871   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5872     return CommuteVectorShuffle(SVOp, DAG);
5873
5874   // The checks below are all present in isShuffleMaskLegal, but they are
5875   // inlined here right now to enable us to directly emit target specific
5876   // nodes, and remove one by one until they don't return Op anymore.
5877   SmallVector<int, 16> M;
5878   SVOp->getMask(M);
5879
5880   if (isPALIGNRMask(M, VT, HasSSSE3))
5881     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5882                                 X86::getShufflePALIGNRImmediate(SVOp),
5883                                 DAG);
5884
5885   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5886       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5887     if (VT == MVT::v2f64) {
5888       X86ISD::NodeType Opcode =
5889         getSubtarget()->hasAVX() ? X86ISD::VUNPCKLPD : X86ISD::UNPCKLPD;
5890       return getTargetShuffleNode(Opcode, dl, VT, V1, V1, DAG);
5891     }
5892     if (VT == MVT::v2i64)
5893       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5894   }
5895
5896   if (isPSHUFHWMask(M, VT))
5897     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5898                                 X86::getShufflePSHUFHWImmediate(SVOp),
5899                                 DAG);
5900
5901   if (isPSHUFLWMask(M, VT))
5902     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5903                                 X86::getShufflePSHUFLWImmediate(SVOp),
5904                                 DAG);
5905
5906   if (isSHUFPMask(M, VT)) {
5907     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5908     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5909       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5910                                   TargetMask, DAG);
5911     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5912       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5913                                   TargetMask, DAG);
5914   }
5915
5916   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5917     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5918       return getTargetShuffleNode(getUNPCKLOpcode(VT, getSubtarget()),
5919                                   dl, VT, V1, V1, DAG);
5920   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5921     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5922       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5923
5924   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5925   if (VT == MVT::v8i16) {
5926     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5927     if (NewOp.getNode())
5928       return NewOp;
5929   }
5930
5931   if (VT == MVT::v16i8) {
5932     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5933     if (NewOp.getNode())
5934       return NewOp;
5935   }
5936
5937   // Handle all 4 wide cases with a number of shuffles.
5938   if (NumElems == 4)
5939     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5940
5941   return SDValue();
5942 }
5943
5944 SDValue
5945 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5946                                                 SelectionDAG &DAG) const {
5947   EVT VT = Op.getValueType();
5948   DebugLoc dl = Op.getDebugLoc();
5949   if (VT.getSizeInBits() == 8) {
5950     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5951                                     Op.getOperand(0), Op.getOperand(1));
5952     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5953                                     DAG.getValueType(VT));
5954     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5955   } else if (VT.getSizeInBits() == 16) {
5956     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5957     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5958     if (Idx == 0)
5959       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5960                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5961                                      DAG.getNode(ISD::BITCAST, dl,
5962                                                  MVT::v4i32,
5963                                                  Op.getOperand(0)),
5964                                      Op.getOperand(1)));
5965     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5966                                     Op.getOperand(0), Op.getOperand(1));
5967     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5968                                     DAG.getValueType(VT));
5969     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5970   } else if (VT == MVT::f32) {
5971     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5972     // the result back to FR32 register. It's only worth matching if the
5973     // result has a single use which is a store or a bitcast to i32.  And in
5974     // the case of a store, it's not worth it if the index is a constant 0,
5975     // because a MOVSSmr can be used instead, which is smaller and faster.
5976     if (!Op.hasOneUse())
5977       return SDValue();
5978     SDNode *User = *Op.getNode()->use_begin();
5979     if ((User->getOpcode() != ISD::STORE ||
5980          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5981           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5982         (User->getOpcode() != ISD::BITCAST ||
5983          User->getValueType(0) != MVT::i32))
5984       return SDValue();
5985     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5986                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5987                                               Op.getOperand(0)),
5988                                               Op.getOperand(1));
5989     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5990   } else if (VT == MVT::i32) {
5991     // ExtractPS works with constant index.
5992     if (isa<ConstantSDNode>(Op.getOperand(1)))
5993       return Op;
5994   }
5995   return SDValue();
5996 }
5997
5998
5999 SDValue
6000 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6001                                            SelectionDAG &DAG) const {
6002   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6003     return SDValue();
6004
6005   SDValue Vec = Op.getOperand(0);
6006   EVT VecVT = Vec.getValueType();
6007
6008   // If this is a 256-bit vector result, first extract the 128-bit
6009   // vector and then extract from the 128-bit vector.
6010   if (VecVT.getSizeInBits() > 128) {
6011     DebugLoc dl = Op.getNode()->getDebugLoc();
6012     unsigned NumElems = VecVT.getVectorNumElements();
6013     SDValue Idx = Op.getOperand(1);
6014
6015     if (!isa<ConstantSDNode>(Idx))
6016       return SDValue();
6017
6018     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
6019     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6020
6021     // Get the 128-bit vector.
6022     bool Upper = IdxVal >= ExtractNumElems;
6023     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
6024
6025     // Extract from it.
6026     SDValue ScaledIdx = Idx;
6027     if (Upper)
6028       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
6029                               DAG.getConstant(ExtractNumElems,
6030                                               Idx.getValueType()));
6031     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6032                        ScaledIdx);
6033   }
6034
6035   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6036
6037   if (Subtarget->hasSSE41()) {
6038     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6039     if (Res.getNode())
6040       return Res;
6041   }
6042
6043   EVT VT = Op.getValueType();
6044   DebugLoc dl = Op.getDebugLoc();
6045   // TODO: handle v16i8.
6046   if (VT.getSizeInBits() == 16) {
6047     SDValue Vec = Op.getOperand(0);
6048     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6049     if (Idx == 0)
6050       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6051                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6052                                      DAG.getNode(ISD::BITCAST, dl,
6053                                                  MVT::v4i32, Vec),
6054                                      Op.getOperand(1)));
6055     // Transform it so it match pextrw which produces a 32-bit result.
6056     EVT EltVT = MVT::i32;
6057     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6058                                     Op.getOperand(0), Op.getOperand(1));
6059     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6060                                     DAG.getValueType(VT));
6061     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6062   } else if (VT.getSizeInBits() == 32) {
6063     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6064     if (Idx == 0)
6065       return Op;
6066
6067     // SHUFPS the element to the lowest double word, then movss.
6068     int Mask[4] = { Idx, -1, -1, -1 };
6069     EVT VVT = Op.getOperand(0).getValueType();
6070     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6071                                        DAG.getUNDEF(VVT), Mask);
6072     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6073                        DAG.getIntPtrConstant(0));
6074   } else if (VT.getSizeInBits() == 64) {
6075     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6076     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6077     //        to match extract_elt for f64.
6078     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6079     if (Idx == 0)
6080       return Op;
6081
6082     // UNPCKHPD the element to the lowest double word, then movsd.
6083     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6084     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6085     int Mask[2] = { 1, -1 };
6086     EVT VVT = Op.getOperand(0).getValueType();
6087     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6088                                        DAG.getUNDEF(VVT), Mask);
6089     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6090                        DAG.getIntPtrConstant(0));
6091   }
6092
6093   return SDValue();
6094 }
6095
6096 SDValue
6097 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6098                                                SelectionDAG &DAG) const {
6099   EVT VT = Op.getValueType();
6100   EVT EltVT = VT.getVectorElementType();
6101   DebugLoc dl = Op.getDebugLoc();
6102
6103   SDValue N0 = Op.getOperand(0);
6104   SDValue N1 = Op.getOperand(1);
6105   SDValue N2 = Op.getOperand(2);
6106
6107   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6108       isa<ConstantSDNode>(N2)) {
6109     unsigned Opc;
6110     if (VT == MVT::v8i16)
6111       Opc = X86ISD::PINSRW;
6112     else if (VT == MVT::v16i8)
6113       Opc = X86ISD::PINSRB;
6114     else
6115       Opc = X86ISD::PINSRB;
6116
6117     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6118     // argument.
6119     if (N1.getValueType() != MVT::i32)
6120       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6121     if (N2.getValueType() != MVT::i32)
6122       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6123     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6124   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6125     // Bits [7:6] of the constant are the source select.  This will always be
6126     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6127     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6128     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6129     // Bits [5:4] of the constant are the destination select.  This is the
6130     //  value of the incoming immediate.
6131     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6132     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6133     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6134     // Create this as a scalar to vector..
6135     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6136     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6137   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6138     // PINSR* works with constant index.
6139     return Op;
6140   }
6141   return SDValue();
6142 }
6143
6144 SDValue
6145 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6146   EVT VT = Op.getValueType();
6147   EVT EltVT = VT.getVectorElementType();
6148
6149   DebugLoc dl = Op.getDebugLoc();
6150   SDValue N0 = Op.getOperand(0);
6151   SDValue N1 = Op.getOperand(1);
6152   SDValue N2 = Op.getOperand(2);
6153
6154   // If this is a 256-bit vector result, first insert into a 128-bit
6155   // vector and then insert into the 256-bit vector.
6156   if (VT.getSizeInBits() > 128) {
6157     if (!isa<ConstantSDNode>(N2))
6158       return SDValue();
6159
6160     // Get the 128-bit vector.
6161     unsigned NumElems = VT.getVectorNumElements();
6162     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6163     bool Upper = IdxVal >= NumElems / 2;
6164
6165     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6166
6167     // Insert into it.
6168     SDValue ScaledN2 = N2;
6169     if (Upper)
6170       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6171                              DAG.getConstant(NumElems /
6172                                              (VT.getSizeInBits() / 128),
6173                                              N2.getValueType()));
6174     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6175                      N1, ScaledN2);
6176
6177     // Insert the 128-bit vector
6178     // FIXME: Why UNDEF?
6179     return Insert128BitVector(N0, Op, N2, DAG, dl);
6180   }
6181
6182   if (Subtarget->hasSSE41())
6183     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6184
6185   if (EltVT == MVT::i8)
6186     return SDValue();
6187
6188   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6189     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6190     // as its second argument.
6191     if (N1.getValueType() != MVT::i32)
6192       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6193     if (N2.getValueType() != MVT::i32)
6194       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6195     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6196   }
6197   return SDValue();
6198 }
6199
6200 SDValue
6201 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6202   LLVMContext *Context = DAG.getContext();
6203   DebugLoc dl = Op.getDebugLoc();
6204   EVT OpVT = Op.getValueType();
6205
6206   // If this is a 256-bit vector result, first insert into a 128-bit
6207   // vector and then insert into the 256-bit vector.
6208   if (OpVT.getSizeInBits() > 128) {
6209     // Insert into a 128-bit vector.
6210     EVT VT128 = EVT::getVectorVT(*Context,
6211                                  OpVT.getVectorElementType(),
6212                                  OpVT.getVectorNumElements() / 2);
6213
6214     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6215
6216     // Insert the 128-bit vector.
6217     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6218                               DAG.getConstant(0, MVT::i32),
6219                               DAG, dl);
6220   }
6221
6222   if (Op.getValueType() == MVT::v1i64 &&
6223       Op.getOperand(0).getValueType() == MVT::i64)
6224     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6225
6226   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6227   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6228          "Expected an SSE type!");
6229   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6230                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6231 }
6232
6233 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6234 // a simple subregister reference or explicit instructions to grab
6235 // upper bits of a vector.
6236 SDValue
6237 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6238   if (Subtarget->hasAVX()) {
6239     DebugLoc dl = Op.getNode()->getDebugLoc();
6240     SDValue Vec = Op.getNode()->getOperand(0);
6241     SDValue Idx = Op.getNode()->getOperand(1);
6242
6243     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6244         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6245         return Extract128BitVector(Vec, Idx, DAG, dl);
6246     }
6247   }
6248   return SDValue();
6249 }
6250
6251 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6252 // simple superregister reference or explicit instructions to insert
6253 // the upper bits of a vector.
6254 SDValue
6255 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6256   if (Subtarget->hasAVX()) {
6257     DebugLoc dl = Op.getNode()->getDebugLoc();
6258     SDValue Vec = Op.getNode()->getOperand(0);
6259     SDValue SubVec = Op.getNode()->getOperand(1);
6260     SDValue Idx = Op.getNode()->getOperand(2);
6261
6262     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6263         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6264       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6265     }
6266   }
6267   return SDValue();
6268 }
6269
6270 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6271 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6272 // one of the above mentioned nodes. It has to be wrapped because otherwise
6273 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6274 // be used to form addressing mode. These wrapped nodes will be selected
6275 // into MOV32ri.
6276 SDValue
6277 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6278   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6279
6280   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6281   // global base reg.
6282   unsigned char OpFlag = 0;
6283   unsigned WrapperKind = X86ISD::Wrapper;
6284   CodeModel::Model M = getTargetMachine().getCodeModel();
6285
6286   if (Subtarget->isPICStyleRIPRel() &&
6287       (M == CodeModel::Small || M == CodeModel::Kernel))
6288     WrapperKind = X86ISD::WrapperRIP;
6289   else if (Subtarget->isPICStyleGOT())
6290     OpFlag = X86II::MO_GOTOFF;
6291   else if (Subtarget->isPICStyleStubPIC())
6292     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6293
6294   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6295                                              CP->getAlignment(),
6296                                              CP->getOffset(), OpFlag);
6297   DebugLoc DL = CP->getDebugLoc();
6298   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6299   // With PIC, the address is actually $g + Offset.
6300   if (OpFlag) {
6301     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6302                          DAG.getNode(X86ISD::GlobalBaseReg,
6303                                      DebugLoc(), getPointerTy()),
6304                          Result);
6305   }
6306
6307   return Result;
6308 }
6309
6310 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6311   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6312
6313   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6314   // global base reg.
6315   unsigned char OpFlag = 0;
6316   unsigned WrapperKind = X86ISD::Wrapper;
6317   CodeModel::Model M = getTargetMachine().getCodeModel();
6318
6319   if (Subtarget->isPICStyleRIPRel() &&
6320       (M == CodeModel::Small || M == CodeModel::Kernel))
6321     WrapperKind = X86ISD::WrapperRIP;
6322   else if (Subtarget->isPICStyleGOT())
6323     OpFlag = X86II::MO_GOTOFF;
6324   else if (Subtarget->isPICStyleStubPIC())
6325     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6326
6327   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6328                                           OpFlag);
6329   DebugLoc DL = JT->getDebugLoc();
6330   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6331
6332   // With PIC, the address is actually $g + Offset.
6333   if (OpFlag)
6334     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6335                          DAG.getNode(X86ISD::GlobalBaseReg,
6336                                      DebugLoc(), getPointerTy()),
6337                          Result);
6338
6339   return Result;
6340 }
6341
6342 SDValue
6343 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6344   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6345
6346   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6347   // global base reg.
6348   unsigned char OpFlag = 0;
6349   unsigned WrapperKind = X86ISD::Wrapper;
6350   CodeModel::Model M = getTargetMachine().getCodeModel();
6351
6352   if (Subtarget->isPICStyleRIPRel() &&
6353       (M == CodeModel::Small || M == CodeModel::Kernel))
6354     WrapperKind = X86ISD::WrapperRIP;
6355   else if (Subtarget->isPICStyleGOT())
6356     OpFlag = X86II::MO_GOTOFF;
6357   else if (Subtarget->isPICStyleStubPIC())
6358     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6359
6360   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6361
6362   DebugLoc DL = Op.getDebugLoc();
6363   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6364
6365
6366   // With PIC, the address is actually $g + Offset.
6367   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6368       !Subtarget->is64Bit()) {
6369     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6370                          DAG.getNode(X86ISD::GlobalBaseReg,
6371                                      DebugLoc(), getPointerTy()),
6372                          Result);
6373   }
6374
6375   return Result;
6376 }
6377
6378 SDValue
6379 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6380   // Create the TargetBlockAddressAddress node.
6381   unsigned char OpFlags =
6382     Subtarget->ClassifyBlockAddressReference();
6383   CodeModel::Model M = getTargetMachine().getCodeModel();
6384   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6385   DebugLoc dl = Op.getDebugLoc();
6386   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6387                                        /*isTarget=*/true, OpFlags);
6388
6389   if (Subtarget->isPICStyleRIPRel() &&
6390       (M == CodeModel::Small || M == CodeModel::Kernel))
6391     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6392   else
6393     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6394
6395   // With PIC, the address is actually $g + Offset.
6396   if (isGlobalRelativeToPICBase(OpFlags)) {
6397     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6398                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6399                          Result);
6400   }
6401
6402   return Result;
6403 }
6404
6405 SDValue
6406 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6407                                       int64_t Offset,
6408                                       SelectionDAG &DAG) const {
6409   // Create the TargetGlobalAddress node, folding in the constant
6410   // offset if it is legal.
6411   unsigned char OpFlags =
6412     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6413   CodeModel::Model M = getTargetMachine().getCodeModel();
6414   SDValue Result;
6415   if (OpFlags == X86II::MO_NO_FLAG &&
6416       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6417     // A direct static reference to a global.
6418     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6419     Offset = 0;
6420   } else {
6421     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6422   }
6423
6424   if (Subtarget->isPICStyleRIPRel() &&
6425       (M == CodeModel::Small || M == CodeModel::Kernel))
6426     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6427   else
6428     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6429
6430   // With PIC, the address is actually $g + Offset.
6431   if (isGlobalRelativeToPICBase(OpFlags)) {
6432     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6433                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6434                          Result);
6435   }
6436
6437   // For globals that require a load from a stub to get the address, emit the
6438   // load.
6439   if (isGlobalStubReference(OpFlags))
6440     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6441                          MachinePointerInfo::getGOT(), false, false, 0);
6442
6443   // If there was a non-zero offset that we didn't fold, create an explicit
6444   // addition for it.
6445   if (Offset != 0)
6446     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6447                          DAG.getConstant(Offset, getPointerTy()));
6448
6449   return Result;
6450 }
6451
6452 SDValue
6453 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6454   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6455   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6456   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6457 }
6458
6459 static SDValue
6460 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6461            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6462            unsigned char OperandFlags) {
6463   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6464   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6465   DebugLoc dl = GA->getDebugLoc();
6466   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6467                                            GA->getValueType(0),
6468                                            GA->getOffset(),
6469                                            OperandFlags);
6470   if (InFlag) {
6471     SDValue Ops[] = { Chain,  TGA, *InFlag };
6472     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6473   } else {
6474     SDValue Ops[]  = { Chain, TGA };
6475     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6476   }
6477
6478   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6479   MFI->setAdjustsStack(true);
6480
6481   SDValue Flag = Chain.getValue(1);
6482   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6483 }
6484
6485 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6486 static SDValue
6487 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6488                                 const EVT PtrVT) {
6489   SDValue InFlag;
6490   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6491   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6492                                      DAG.getNode(X86ISD::GlobalBaseReg,
6493                                                  DebugLoc(), PtrVT), InFlag);
6494   InFlag = Chain.getValue(1);
6495
6496   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6497 }
6498
6499 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6500 static SDValue
6501 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6502                                 const EVT PtrVT) {
6503   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6504                     X86::RAX, X86II::MO_TLSGD);
6505 }
6506
6507 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6508 // "local exec" model.
6509 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6510                                    const EVT PtrVT, TLSModel::Model model,
6511                                    bool is64Bit) {
6512   DebugLoc dl = GA->getDebugLoc();
6513
6514   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6515   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6516                                                          is64Bit ? 257 : 256));
6517
6518   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6519                                       DAG.getIntPtrConstant(0),
6520                                       MachinePointerInfo(Ptr), false, false, 0);
6521
6522   unsigned char OperandFlags = 0;
6523   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6524   // initialexec.
6525   unsigned WrapperKind = X86ISD::Wrapper;
6526   if (model == TLSModel::LocalExec) {
6527     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6528   } else if (is64Bit) {
6529     assert(model == TLSModel::InitialExec);
6530     OperandFlags = X86II::MO_GOTTPOFF;
6531     WrapperKind = X86ISD::WrapperRIP;
6532   } else {
6533     assert(model == TLSModel::InitialExec);
6534     OperandFlags = X86II::MO_INDNTPOFF;
6535   }
6536
6537   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6538   // exec)
6539   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6540                                            GA->getValueType(0),
6541                                            GA->getOffset(), OperandFlags);
6542   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6543
6544   if (model == TLSModel::InitialExec)
6545     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6546                          MachinePointerInfo::getGOT(), false, false, 0);
6547
6548   // The address of the thread local variable is the add of the thread
6549   // pointer with the offset of the variable.
6550   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6551 }
6552
6553 SDValue
6554 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6555
6556   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6557   const GlobalValue *GV = GA->getGlobal();
6558
6559   if (Subtarget->isTargetELF()) {
6560     // TODO: implement the "local dynamic" model
6561     // TODO: implement the "initial exec"model for pic executables
6562
6563     // If GV is an alias then use the aliasee for determining
6564     // thread-localness.
6565     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6566       GV = GA->resolveAliasedGlobal(false);
6567
6568     TLSModel::Model model
6569       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6570
6571     switch (model) {
6572       case TLSModel::GeneralDynamic:
6573       case TLSModel::LocalDynamic: // not implemented
6574         if (Subtarget->is64Bit())
6575           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6576         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6577
6578       case TLSModel::InitialExec:
6579       case TLSModel::LocalExec:
6580         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6581                                    Subtarget->is64Bit());
6582     }
6583   } else if (Subtarget->isTargetDarwin()) {
6584     // Darwin only has one model of TLS.  Lower to that.
6585     unsigned char OpFlag = 0;
6586     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6587                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6588
6589     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6590     // global base reg.
6591     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6592                   !Subtarget->is64Bit();
6593     if (PIC32)
6594       OpFlag = X86II::MO_TLVP_PIC_BASE;
6595     else
6596       OpFlag = X86II::MO_TLVP;
6597     DebugLoc DL = Op.getDebugLoc();
6598     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6599                                                 GA->getValueType(0),
6600                                                 GA->getOffset(), OpFlag);
6601     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6602
6603     // With PIC32, the address is actually $g + Offset.
6604     if (PIC32)
6605       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6606                            DAG.getNode(X86ISD::GlobalBaseReg,
6607                                        DebugLoc(), getPointerTy()),
6608                            Offset);
6609
6610     // Lowering the machine isd will make sure everything is in the right
6611     // location.
6612     SDValue Chain = DAG.getEntryNode();
6613     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6614     SDValue Args[] = { Chain, Offset };
6615     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6616
6617     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6618     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6619     MFI->setAdjustsStack(true);
6620
6621     // And our return value (tls address) is in the standard call return value
6622     // location.
6623     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6624     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6625   }
6626
6627   assert(false &&
6628          "TLS not implemented for this target.");
6629
6630   llvm_unreachable("Unreachable");
6631   return SDValue();
6632 }
6633
6634
6635 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
6636 /// take a 2 x i32 value to shift plus a shift amount.
6637 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
6638   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6639   EVT VT = Op.getValueType();
6640   unsigned VTBits = VT.getSizeInBits();
6641   DebugLoc dl = Op.getDebugLoc();
6642   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6643   SDValue ShOpLo = Op.getOperand(0);
6644   SDValue ShOpHi = Op.getOperand(1);
6645   SDValue ShAmt  = Op.getOperand(2);
6646   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6647                                      DAG.getConstant(VTBits - 1, MVT::i8))
6648                        : DAG.getConstant(0, VT);
6649
6650   SDValue Tmp2, Tmp3;
6651   if (Op.getOpcode() == ISD::SHL_PARTS) {
6652     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6653     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6654   } else {
6655     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6656     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6657   }
6658
6659   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6660                                 DAG.getConstant(VTBits, MVT::i8));
6661   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6662                              AndNode, DAG.getConstant(0, MVT::i8));
6663
6664   SDValue Hi, Lo;
6665   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6666   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6667   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6668
6669   if (Op.getOpcode() == ISD::SHL_PARTS) {
6670     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6671     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6672   } else {
6673     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6674     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6675   }
6676
6677   SDValue Ops[2] = { Lo, Hi };
6678   return DAG.getMergeValues(Ops, 2, dl);
6679 }
6680
6681 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6682                                            SelectionDAG &DAG) const {
6683   EVT SrcVT = Op.getOperand(0).getValueType();
6684
6685   if (SrcVT.isVector())
6686     return SDValue();
6687
6688   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6689          "Unknown SINT_TO_FP to lower!");
6690
6691   // These are really Legal; return the operand so the caller accepts it as
6692   // Legal.
6693   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6694     return Op;
6695   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6696       Subtarget->is64Bit()) {
6697     return Op;
6698   }
6699
6700   DebugLoc dl = Op.getDebugLoc();
6701   unsigned Size = SrcVT.getSizeInBits()/8;
6702   MachineFunction &MF = DAG.getMachineFunction();
6703   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6704   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6705   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6706                                StackSlot,
6707                                MachinePointerInfo::getFixedStack(SSFI),
6708                                false, false, 0);
6709   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6710 }
6711
6712 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6713                                      SDValue StackSlot,
6714                                      SelectionDAG &DAG) const {
6715   // Build the FILD
6716   DebugLoc DL = Op.getDebugLoc();
6717   SDVTList Tys;
6718   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6719   if (useSSE)
6720     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6721   else
6722     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6723
6724   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6725
6726   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6727   MachineMemOperand *MMO =
6728     DAG.getMachineFunction()
6729     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6730                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6731
6732   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6733   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6734                                            X86ISD::FILD, DL,
6735                                            Tys, Ops, array_lengthof(Ops),
6736                                            SrcVT, MMO);
6737
6738   if (useSSE) {
6739     Chain = Result.getValue(1);
6740     SDValue InFlag = Result.getValue(2);
6741
6742     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6743     // shouldn't be necessary except that RFP cannot be live across
6744     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6745     MachineFunction &MF = DAG.getMachineFunction();
6746     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6747     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6748     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6749     Tys = DAG.getVTList(MVT::Other);
6750     SDValue Ops[] = {
6751       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6752     };
6753     MachineMemOperand *MMO =
6754       DAG.getMachineFunction()
6755       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6756                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6757
6758     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6759                                     Ops, array_lengthof(Ops),
6760                                     Op.getValueType(), MMO);
6761     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6762                          MachinePointerInfo::getFixedStack(SSFI),
6763                          false, false, 0);
6764   }
6765
6766   return Result;
6767 }
6768
6769 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6770 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6771                                                SelectionDAG &DAG) const {
6772   // This algorithm is not obvious. Here it is in C code, more or less:
6773   /*
6774     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6775       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6776       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6777
6778       // Copy ints to xmm registers.
6779       __m128i xh = _mm_cvtsi32_si128( hi );
6780       __m128i xl = _mm_cvtsi32_si128( lo );
6781
6782       // Combine into low half of a single xmm register.
6783       __m128i x = _mm_unpacklo_epi32( xh, xl );
6784       __m128d d;
6785       double sd;
6786
6787       // Merge in appropriate exponents to give the integer bits the right
6788       // magnitude.
6789       x = _mm_unpacklo_epi32( x, exp );
6790
6791       // Subtract away the biases to deal with the IEEE-754 double precision
6792       // implicit 1.
6793       d = _mm_sub_pd( (__m128d) x, bias );
6794
6795       // All conversions up to here are exact. The correctly rounded result is
6796       // calculated using the current rounding mode using the following
6797       // horizontal add.
6798       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6799       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6800                                 // store doesn't really need to be here (except
6801                                 // maybe to zero the other double)
6802       return sd;
6803     }
6804   */
6805
6806   DebugLoc dl = Op.getDebugLoc();
6807   LLVMContext *Context = DAG.getContext();
6808
6809   // Build some magic constants.
6810   std::vector<Constant*> CV0;
6811   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6812   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6813   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6814   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6815   Constant *C0 = ConstantVector::get(CV0);
6816   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6817
6818   std::vector<Constant*> CV1;
6819   CV1.push_back(
6820     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6821   CV1.push_back(
6822     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6823   Constant *C1 = ConstantVector::get(CV1);
6824   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6825
6826   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6827                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6828                                         Op.getOperand(0),
6829                                         DAG.getIntPtrConstant(1)));
6830   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6831                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6832                                         Op.getOperand(0),
6833                                         DAG.getIntPtrConstant(0)));
6834   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6835   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6836                               MachinePointerInfo::getConstantPool(),
6837                               false, false, 16);
6838   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6839   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6840   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6841                               MachinePointerInfo::getConstantPool(),
6842                               false, false, 16);
6843   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6844
6845   // Add the halves; easiest way is to swap them into another reg first.
6846   int ShufMask[2] = { 1, -1 };
6847   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6848                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6849   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6850   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6851                      DAG.getIntPtrConstant(0));
6852 }
6853
6854 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6855 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6856                                                SelectionDAG &DAG) const {
6857   DebugLoc dl = Op.getDebugLoc();
6858   // FP constant to bias correct the final result.
6859   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6860                                    MVT::f64);
6861
6862   // Load the 32-bit value into an XMM register.
6863   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6864                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6865                                          Op.getOperand(0),
6866                                          DAG.getIntPtrConstant(0)));
6867
6868   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6869                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6870                      DAG.getIntPtrConstant(0));
6871
6872   // Or the load with the bias.
6873   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6874                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6875                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6876                                                    MVT::v2f64, Load)),
6877                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6878                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6879                                                    MVT::v2f64, Bias)));
6880   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6881                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6882                    DAG.getIntPtrConstant(0));
6883
6884   // Subtract the bias.
6885   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6886
6887   // Handle final rounding.
6888   EVT DestVT = Op.getValueType();
6889
6890   if (DestVT.bitsLT(MVT::f64)) {
6891     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6892                        DAG.getIntPtrConstant(0));
6893   } else if (DestVT.bitsGT(MVT::f64)) {
6894     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6895   }
6896
6897   // Handle final rounding.
6898   return Sub;
6899 }
6900
6901 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6902                                            SelectionDAG &DAG) const {
6903   SDValue N0 = Op.getOperand(0);
6904   DebugLoc dl = Op.getDebugLoc();
6905
6906   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6907   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6908   // the optimization here.
6909   if (DAG.SignBitIsZero(N0))
6910     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6911
6912   EVT SrcVT = N0.getValueType();
6913   EVT DstVT = Op.getValueType();
6914   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6915     return LowerUINT_TO_FP_i64(Op, DAG);
6916   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6917     return LowerUINT_TO_FP_i32(Op, DAG);
6918
6919   // Make a 64-bit buffer, and use it to build an FILD.
6920   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6921   if (SrcVT == MVT::i32) {
6922     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6923     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6924                                      getPointerTy(), StackSlot, WordOff);
6925     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6926                                   StackSlot, MachinePointerInfo(),
6927                                   false, false, 0);
6928     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6929                                   OffsetSlot, MachinePointerInfo(),
6930                                   false, false, 0);
6931     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6932     return Fild;
6933   }
6934
6935   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6936   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6937                                 StackSlot, MachinePointerInfo(),
6938                                false, false, 0);
6939   // For i64 source, we need to add the appropriate power of 2 if the input
6940   // was negative.  This is the same as the optimization in
6941   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6942   // we must be careful to do the computation in x87 extended precision, not
6943   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6944   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6945   MachineMemOperand *MMO =
6946     DAG.getMachineFunction()
6947     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6948                           MachineMemOperand::MOLoad, 8, 8);
6949
6950   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6951   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6952   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6953                                          MVT::i64, MMO);
6954
6955   APInt FF(32, 0x5F800000ULL);
6956
6957   // Check whether the sign bit is set.
6958   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6959                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6960                                  ISD::SETLT);
6961
6962   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6963   SDValue FudgePtr = DAG.getConstantPool(
6964                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6965                                          getPointerTy());
6966
6967   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6968   SDValue Zero = DAG.getIntPtrConstant(0);
6969   SDValue Four = DAG.getIntPtrConstant(4);
6970   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6971                                Zero, Four);
6972   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6973
6974   // Load the value out, extending it from f32 to f80.
6975   // FIXME: Avoid the extend by constructing the right constant pool?
6976   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
6977                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6978                                  MVT::f32, false, false, 4);
6979   // Extend everything to 80 bits to force it to be done on x87.
6980   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6981   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6982 }
6983
6984 std::pair<SDValue,SDValue> X86TargetLowering::
6985 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6986   DebugLoc DL = Op.getDebugLoc();
6987
6988   EVT DstTy = Op.getValueType();
6989
6990   if (!IsSigned) {
6991     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6992     DstTy = MVT::i64;
6993   }
6994
6995   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6996          DstTy.getSimpleVT() >= MVT::i16 &&
6997          "Unknown FP_TO_SINT to lower!");
6998
6999   // These are really Legal.
7000   if (DstTy == MVT::i32 &&
7001       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7002     return std::make_pair(SDValue(), SDValue());
7003   if (Subtarget->is64Bit() &&
7004       DstTy == MVT::i64 &&
7005       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7006     return std::make_pair(SDValue(), SDValue());
7007
7008   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7009   // stack slot.
7010   MachineFunction &MF = DAG.getMachineFunction();
7011   unsigned MemSize = DstTy.getSizeInBits()/8;
7012   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7013   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7014
7015
7016
7017   unsigned Opc;
7018   switch (DstTy.getSimpleVT().SimpleTy) {
7019   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7020   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7021   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7022   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7023   }
7024
7025   SDValue Chain = DAG.getEntryNode();
7026   SDValue Value = Op.getOperand(0);
7027   EVT TheVT = Op.getOperand(0).getValueType();
7028   if (isScalarFPTypeInSSEReg(TheVT)) {
7029     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7030     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7031                          MachinePointerInfo::getFixedStack(SSFI),
7032                          false, false, 0);
7033     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7034     SDValue Ops[] = {
7035       Chain, StackSlot, DAG.getValueType(TheVT)
7036     };
7037
7038     MachineMemOperand *MMO =
7039       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7040                               MachineMemOperand::MOLoad, MemSize, MemSize);
7041     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7042                                     DstTy, MMO);
7043     Chain = Value.getValue(1);
7044     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7045     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7046   }
7047
7048   MachineMemOperand *MMO =
7049     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7050                             MachineMemOperand::MOStore, MemSize, MemSize);
7051
7052   // Build the FP_TO_INT*_IN_MEM
7053   SDValue Ops[] = { Chain, Value, StackSlot };
7054   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7055                                          Ops, 3, DstTy, MMO);
7056
7057   return std::make_pair(FIST, StackSlot);
7058 }
7059
7060 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7061                                            SelectionDAG &DAG) const {
7062   if (Op.getValueType().isVector())
7063     return SDValue();
7064
7065   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7066   SDValue FIST = Vals.first, StackSlot = Vals.second;
7067   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7068   if (FIST.getNode() == 0) return Op;
7069
7070   // Load the result.
7071   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7072                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7073 }
7074
7075 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7076                                            SelectionDAG &DAG) const {
7077   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7078   SDValue FIST = Vals.first, StackSlot = Vals.second;
7079   assert(FIST.getNode() && "Unexpected failure");
7080
7081   // Load the result.
7082   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7083                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7084 }
7085
7086 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7087                                      SelectionDAG &DAG) const {
7088   LLVMContext *Context = DAG.getContext();
7089   DebugLoc dl = Op.getDebugLoc();
7090   EVT VT = Op.getValueType();
7091   EVT EltVT = VT;
7092   if (VT.isVector())
7093     EltVT = VT.getVectorElementType();
7094   std::vector<Constant*> CV;
7095   if (EltVT == MVT::f64) {
7096     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7097     CV.push_back(C);
7098     CV.push_back(C);
7099   } else {
7100     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7101     CV.push_back(C);
7102     CV.push_back(C);
7103     CV.push_back(C);
7104     CV.push_back(C);
7105   }
7106   Constant *C = ConstantVector::get(CV);
7107   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7108   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7109                              MachinePointerInfo::getConstantPool(),
7110                              false, false, 16);
7111   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7112 }
7113
7114 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7115   LLVMContext *Context = DAG.getContext();
7116   DebugLoc dl = Op.getDebugLoc();
7117   EVT VT = Op.getValueType();
7118   EVT EltVT = VT;
7119   if (VT.isVector())
7120     EltVT = VT.getVectorElementType();
7121   std::vector<Constant*> CV;
7122   if (EltVT == MVT::f64) {
7123     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7124     CV.push_back(C);
7125     CV.push_back(C);
7126   } else {
7127     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7128     CV.push_back(C);
7129     CV.push_back(C);
7130     CV.push_back(C);
7131     CV.push_back(C);
7132   }
7133   Constant *C = ConstantVector::get(CV);
7134   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7135   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7136                              MachinePointerInfo::getConstantPool(),
7137                              false, false, 16);
7138   if (VT.isVector()) {
7139     return DAG.getNode(ISD::BITCAST, dl, VT,
7140                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7141                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7142                                 Op.getOperand(0)),
7143                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7144   } else {
7145     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7146   }
7147 }
7148
7149 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7150   LLVMContext *Context = DAG.getContext();
7151   SDValue Op0 = Op.getOperand(0);
7152   SDValue Op1 = Op.getOperand(1);
7153   DebugLoc dl = Op.getDebugLoc();
7154   EVT VT = Op.getValueType();
7155   EVT SrcVT = Op1.getValueType();
7156
7157   // If second operand is smaller, extend it first.
7158   if (SrcVT.bitsLT(VT)) {
7159     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7160     SrcVT = VT;
7161   }
7162   // And if it is bigger, shrink it first.
7163   if (SrcVT.bitsGT(VT)) {
7164     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7165     SrcVT = VT;
7166   }
7167
7168   // At this point the operands and the result should have the same
7169   // type, and that won't be f80 since that is not custom lowered.
7170
7171   // First get the sign bit of second operand.
7172   std::vector<Constant*> CV;
7173   if (SrcVT == MVT::f64) {
7174     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7175     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7176   } else {
7177     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7178     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7179     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7180     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7181   }
7182   Constant *C = ConstantVector::get(CV);
7183   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7184   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7185                               MachinePointerInfo::getConstantPool(),
7186                               false, false, 16);
7187   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7188
7189   // Shift sign bit right or left if the two operands have different types.
7190   if (SrcVT.bitsGT(VT)) {
7191     // Op0 is MVT::f32, Op1 is MVT::f64.
7192     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7193     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7194                           DAG.getConstant(32, MVT::i32));
7195     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7196     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7197                           DAG.getIntPtrConstant(0));
7198   }
7199
7200   // Clear first operand sign bit.
7201   CV.clear();
7202   if (VT == MVT::f64) {
7203     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7204     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7205   } else {
7206     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7207     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7208     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7209     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7210   }
7211   C = ConstantVector::get(CV);
7212   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7213   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7214                               MachinePointerInfo::getConstantPool(),
7215                               false, false, 16);
7216   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7217
7218   // Or the value with the sign bit.
7219   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7220 }
7221
7222 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7223   SDValue N0 = Op.getOperand(0);
7224   DebugLoc dl = Op.getDebugLoc();
7225   EVT VT = Op.getValueType();
7226
7227   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7228   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7229                                   DAG.getConstant(1, VT));
7230   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7231 }
7232
7233 /// Emit nodes that will be selected as "test Op0,Op0", or something
7234 /// equivalent.
7235 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7236                                     SelectionDAG &DAG) const {
7237   DebugLoc dl = Op.getDebugLoc();
7238
7239   // CF and OF aren't always set the way we want. Determine which
7240   // of these we need.
7241   bool NeedCF = false;
7242   bool NeedOF = false;
7243   switch (X86CC) {
7244   default: break;
7245   case X86::COND_A: case X86::COND_AE:
7246   case X86::COND_B: case X86::COND_BE:
7247     NeedCF = true;
7248     break;
7249   case X86::COND_G: case X86::COND_GE:
7250   case X86::COND_L: case X86::COND_LE:
7251   case X86::COND_O: case X86::COND_NO:
7252     NeedOF = true;
7253     break;
7254   }
7255
7256   // See if we can use the EFLAGS value from the operand instead of
7257   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7258   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7259   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7260     // Emit a CMP with 0, which is the TEST pattern.
7261     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7262                        DAG.getConstant(0, Op.getValueType()));
7263
7264   unsigned Opcode = 0;
7265   unsigned NumOperands = 0;
7266   switch (Op.getNode()->getOpcode()) {
7267   case ISD::ADD:
7268     // Due to an isel shortcoming, be conservative if this add is likely to be
7269     // selected as part of a load-modify-store instruction. When the root node
7270     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7271     // uses of other nodes in the match, such as the ADD in this case. This
7272     // leads to the ADD being left around and reselected, with the result being
7273     // two adds in the output.  Alas, even if none our users are stores, that
7274     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7275     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7276     // climbing the DAG back to the root, and it doesn't seem to be worth the
7277     // effort.
7278     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7279            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7280       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7281         goto default_case;
7282
7283     if (ConstantSDNode *C =
7284         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7285       // An add of one will be selected as an INC.
7286       if (C->getAPIntValue() == 1) {
7287         Opcode = X86ISD::INC;
7288         NumOperands = 1;
7289         break;
7290       }
7291
7292       // An add of negative one (subtract of one) will be selected as a DEC.
7293       if (C->getAPIntValue().isAllOnesValue()) {
7294         Opcode = X86ISD::DEC;
7295         NumOperands = 1;
7296         break;
7297       }
7298     }
7299
7300     // Otherwise use a regular EFLAGS-setting add.
7301     Opcode = X86ISD::ADD;
7302     NumOperands = 2;
7303     break;
7304   case ISD::AND: {
7305     // If the primary and result isn't used, don't bother using X86ISD::AND,
7306     // because a TEST instruction will be better.
7307     bool NonFlagUse = false;
7308     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7309            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7310       SDNode *User = *UI;
7311       unsigned UOpNo = UI.getOperandNo();
7312       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7313         // Look pass truncate.
7314         UOpNo = User->use_begin().getOperandNo();
7315         User = *User->use_begin();
7316       }
7317
7318       if (User->getOpcode() != ISD::BRCOND &&
7319           User->getOpcode() != ISD::SETCC &&
7320           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7321         NonFlagUse = true;
7322         break;
7323       }
7324     }
7325
7326     if (!NonFlagUse)
7327       break;
7328   }
7329     // FALL THROUGH
7330   case ISD::SUB:
7331   case ISD::OR:
7332   case ISD::XOR:
7333     // Due to the ISEL shortcoming noted above, be conservative if this op is
7334     // likely to be selected as part of a load-modify-store instruction.
7335     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7336            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7337       if (UI->getOpcode() == ISD::STORE)
7338         goto default_case;
7339
7340     // Otherwise use a regular EFLAGS-setting instruction.
7341     switch (Op.getNode()->getOpcode()) {
7342     default: llvm_unreachable("unexpected operator!");
7343     case ISD::SUB: Opcode = X86ISD::SUB; break;
7344     case ISD::OR:  Opcode = X86ISD::OR;  break;
7345     case ISD::XOR: Opcode = X86ISD::XOR; break;
7346     case ISD::AND: Opcode = X86ISD::AND; break;
7347     }
7348
7349     NumOperands = 2;
7350     break;
7351   case X86ISD::ADD:
7352   case X86ISD::SUB:
7353   case X86ISD::INC:
7354   case X86ISD::DEC:
7355   case X86ISD::OR:
7356   case X86ISD::XOR:
7357   case X86ISD::AND:
7358     return SDValue(Op.getNode(), 1);
7359   default:
7360   default_case:
7361     break;
7362   }
7363
7364   if (Opcode == 0)
7365     // Emit a CMP with 0, which is the TEST pattern.
7366     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7367                        DAG.getConstant(0, Op.getValueType()));
7368
7369   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7370   SmallVector<SDValue, 4> Ops;
7371   for (unsigned i = 0; i != NumOperands; ++i)
7372     Ops.push_back(Op.getOperand(i));
7373
7374   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7375   DAG.ReplaceAllUsesWith(Op, New);
7376   return SDValue(New.getNode(), 1);
7377 }
7378
7379 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7380 /// equivalent.
7381 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7382                                    SelectionDAG &DAG) const {
7383   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7384     if (C->getAPIntValue() == 0)
7385       return EmitTest(Op0, X86CC, DAG);
7386
7387   DebugLoc dl = Op0.getDebugLoc();
7388   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7389 }
7390
7391 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7392 /// if it's possible.
7393 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7394                                      DebugLoc dl, SelectionDAG &DAG) const {
7395   SDValue Op0 = And.getOperand(0);
7396   SDValue Op1 = And.getOperand(1);
7397   if (Op0.getOpcode() == ISD::TRUNCATE)
7398     Op0 = Op0.getOperand(0);
7399   if (Op1.getOpcode() == ISD::TRUNCATE)
7400     Op1 = Op1.getOperand(0);
7401
7402   SDValue LHS, RHS;
7403   if (Op1.getOpcode() == ISD::SHL)
7404     std::swap(Op0, Op1);
7405   if (Op0.getOpcode() == ISD::SHL) {
7406     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7407       if (And00C->getZExtValue() == 1) {
7408         // If we looked past a truncate, check that it's only truncating away
7409         // known zeros.
7410         unsigned BitWidth = Op0.getValueSizeInBits();
7411         unsigned AndBitWidth = And.getValueSizeInBits();
7412         if (BitWidth > AndBitWidth) {
7413           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7414           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7415           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7416             return SDValue();
7417         }
7418         LHS = Op1;
7419         RHS = Op0.getOperand(1);
7420       }
7421   } else if (Op1.getOpcode() == ISD::Constant) {
7422     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7423     SDValue AndLHS = Op0;
7424     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7425       LHS = AndLHS.getOperand(0);
7426       RHS = AndLHS.getOperand(1);
7427     }
7428   }
7429
7430   if (LHS.getNode()) {
7431     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7432     // instruction.  Since the shift amount is in-range-or-undefined, we know
7433     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7434     // the encoding for the i16 version is larger than the i32 version.
7435     // Also promote i16 to i32 for performance / code size reason.
7436     if (LHS.getValueType() == MVT::i8 ||
7437         LHS.getValueType() == MVT::i16)
7438       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7439
7440     // If the operand types disagree, extend the shift amount to match.  Since
7441     // BT ignores high bits (like shifts) we can use anyextend.
7442     if (LHS.getValueType() != RHS.getValueType())
7443       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7444
7445     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7446     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7447     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7448                        DAG.getConstant(Cond, MVT::i8), BT);
7449   }
7450
7451   return SDValue();
7452 }
7453
7454 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7455   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7456   SDValue Op0 = Op.getOperand(0);
7457   SDValue Op1 = Op.getOperand(1);
7458   DebugLoc dl = Op.getDebugLoc();
7459   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7460
7461   // Optimize to BT if possible.
7462   // Lower (X & (1 << N)) == 0 to BT(X, N).
7463   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7464   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7465   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7466       Op1.getOpcode() == ISD::Constant &&
7467       cast<ConstantSDNode>(Op1)->isNullValue() &&
7468       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7469     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7470     if (NewSetCC.getNode())
7471       return NewSetCC;
7472   }
7473
7474   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7475   // these.
7476   if (Op1.getOpcode() == ISD::Constant &&
7477       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7478        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7479       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7480
7481     // If the input is a setcc, then reuse the input setcc or use a new one with
7482     // the inverted condition.
7483     if (Op0.getOpcode() == X86ISD::SETCC) {
7484       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7485       bool Invert = (CC == ISD::SETNE) ^
7486         cast<ConstantSDNode>(Op1)->isNullValue();
7487       if (!Invert) return Op0;
7488
7489       CCode = X86::GetOppositeBranchCondition(CCode);
7490       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7491                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7492     }
7493   }
7494
7495   bool isFP = Op1.getValueType().isFloatingPoint();
7496   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7497   if (X86CC == X86::COND_INVALID)
7498     return SDValue();
7499
7500   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7501   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7502                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7503 }
7504
7505 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7506   SDValue Cond;
7507   SDValue Op0 = Op.getOperand(0);
7508   SDValue Op1 = Op.getOperand(1);
7509   SDValue CC = Op.getOperand(2);
7510   EVT VT = Op.getValueType();
7511   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7512   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7513   DebugLoc dl = Op.getDebugLoc();
7514
7515   if (isFP) {
7516     unsigned SSECC = 8;
7517     EVT VT0 = Op0.getValueType();
7518     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7519     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7520     bool Swap = false;
7521
7522     switch (SetCCOpcode) {
7523     default: break;
7524     case ISD::SETOEQ:
7525     case ISD::SETEQ:  SSECC = 0; break;
7526     case ISD::SETOGT:
7527     case ISD::SETGT: Swap = true; // Fallthrough
7528     case ISD::SETLT:
7529     case ISD::SETOLT: SSECC = 1; break;
7530     case ISD::SETOGE:
7531     case ISD::SETGE: Swap = true; // Fallthrough
7532     case ISD::SETLE:
7533     case ISD::SETOLE: SSECC = 2; break;
7534     case ISD::SETUO:  SSECC = 3; break;
7535     case ISD::SETUNE:
7536     case ISD::SETNE:  SSECC = 4; break;
7537     case ISD::SETULE: Swap = true;
7538     case ISD::SETUGE: SSECC = 5; break;
7539     case ISD::SETULT: Swap = true;
7540     case ISD::SETUGT: SSECC = 6; break;
7541     case ISD::SETO:   SSECC = 7; break;
7542     }
7543     if (Swap)
7544       std::swap(Op0, Op1);
7545
7546     // In the two special cases we can't handle, emit two comparisons.
7547     if (SSECC == 8) {
7548       if (SetCCOpcode == ISD::SETUEQ) {
7549         SDValue UNORD, EQ;
7550         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7551         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7552         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7553       }
7554       else if (SetCCOpcode == ISD::SETONE) {
7555         SDValue ORD, NEQ;
7556         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7557         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7558         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7559       }
7560       llvm_unreachable("Illegal FP comparison");
7561     }
7562     // Handle all other FP comparisons here.
7563     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7564   }
7565
7566   // We are handling one of the integer comparisons here.  Since SSE only has
7567   // GT and EQ comparisons for integer, swapping operands and multiple
7568   // operations may be required for some comparisons.
7569   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7570   bool Swap = false, Invert = false, FlipSigns = false;
7571
7572   switch (VT.getSimpleVT().SimpleTy) {
7573   default: break;
7574   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7575   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7576   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7577   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7578   }
7579
7580   switch (SetCCOpcode) {
7581   default: break;
7582   case ISD::SETNE:  Invert = true;
7583   case ISD::SETEQ:  Opc = EQOpc; break;
7584   case ISD::SETLT:  Swap = true;
7585   case ISD::SETGT:  Opc = GTOpc; break;
7586   case ISD::SETGE:  Swap = true;
7587   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7588   case ISD::SETULT: Swap = true;
7589   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7590   case ISD::SETUGE: Swap = true;
7591   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7592   }
7593   if (Swap)
7594     std::swap(Op0, Op1);
7595
7596   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7597   // bits of the inputs before performing those operations.
7598   if (FlipSigns) {
7599     EVT EltVT = VT.getVectorElementType();
7600     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7601                                       EltVT);
7602     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7603     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7604                                     SignBits.size());
7605     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7606     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7607   }
7608
7609   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7610
7611   // If the logical-not of the result is required, perform that now.
7612   if (Invert)
7613     Result = DAG.getNOT(dl, Result, VT);
7614
7615   return Result;
7616 }
7617
7618 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7619 static bool isX86LogicalCmp(SDValue Op) {
7620   unsigned Opc = Op.getNode()->getOpcode();
7621   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7622     return true;
7623   if (Op.getResNo() == 1 &&
7624       (Opc == X86ISD::ADD ||
7625        Opc == X86ISD::SUB ||
7626        Opc == X86ISD::ADC ||
7627        Opc == X86ISD::SBB ||
7628        Opc == X86ISD::SMUL ||
7629        Opc == X86ISD::UMUL ||
7630        Opc == X86ISD::INC ||
7631        Opc == X86ISD::DEC ||
7632        Opc == X86ISD::OR ||
7633        Opc == X86ISD::XOR ||
7634        Opc == X86ISD::AND))
7635     return true;
7636
7637   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7638     return true;
7639
7640   return false;
7641 }
7642
7643 static bool isZero(SDValue V) {
7644   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7645   return C && C->isNullValue();
7646 }
7647
7648 static bool isAllOnes(SDValue V) {
7649   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7650   return C && C->isAllOnesValue();
7651 }
7652
7653 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7654   bool addTest = true;
7655   SDValue Cond  = Op.getOperand(0);
7656   SDValue Op1 = Op.getOperand(1);
7657   SDValue Op2 = Op.getOperand(2);
7658   DebugLoc DL = Op.getDebugLoc();
7659   SDValue CC;
7660
7661   if (Cond.getOpcode() == ISD::SETCC) {
7662     SDValue NewCond = LowerSETCC(Cond, DAG);
7663     if (NewCond.getNode())
7664       Cond = NewCond;
7665   }
7666
7667   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7668   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7669   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7670   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7671   if (Cond.getOpcode() == X86ISD::SETCC &&
7672       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7673       isZero(Cond.getOperand(1).getOperand(1))) {
7674     SDValue Cmp = Cond.getOperand(1);
7675
7676     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7677
7678     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7679         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7680       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7681
7682       SDValue CmpOp0 = Cmp.getOperand(0);
7683       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7684                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7685
7686       SDValue Res =   // Res = 0 or -1.
7687         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7688                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7689
7690       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7691         Res = DAG.getNOT(DL, Res, Res.getValueType());
7692
7693       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7694       if (N2C == 0 || !N2C->isNullValue())
7695         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7696       return Res;
7697     }
7698   }
7699
7700   // Look past (and (setcc_carry (cmp ...)), 1).
7701   if (Cond.getOpcode() == ISD::AND &&
7702       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7703     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7704     if (C && C->getAPIntValue() == 1)
7705       Cond = Cond.getOperand(0);
7706   }
7707
7708   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7709   // setting operand in place of the X86ISD::SETCC.
7710   if (Cond.getOpcode() == X86ISD::SETCC ||
7711       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7712     CC = Cond.getOperand(0);
7713
7714     SDValue Cmp = Cond.getOperand(1);
7715     unsigned Opc = Cmp.getOpcode();
7716     EVT VT = Op.getValueType();
7717
7718     bool IllegalFPCMov = false;
7719     if (VT.isFloatingPoint() && !VT.isVector() &&
7720         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7721       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7722
7723     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7724         Opc == X86ISD::BT) { // FIXME
7725       Cond = Cmp;
7726       addTest = false;
7727     }
7728   }
7729
7730   if (addTest) {
7731     // Look pass the truncate.
7732     if (Cond.getOpcode() == ISD::TRUNCATE)
7733       Cond = Cond.getOperand(0);
7734
7735     // We know the result of AND is compared against zero. Try to match
7736     // it to BT.
7737     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7738       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7739       if (NewSetCC.getNode()) {
7740         CC = NewSetCC.getOperand(0);
7741         Cond = NewSetCC.getOperand(1);
7742         addTest = false;
7743       }
7744     }
7745   }
7746
7747   if (addTest) {
7748     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7749     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7750   }
7751
7752   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7753   // a <  b ?  0 : -1 -> RES = setcc_carry
7754   // a >= b ? -1 :  0 -> RES = setcc_carry
7755   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7756   if (Cond.getOpcode() == X86ISD::CMP) {
7757     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7758
7759     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7760         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7761       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7762                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7763       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7764         return DAG.getNOT(DL, Res, Res.getValueType());
7765       return Res;
7766     }
7767   }
7768
7769   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7770   // condition is true.
7771   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7772   SDValue Ops[] = { Op2, Op1, CC, Cond };
7773   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7774 }
7775
7776 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7777 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7778 // from the AND / OR.
7779 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7780   Opc = Op.getOpcode();
7781   if (Opc != ISD::OR && Opc != ISD::AND)
7782     return false;
7783   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7784           Op.getOperand(0).hasOneUse() &&
7785           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7786           Op.getOperand(1).hasOneUse());
7787 }
7788
7789 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7790 // 1 and that the SETCC node has a single use.
7791 static bool isXor1OfSetCC(SDValue Op) {
7792   if (Op.getOpcode() != ISD::XOR)
7793     return false;
7794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7795   if (N1C && N1C->getAPIntValue() == 1) {
7796     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7797       Op.getOperand(0).hasOneUse();
7798   }
7799   return false;
7800 }
7801
7802 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7803   bool addTest = true;
7804   SDValue Chain = Op.getOperand(0);
7805   SDValue Cond  = Op.getOperand(1);
7806   SDValue Dest  = Op.getOperand(2);
7807   DebugLoc dl = Op.getDebugLoc();
7808   SDValue CC;
7809
7810   if (Cond.getOpcode() == ISD::SETCC) {
7811     SDValue NewCond = LowerSETCC(Cond, DAG);
7812     if (NewCond.getNode())
7813       Cond = NewCond;
7814   }
7815 #if 0
7816   // FIXME: LowerXALUO doesn't handle these!!
7817   else if (Cond.getOpcode() == X86ISD::ADD  ||
7818            Cond.getOpcode() == X86ISD::SUB  ||
7819            Cond.getOpcode() == X86ISD::SMUL ||
7820            Cond.getOpcode() == X86ISD::UMUL)
7821     Cond = LowerXALUO(Cond, DAG);
7822 #endif
7823
7824   // Look pass (and (setcc_carry (cmp ...)), 1).
7825   if (Cond.getOpcode() == ISD::AND &&
7826       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7827     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7828     if (C && C->getAPIntValue() == 1)
7829       Cond = Cond.getOperand(0);
7830   }
7831
7832   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7833   // setting operand in place of the X86ISD::SETCC.
7834   if (Cond.getOpcode() == X86ISD::SETCC ||
7835       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7836     CC = Cond.getOperand(0);
7837
7838     SDValue Cmp = Cond.getOperand(1);
7839     unsigned Opc = Cmp.getOpcode();
7840     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7841     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7842       Cond = Cmp;
7843       addTest = false;
7844     } else {
7845       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7846       default: break;
7847       case X86::COND_O:
7848       case X86::COND_B:
7849         // These can only come from an arithmetic instruction with overflow,
7850         // e.g. SADDO, UADDO.
7851         Cond = Cond.getNode()->getOperand(1);
7852         addTest = false;
7853         break;
7854       }
7855     }
7856   } else {
7857     unsigned CondOpc;
7858     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7859       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7860       if (CondOpc == ISD::OR) {
7861         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7862         // two branches instead of an explicit OR instruction with a
7863         // separate test.
7864         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7865             isX86LogicalCmp(Cmp)) {
7866           CC = Cond.getOperand(0).getOperand(0);
7867           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7868                               Chain, Dest, CC, Cmp);
7869           CC = Cond.getOperand(1).getOperand(0);
7870           Cond = Cmp;
7871           addTest = false;
7872         }
7873       } else { // ISD::AND
7874         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7875         // two branches instead of an explicit AND instruction with a
7876         // separate test. However, we only do this if this block doesn't
7877         // have a fall-through edge, because this requires an explicit
7878         // jmp when the condition is false.
7879         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7880             isX86LogicalCmp(Cmp) &&
7881             Op.getNode()->hasOneUse()) {
7882           X86::CondCode CCode =
7883             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7884           CCode = X86::GetOppositeBranchCondition(CCode);
7885           CC = DAG.getConstant(CCode, MVT::i8);
7886           SDNode *User = *Op.getNode()->use_begin();
7887           // Look for an unconditional branch following this conditional branch.
7888           // We need this because we need to reverse the successors in order
7889           // to implement FCMP_OEQ.
7890           if (User->getOpcode() == ISD::BR) {
7891             SDValue FalseBB = User->getOperand(1);
7892             SDNode *NewBR =
7893               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7894             assert(NewBR == User);
7895             (void)NewBR;
7896             Dest = FalseBB;
7897
7898             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7899                                 Chain, Dest, CC, Cmp);
7900             X86::CondCode CCode =
7901               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7902             CCode = X86::GetOppositeBranchCondition(CCode);
7903             CC = DAG.getConstant(CCode, MVT::i8);
7904             Cond = Cmp;
7905             addTest = false;
7906           }
7907         }
7908       }
7909     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7910       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7911       // It should be transformed during dag combiner except when the condition
7912       // is set by a arithmetics with overflow node.
7913       X86::CondCode CCode =
7914         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7915       CCode = X86::GetOppositeBranchCondition(CCode);
7916       CC = DAG.getConstant(CCode, MVT::i8);
7917       Cond = Cond.getOperand(0).getOperand(1);
7918       addTest = false;
7919     }
7920   }
7921
7922   if (addTest) {
7923     // Look pass the truncate.
7924     if (Cond.getOpcode() == ISD::TRUNCATE)
7925       Cond = Cond.getOperand(0);
7926
7927     // We know the result of AND is compared against zero. Try to match
7928     // it to BT.
7929     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7930       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7931       if (NewSetCC.getNode()) {
7932         CC = NewSetCC.getOperand(0);
7933         Cond = NewSetCC.getOperand(1);
7934         addTest = false;
7935       }
7936     }
7937   }
7938
7939   if (addTest) {
7940     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7941     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7942   }
7943   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7944                      Chain, Dest, CC, Cond);
7945 }
7946
7947
7948 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7949 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7950 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7951 // that the guard pages used by the OS virtual memory manager are allocated in
7952 // correct sequence.
7953 SDValue
7954 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7955                                            SelectionDAG &DAG) const {
7956   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7957          "This should be used only on Windows targets");
7958   assert(!Subtarget->isTargetEnvMacho());
7959   DebugLoc dl = Op.getDebugLoc();
7960
7961   // Get the inputs.
7962   SDValue Chain = Op.getOperand(0);
7963   SDValue Size  = Op.getOperand(1);
7964   // FIXME: Ensure alignment here
7965
7966   SDValue Flag;
7967
7968   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7969   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
7970
7971   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
7972   Flag = Chain.getValue(1);
7973
7974   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7975
7976   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7977   Flag = Chain.getValue(1);
7978
7979   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7980
7981   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7982   return DAG.getMergeValues(Ops1, 2, dl);
7983 }
7984
7985 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7986   MachineFunction &MF = DAG.getMachineFunction();
7987   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7988
7989   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7990   DebugLoc DL = Op.getDebugLoc();
7991
7992   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7993     // vastart just stores the address of the VarArgsFrameIndex slot into the
7994     // memory location argument.
7995     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7996                                    getPointerTy());
7997     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7998                         MachinePointerInfo(SV), false, false, 0);
7999   }
8000
8001   // __va_list_tag:
8002   //   gp_offset         (0 - 6 * 8)
8003   //   fp_offset         (48 - 48 + 8 * 16)
8004   //   overflow_arg_area (point to parameters coming in memory).
8005   //   reg_save_area
8006   SmallVector<SDValue, 8> MemOps;
8007   SDValue FIN = Op.getOperand(1);
8008   // Store gp_offset
8009   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8010                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8011                                                MVT::i32),
8012                                FIN, MachinePointerInfo(SV), false, false, 0);
8013   MemOps.push_back(Store);
8014
8015   // Store fp_offset
8016   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8017                     FIN, DAG.getIntPtrConstant(4));
8018   Store = DAG.getStore(Op.getOperand(0), DL,
8019                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8020                                        MVT::i32),
8021                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8022   MemOps.push_back(Store);
8023
8024   // Store ptr to overflow_arg_area
8025   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8026                     FIN, DAG.getIntPtrConstant(4));
8027   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8028                                     getPointerTy());
8029   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8030                        MachinePointerInfo(SV, 8),
8031                        false, false, 0);
8032   MemOps.push_back(Store);
8033
8034   // Store ptr to reg_save_area.
8035   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8036                     FIN, DAG.getIntPtrConstant(8));
8037   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8038                                     getPointerTy());
8039   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8040                        MachinePointerInfo(SV, 16), false, false, 0);
8041   MemOps.push_back(Store);
8042   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8043                      &MemOps[0], MemOps.size());
8044 }
8045
8046 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8047   assert(Subtarget->is64Bit() &&
8048          "LowerVAARG only handles 64-bit va_arg!");
8049   assert((Subtarget->isTargetLinux() ||
8050           Subtarget->isTargetDarwin()) &&
8051           "Unhandled target in LowerVAARG");
8052   assert(Op.getNode()->getNumOperands() == 4);
8053   SDValue Chain = Op.getOperand(0);
8054   SDValue SrcPtr = Op.getOperand(1);
8055   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8056   unsigned Align = Op.getConstantOperandVal(3);
8057   DebugLoc dl = Op.getDebugLoc();
8058
8059   EVT ArgVT = Op.getNode()->getValueType(0);
8060   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8061   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8062   uint8_t ArgMode;
8063
8064   // Decide which area this value should be read from.
8065   // TODO: Implement the AMD64 ABI in its entirety. This simple
8066   // selection mechanism works only for the basic types.
8067   if (ArgVT == MVT::f80) {
8068     llvm_unreachable("va_arg for f80 not yet implemented");
8069   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8070     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8071   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8072     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8073   } else {
8074     llvm_unreachable("Unhandled argument type in LowerVAARG");
8075   }
8076
8077   if (ArgMode == 2) {
8078     // Sanity Check: Make sure using fp_offset makes sense.
8079     assert(!UseSoftFloat &&
8080            !(DAG.getMachineFunction()
8081                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8082            Subtarget->hasXMM());
8083   }
8084
8085   // Insert VAARG_64 node into the DAG
8086   // VAARG_64 returns two values: Variable Argument Address, Chain
8087   SmallVector<SDValue, 11> InstOps;
8088   InstOps.push_back(Chain);
8089   InstOps.push_back(SrcPtr);
8090   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8091   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8092   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8093   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8094   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8095                                           VTs, &InstOps[0], InstOps.size(),
8096                                           MVT::i64,
8097                                           MachinePointerInfo(SV),
8098                                           /*Align=*/0,
8099                                           /*Volatile=*/false,
8100                                           /*ReadMem=*/true,
8101                                           /*WriteMem=*/true);
8102   Chain = VAARG.getValue(1);
8103
8104   // Load the next argument and return it
8105   return DAG.getLoad(ArgVT, dl,
8106                      Chain,
8107                      VAARG,
8108                      MachinePointerInfo(),
8109                      false, false, 0);
8110 }
8111
8112 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8113   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8114   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8115   SDValue Chain = Op.getOperand(0);
8116   SDValue DstPtr = Op.getOperand(1);
8117   SDValue SrcPtr = Op.getOperand(2);
8118   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8119   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8120   DebugLoc DL = Op.getDebugLoc();
8121
8122   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8123                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8124                        false,
8125                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8126 }
8127
8128 SDValue
8129 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8130   DebugLoc dl = Op.getDebugLoc();
8131   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8132   switch (IntNo) {
8133   default: return SDValue();    // Don't custom lower most intrinsics.
8134   // Comparison intrinsics.
8135   case Intrinsic::x86_sse_comieq_ss:
8136   case Intrinsic::x86_sse_comilt_ss:
8137   case Intrinsic::x86_sse_comile_ss:
8138   case Intrinsic::x86_sse_comigt_ss:
8139   case Intrinsic::x86_sse_comige_ss:
8140   case Intrinsic::x86_sse_comineq_ss:
8141   case Intrinsic::x86_sse_ucomieq_ss:
8142   case Intrinsic::x86_sse_ucomilt_ss:
8143   case Intrinsic::x86_sse_ucomile_ss:
8144   case Intrinsic::x86_sse_ucomigt_ss:
8145   case Intrinsic::x86_sse_ucomige_ss:
8146   case Intrinsic::x86_sse_ucomineq_ss:
8147   case Intrinsic::x86_sse2_comieq_sd:
8148   case Intrinsic::x86_sse2_comilt_sd:
8149   case Intrinsic::x86_sse2_comile_sd:
8150   case Intrinsic::x86_sse2_comigt_sd:
8151   case Intrinsic::x86_sse2_comige_sd:
8152   case Intrinsic::x86_sse2_comineq_sd:
8153   case Intrinsic::x86_sse2_ucomieq_sd:
8154   case Intrinsic::x86_sse2_ucomilt_sd:
8155   case Intrinsic::x86_sse2_ucomile_sd:
8156   case Intrinsic::x86_sse2_ucomigt_sd:
8157   case Intrinsic::x86_sse2_ucomige_sd:
8158   case Intrinsic::x86_sse2_ucomineq_sd: {
8159     unsigned Opc = 0;
8160     ISD::CondCode CC = ISD::SETCC_INVALID;
8161     switch (IntNo) {
8162     default: break;
8163     case Intrinsic::x86_sse_comieq_ss:
8164     case Intrinsic::x86_sse2_comieq_sd:
8165       Opc = X86ISD::COMI;
8166       CC = ISD::SETEQ;
8167       break;
8168     case Intrinsic::x86_sse_comilt_ss:
8169     case Intrinsic::x86_sse2_comilt_sd:
8170       Opc = X86ISD::COMI;
8171       CC = ISD::SETLT;
8172       break;
8173     case Intrinsic::x86_sse_comile_ss:
8174     case Intrinsic::x86_sse2_comile_sd:
8175       Opc = X86ISD::COMI;
8176       CC = ISD::SETLE;
8177       break;
8178     case Intrinsic::x86_sse_comigt_ss:
8179     case Intrinsic::x86_sse2_comigt_sd:
8180       Opc = X86ISD::COMI;
8181       CC = ISD::SETGT;
8182       break;
8183     case Intrinsic::x86_sse_comige_ss:
8184     case Intrinsic::x86_sse2_comige_sd:
8185       Opc = X86ISD::COMI;
8186       CC = ISD::SETGE;
8187       break;
8188     case Intrinsic::x86_sse_comineq_ss:
8189     case Intrinsic::x86_sse2_comineq_sd:
8190       Opc = X86ISD::COMI;
8191       CC = ISD::SETNE;
8192       break;
8193     case Intrinsic::x86_sse_ucomieq_ss:
8194     case Intrinsic::x86_sse2_ucomieq_sd:
8195       Opc = X86ISD::UCOMI;
8196       CC = ISD::SETEQ;
8197       break;
8198     case Intrinsic::x86_sse_ucomilt_ss:
8199     case Intrinsic::x86_sse2_ucomilt_sd:
8200       Opc = X86ISD::UCOMI;
8201       CC = ISD::SETLT;
8202       break;
8203     case Intrinsic::x86_sse_ucomile_ss:
8204     case Intrinsic::x86_sse2_ucomile_sd:
8205       Opc = X86ISD::UCOMI;
8206       CC = ISD::SETLE;
8207       break;
8208     case Intrinsic::x86_sse_ucomigt_ss:
8209     case Intrinsic::x86_sse2_ucomigt_sd:
8210       Opc = X86ISD::UCOMI;
8211       CC = ISD::SETGT;
8212       break;
8213     case Intrinsic::x86_sse_ucomige_ss:
8214     case Intrinsic::x86_sse2_ucomige_sd:
8215       Opc = X86ISD::UCOMI;
8216       CC = ISD::SETGE;
8217       break;
8218     case Intrinsic::x86_sse_ucomineq_ss:
8219     case Intrinsic::x86_sse2_ucomineq_sd:
8220       Opc = X86ISD::UCOMI;
8221       CC = ISD::SETNE;
8222       break;
8223     }
8224
8225     SDValue LHS = Op.getOperand(1);
8226     SDValue RHS = Op.getOperand(2);
8227     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8228     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8229     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8230     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8231                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8232     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8233   }
8234   // ptest and testp intrinsics. The intrinsic these come from are designed to
8235   // return an integer value, not just an instruction so lower it to the ptest
8236   // or testp pattern and a setcc for the result.
8237   case Intrinsic::x86_sse41_ptestz:
8238   case Intrinsic::x86_sse41_ptestc:
8239   case Intrinsic::x86_sse41_ptestnzc:
8240   case Intrinsic::x86_avx_ptestz_256:
8241   case Intrinsic::x86_avx_ptestc_256:
8242   case Intrinsic::x86_avx_ptestnzc_256:
8243   case Intrinsic::x86_avx_vtestz_ps:
8244   case Intrinsic::x86_avx_vtestc_ps:
8245   case Intrinsic::x86_avx_vtestnzc_ps:
8246   case Intrinsic::x86_avx_vtestz_pd:
8247   case Intrinsic::x86_avx_vtestc_pd:
8248   case Intrinsic::x86_avx_vtestnzc_pd:
8249   case Intrinsic::x86_avx_vtestz_ps_256:
8250   case Intrinsic::x86_avx_vtestc_ps_256:
8251   case Intrinsic::x86_avx_vtestnzc_ps_256:
8252   case Intrinsic::x86_avx_vtestz_pd_256:
8253   case Intrinsic::x86_avx_vtestc_pd_256:
8254   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8255     bool IsTestPacked = false;
8256     unsigned X86CC = 0;
8257     switch (IntNo) {
8258     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8259     case Intrinsic::x86_avx_vtestz_ps:
8260     case Intrinsic::x86_avx_vtestz_pd:
8261     case Intrinsic::x86_avx_vtestz_ps_256:
8262     case Intrinsic::x86_avx_vtestz_pd_256:
8263       IsTestPacked = true; // Fallthrough
8264     case Intrinsic::x86_sse41_ptestz:
8265     case Intrinsic::x86_avx_ptestz_256:
8266       // ZF = 1
8267       X86CC = X86::COND_E;
8268       break;
8269     case Intrinsic::x86_avx_vtestc_ps:
8270     case Intrinsic::x86_avx_vtestc_pd:
8271     case Intrinsic::x86_avx_vtestc_ps_256:
8272     case Intrinsic::x86_avx_vtestc_pd_256:
8273       IsTestPacked = true; // Fallthrough
8274     case Intrinsic::x86_sse41_ptestc:
8275     case Intrinsic::x86_avx_ptestc_256:
8276       // CF = 1
8277       X86CC = X86::COND_B;
8278       break;
8279     case Intrinsic::x86_avx_vtestnzc_ps:
8280     case Intrinsic::x86_avx_vtestnzc_pd:
8281     case Intrinsic::x86_avx_vtestnzc_ps_256:
8282     case Intrinsic::x86_avx_vtestnzc_pd_256:
8283       IsTestPacked = true; // Fallthrough
8284     case Intrinsic::x86_sse41_ptestnzc:
8285     case Intrinsic::x86_avx_ptestnzc_256:
8286       // ZF and CF = 0
8287       X86CC = X86::COND_A;
8288       break;
8289     }
8290
8291     SDValue LHS = Op.getOperand(1);
8292     SDValue RHS = Op.getOperand(2);
8293     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8294     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8295     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8296     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8297     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8298   }
8299
8300   // Fix vector shift instructions where the last operand is a non-immediate
8301   // i32 value.
8302   case Intrinsic::x86_sse2_pslli_w:
8303   case Intrinsic::x86_sse2_pslli_d:
8304   case Intrinsic::x86_sse2_pslli_q:
8305   case Intrinsic::x86_sse2_psrli_w:
8306   case Intrinsic::x86_sse2_psrli_d:
8307   case Intrinsic::x86_sse2_psrli_q:
8308   case Intrinsic::x86_sse2_psrai_w:
8309   case Intrinsic::x86_sse2_psrai_d:
8310   case Intrinsic::x86_mmx_pslli_w:
8311   case Intrinsic::x86_mmx_pslli_d:
8312   case Intrinsic::x86_mmx_pslli_q:
8313   case Intrinsic::x86_mmx_psrli_w:
8314   case Intrinsic::x86_mmx_psrli_d:
8315   case Intrinsic::x86_mmx_psrli_q:
8316   case Intrinsic::x86_mmx_psrai_w:
8317   case Intrinsic::x86_mmx_psrai_d: {
8318     SDValue ShAmt = Op.getOperand(2);
8319     if (isa<ConstantSDNode>(ShAmt))
8320       return SDValue();
8321
8322     unsigned NewIntNo = 0;
8323     EVT ShAmtVT = MVT::v4i32;
8324     switch (IntNo) {
8325     case Intrinsic::x86_sse2_pslli_w:
8326       NewIntNo = Intrinsic::x86_sse2_psll_w;
8327       break;
8328     case Intrinsic::x86_sse2_pslli_d:
8329       NewIntNo = Intrinsic::x86_sse2_psll_d;
8330       break;
8331     case Intrinsic::x86_sse2_pslli_q:
8332       NewIntNo = Intrinsic::x86_sse2_psll_q;
8333       break;
8334     case Intrinsic::x86_sse2_psrli_w:
8335       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8336       break;
8337     case Intrinsic::x86_sse2_psrli_d:
8338       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8339       break;
8340     case Intrinsic::x86_sse2_psrli_q:
8341       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8342       break;
8343     case Intrinsic::x86_sse2_psrai_w:
8344       NewIntNo = Intrinsic::x86_sse2_psra_w;
8345       break;
8346     case Intrinsic::x86_sse2_psrai_d:
8347       NewIntNo = Intrinsic::x86_sse2_psra_d;
8348       break;
8349     default: {
8350       ShAmtVT = MVT::v2i32;
8351       switch (IntNo) {
8352       case Intrinsic::x86_mmx_pslli_w:
8353         NewIntNo = Intrinsic::x86_mmx_psll_w;
8354         break;
8355       case Intrinsic::x86_mmx_pslli_d:
8356         NewIntNo = Intrinsic::x86_mmx_psll_d;
8357         break;
8358       case Intrinsic::x86_mmx_pslli_q:
8359         NewIntNo = Intrinsic::x86_mmx_psll_q;
8360         break;
8361       case Intrinsic::x86_mmx_psrli_w:
8362         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8363         break;
8364       case Intrinsic::x86_mmx_psrli_d:
8365         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8366         break;
8367       case Intrinsic::x86_mmx_psrli_q:
8368         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8369         break;
8370       case Intrinsic::x86_mmx_psrai_w:
8371         NewIntNo = Intrinsic::x86_mmx_psra_w;
8372         break;
8373       case Intrinsic::x86_mmx_psrai_d:
8374         NewIntNo = Intrinsic::x86_mmx_psra_d;
8375         break;
8376       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8377       }
8378       break;
8379     }
8380     }
8381
8382     // The vector shift intrinsics with scalars uses 32b shift amounts but
8383     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8384     // to be zero.
8385     SDValue ShOps[4];
8386     ShOps[0] = ShAmt;
8387     ShOps[1] = DAG.getConstant(0, MVT::i32);
8388     if (ShAmtVT == MVT::v4i32) {
8389       ShOps[2] = DAG.getUNDEF(MVT::i32);
8390       ShOps[3] = DAG.getUNDEF(MVT::i32);
8391       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8392     } else {
8393       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8394 // FIXME this must be lowered to get rid of the invalid type.
8395     }
8396
8397     EVT VT = Op.getValueType();
8398     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8399     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8400                        DAG.getConstant(NewIntNo, MVT::i32),
8401                        Op.getOperand(1), ShAmt);
8402   }
8403   }
8404 }
8405
8406 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8407                                            SelectionDAG &DAG) const {
8408   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8409   MFI->setReturnAddressIsTaken(true);
8410
8411   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8412   DebugLoc dl = Op.getDebugLoc();
8413
8414   if (Depth > 0) {
8415     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8416     SDValue Offset =
8417       DAG.getConstant(TD->getPointerSize(),
8418                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8419     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8420                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8421                                    FrameAddr, Offset),
8422                        MachinePointerInfo(), false, false, 0);
8423   }
8424
8425   // Just load the return address.
8426   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8427   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8428                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8429 }
8430
8431 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8432   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8433   MFI->setFrameAddressIsTaken(true);
8434
8435   EVT VT = Op.getValueType();
8436   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8437   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8438   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8439   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8440   while (Depth--)
8441     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8442                             MachinePointerInfo(),
8443                             false, false, 0);
8444   return FrameAddr;
8445 }
8446
8447 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8448                                                      SelectionDAG &DAG) const {
8449   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8450 }
8451
8452 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8453   MachineFunction &MF = DAG.getMachineFunction();
8454   SDValue Chain     = Op.getOperand(0);
8455   SDValue Offset    = Op.getOperand(1);
8456   SDValue Handler   = Op.getOperand(2);
8457   DebugLoc dl       = Op.getDebugLoc();
8458
8459   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8460                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8461                                      getPointerTy());
8462   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8463
8464   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8465                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8466   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8467   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8468                        false, false, 0);
8469   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8470   MF.getRegInfo().addLiveOut(StoreAddrReg);
8471
8472   return DAG.getNode(X86ISD::EH_RETURN, dl,
8473                      MVT::Other,
8474                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8475 }
8476
8477 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8478                                              SelectionDAG &DAG) const {
8479   SDValue Root = Op.getOperand(0);
8480   SDValue Trmp = Op.getOperand(1); // trampoline
8481   SDValue FPtr = Op.getOperand(2); // nested function
8482   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8483   DebugLoc dl  = Op.getDebugLoc();
8484
8485   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8486
8487   if (Subtarget->is64Bit()) {
8488     SDValue OutChains[6];
8489
8490     // Large code-model.
8491     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8492     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8493
8494     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8495     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8496
8497     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8498
8499     // Load the pointer to the nested function into R11.
8500     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8501     SDValue Addr = Trmp;
8502     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8503                                 Addr, MachinePointerInfo(TrmpAddr),
8504                                 false, false, 0);
8505
8506     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8507                        DAG.getConstant(2, MVT::i64));
8508     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8509                                 MachinePointerInfo(TrmpAddr, 2),
8510                                 false, false, 2);
8511
8512     // Load the 'nest' parameter value into R10.
8513     // R10 is specified in X86CallingConv.td
8514     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8515     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8516                        DAG.getConstant(10, MVT::i64));
8517     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8518                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8519                                 false, false, 0);
8520
8521     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8522                        DAG.getConstant(12, MVT::i64));
8523     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8524                                 MachinePointerInfo(TrmpAddr, 12),
8525                                 false, false, 2);
8526
8527     // Jump to the nested function.
8528     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8529     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8530                        DAG.getConstant(20, MVT::i64));
8531     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8532                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8533                                 false, false, 0);
8534
8535     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8536     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8537                        DAG.getConstant(22, MVT::i64));
8538     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8539                                 MachinePointerInfo(TrmpAddr, 22),
8540                                 false, false, 0);
8541
8542     SDValue Ops[] =
8543       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8544     return DAG.getMergeValues(Ops, 2, dl);
8545   } else {
8546     const Function *Func =
8547       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8548     CallingConv::ID CC = Func->getCallingConv();
8549     unsigned NestReg;
8550
8551     switch (CC) {
8552     default:
8553       llvm_unreachable("Unsupported calling convention");
8554     case CallingConv::C:
8555     case CallingConv::X86_StdCall: {
8556       // Pass 'nest' parameter in ECX.
8557       // Must be kept in sync with X86CallingConv.td
8558       NestReg = X86::ECX;
8559
8560       // Check that ECX wasn't needed by an 'inreg' parameter.
8561       const FunctionType *FTy = Func->getFunctionType();
8562       const AttrListPtr &Attrs = Func->getAttributes();
8563
8564       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8565         unsigned InRegCount = 0;
8566         unsigned Idx = 1;
8567
8568         for (FunctionType::param_iterator I = FTy->param_begin(),
8569              E = FTy->param_end(); I != E; ++I, ++Idx)
8570           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8571             // FIXME: should only count parameters that are lowered to integers.
8572             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8573
8574         if (InRegCount > 2) {
8575           report_fatal_error("Nest register in use - reduce number of inreg"
8576                              " parameters!");
8577         }
8578       }
8579       break;
8580     }
8581     case CallingConv::X86_FastCall:
8582     case CallingConv::X86_ThisCall:
8583     case CallingConv::Fast:
8584       // Pass 'nest' parameter in EAX.
8585       // Must be kept in sync with X86CallingConv.td
8586       NestReg = X86::EAX;
8587       break;
8588     }
8589
8590     SDValue OutChains[4];
8591     SDValue Addr, Disp;
8592
8593     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8594                        DAG.getConstant(10, MVT::i32));
8595     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8596
8597     // This is storing the opcode for MOV32ri.
8598     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8599     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8600     OutChains[0] = DAG.getStore(Root, dl,
8601                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8602                                 Trmp, MachinePointerInfo(TrmpAddr),
8603                                 false, false, 0);
8604
8605     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8606                        DAG.getConstant(1, MVT::i32));
8607     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8608                                 MachinePointerInfo(TrmpAddr, 1),
8609                                 false, false, 1);
8610
8611     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8612     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8613                        DAG.getConstant(5, MVT::i32));
8614     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8615                                 MachinePointerInfo(TrmpAddr, 5),
8616                                 false, false, 1);
8617
8618     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8619                        DAG.getConstant(6, MVT::i32));
8620     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8621                                 MachinePointerInfo(TrmpAddr, 6),
8622                                 false, false, 1);
8623
8624     SDValue Ops[] =
8625       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8626     return DAG.getMergeValues(Ops, 2, dl);
8627   }
8628 }
8629
8630 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8631                                             SelectionDAG &DAG) const {
8632   /*
8633    The rounding mode is in bits 11:10 of FPSR, and has the following
8634    settings:
8635      00 Round to nearest
8636      01 Round to -inf
8637      10 Round to +inf
8638      11 Round to 0
8639
8640   FLT_ROUNDS, on the other hand, expects the following:
8641     -1 Undefined
8642      0 Round to 0
8643      1 Round to nearest
8644      2 Round to +inf
8645      3 Round to -inf
8646
8647   To perform the conversion, we do:
8648     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8649   */
8650
8651   MachineFunction &MF = DAG.getMachineFunction();
8652   const TargetMachine &TM = MF.getTarget();
8653   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8654   unsigned StackAlignment = TFI.getStackAlignment();
8655   EVT VT = Op.getValueType();
8656   DebugLoc DL = Op.getDebugLoc();
8657
8658   // Save FP Control Word to stack slot
8659   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8660   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8661
8662
8663   MachineMemOperand *MMO =
8664    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8665                            MachineMemOperand::MOStore, 2, 2);
8666
8667   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8668   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8669                                           DAG.getVTList(MVT::Other),
8670                                           Ops, 2, MVT::i16, MMO);
8671
8672   // Load FP Control Word from stack slot
8673   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8674                             MachinePointerInfo(), false, false, 0);
8675
8676   // Transform as necessary
8677   SDValue CWD1 =
8678     DAG.getNode(ISD::SRL, DL, MVT::i16,
8679                 DAG.getNode(ISD::AND, DL, MVT::i16,
8680                             CWD, DAG.getConstant(0x800, MVT::i16)),
8681                 DAG.getConstant(11, MVT::i8));
8682   SDValue CWD2 =
8683     DAG.getNode(ISD::SRL, DL, MVT::i16,
8684                 DAG.getNode(ISD::AND, DL, MVT::i16,
8685                             CWD, DAG.getConstant(0x400, MVT::i16)),
8686                 DAG.getConstant(9, MVT::i8));
8687
8688   SDValue RetVal =
8689     DAG.getNode(ISD::AND, DL, MVT::i16,
8690                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8691                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8692                             DAG.getConstant(1, MVT::i16)),
8693                 DAG.getConstant(3, MVT::i16));
8694
8695
8696   return DAG.getNode((VT.getSizeInBits() < 16 ?
8697                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8698 }
8699
8700 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8701   EVT VT = Op.getValueType();
8702   EVT OpVT = VT;
8703   unsigned NumBits = VT.getSizeInBits();
8704   DebugLoc dl = Op.getDebugLoc();
8705
8706   Op = Op.getOperand(0);
8707   if (VT == MVT::i8) {
8708     // Zero extend to i32 since there is not an i8 bsr.
8709     OpVT = MVT::i32;
8710     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8711   }
8712
8713   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8714   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8715   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8716
8717   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8718   SDValue Ops[] = {
8719     Op,
8720     DAG.getConstant(NumBits+NumBits-1, OpVT),
8721     DAG.getConstant(X86::COND_E, MVT::i8),
8722     Op.getValue(1)
8723   };
8724   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8725
8726   // Finally xor with NumBits-1.
8727   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8728
8729   if (VT == MVT::i8)
8730     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8731   return Op;
8732 }
8733
8734 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8735   EVT VT = Op.getValueType();
8736   EVT OpVT = VT;
8737   unsigned NumBits = VT.getSizeInBits();
8738   DebugLoc dl = Op.getDebugLoc();
8739
8740   Op = Op.getOperand(0);
8741   if (VT == MVT::i8) {
8742     OpVT = MVT::i32;
8743     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8744   }
8745
8746   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8747   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8748   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8749
8750   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8751   SDValue Ops[] = {
8752     Op,
8753     DAG.getConstant(NumBits, OpVT),
8754     DAG.getConstant(X86::COND_E, MVT::i8),
8755     Op.getValue(1)
8756   };
8757   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8758
8759   if (VT == MVT::i8)
8760     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8761   return Op;
8762 }
8763
8764 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8765   EVT VT = Op.getValueType();
8766   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8767   DebugLoc dl = Op.getDebugLoc();
8768
8769   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8770   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8771   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8772   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8773   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8774   //
8775   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8776   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8777   //  return AloBlo + AloBhi + AhiBlo;
8778
8779   SDValue A = Op.getOperand(0);
8780   SDValue B = Op.getOperand(1);
8781
8782   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8783                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8784                        A, DAG.getConstant(32, MVT::i32));
8785   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8786                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8787                        B, DAG.getConstant(32, MVT::i32));
8788   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8789                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8790                        A, B);
8791   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8792                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8793                        A, Bhi);
8794   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8795                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8796                        Ahi, B);
8797   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8798                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8799                        AloBhi, DAG.getConstant(32, MVT::i32));
8800   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8801                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8802                        AhiBlo, DAG.getConstant(32, MVT::i32));
8803   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8804   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8805   return Res;
8806 }
8807
8808 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
8809
8810   EVT VT = Op.getValueType();
8811   DebugLoc dl = Op.getDebugLoc();
8812   SDValue R = Op.getOperand(0);
8813   SDValue Amt = Op.getOperand(1);
8814
8815   LLVMContext *Context = DAG.getContext();
8816
8817   // Must have SSE2.
8818   if (!Subtarget->hasSSE2()) return SDValue();
8819
8820   // Optimize shl/srl/sra with constant shift amount.
8821   if (isSplatVector(Amt.getNode())) {
8822     SDValue SclrAmt = Amt->getOperand(0);
8823     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
8824       uint64_t ShiftAmt = C->getZExtValue();
8825
8826       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
8827        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8828                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8829                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8830
8831       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
8832        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8833                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8834                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8835
8836       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
8837        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8838                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8839                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8840
8841       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
8842        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8843                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8844                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8845
8846       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
8847        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8848                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8849                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8850
8851       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
8852        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8853                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8854                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8855
8856       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
8857        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8858                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8859                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8860
8861       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
8862        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8863                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8864                      R, DAG.getConstant(ShiftAmt, MVT::i32));
8865     }
8866   }
8867
8868   // Lower SHL with variable shift amount.
8869   // Cannot lower SHL without SSE4.1 or later.
8870   if (!Subtarget->hasSSE41()) return SDValue();
8871
8872   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
8873     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8874                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8875                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8876
8877     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8878
8879     std::vector<Constant*> CV(4, CI);
8880     Constant *C = ConstantVector::get(CV);
8881     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8882     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8883                                  MachinePointerInfo::getConstantPool(),
8884                                  false, false, 16);
8885
8886     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8887     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8888     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8889     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8890   }
8891   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
8892     // a = a << 5;
8893     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8894                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8895                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8896
8897     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8898     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8899
8900     std::vector<Constant*> CVM1(16, CM1);
8901     std::vector<Constant*> CVM2(16, CM2);
8902     Constant *C = ConstantVector::get(CVM1);
8903     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8904     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8905                             MachinePointerInfo::getConstantPool(),
8906                             false, false, 16);
8907
8908     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8909     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8910     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8911                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8912                     DAG.getConstant(4, MVT::i32));
8913     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8914     // a += a
8915     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8916
8917     C = ConstantVector::get(CVM2);
8918     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8919     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8920                     MachinePointerInfo::getConstantPool(),
8921                     false, false, 16);
8922
8923     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8924     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8925     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8926                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8927                     DAG.getConstant(2, MVT::i32));
8928     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8929     // a += a
8930     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8931
8932     // return pblendv(r, r+r, a);
8933     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8934                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8935     return R;
8936   }
8937   return SDValue();
8938 }
8939
8940 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8941   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8942   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8943   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8944   // has only one use.
8945   SDNode *N = Op.getNode();
8946   SDValue LHS = N->getOperand(0);
8947   SDValue RHS = N->getOperand(1);
8948   unsigned BaseOp = 0;
8949   unsigned Cond = 0;
8950   DebugLoc DL = Op.getDebugLoc();
8951   switch (Op.getOpcode()) {
8952   default: llvm_unreachable("Unknown ovf instruction!");
8953   case ISD::SADDO:
8954     // A subtract of one will be selected as a INC. Note that INC doesn't
8955     // set CF, so we can't do this for UADDO.
8956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8957       if (C->isOne()) {
8958         BaseOp = X86ISD::INC;
8959         Cond = X86::COND_O;
8960         break;
8961       }
8962     BaseOp = X86ISD::ADD;
8963     Cond = X86::COND_O;
8964     break;
8965   case ISD::UADDO:
8966     BaseOp = X86ISD::ADD;
8967     Cond = X86::COND_B;
8968     break;
8969   case ISD::SSUBO:
8970     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8971     // set CF, so we can't do this for USUBO.
8972     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
8973       if (C->isOne()) {
8974         BaseOp = X86ISD::DEC;
8975         Cond = X86::COND_O;
8976         break;
8977       }
8978     BaseOp = X86ISD::SUB;
8979     Cond = X86::COND_O;
8980     break;
8981   case ISD::USUBO:
8982     BaseOp = X86ISD::SUB;
8983     Cond = X86::COND_B;
8984     break;
8985   case ISD::SMULO:
8986     BaseOp = X86ISD::SMUL;
8987     Cond = X86::COND_O;
8988     break;
8989   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8990     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8991                                  MVT::i32);
8992     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8993
8994     SDValue SetCC =
8995       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8996                   DAG.getConstant(X86::COND_O, MVT::i32),
8997                   SDValue(Sum.getNode(), 2));
8998
8999     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9000     return Sum;
9001   }
9002   }
9003
9004   // Also sets EFLAGS.
9005   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9006   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9007
9008   SDValue SetCC =
9009     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9010                 DAG.getConstant(Cond, MVT::i32),
9011                 SDValue(Sum.getNode(), 1));
9012
9013   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
9014   return Sum;
9015 }
9016
9017 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9018   DebugLoc dl = Op.getDebugLoc();
9019
9020   if (!Subtarget->hasSSE2()) {
9021     SDValue Chain = Op.getOperand(0);
9022     SDValue Zero = DAG.getConstant(0,
9023                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9024     SDValue Ops[] = {
9025       DAG.getRegister(X86::ESP, MVT::i32), // Base
9026       DAG.getTargetConstant(1, MVT::i8),   // Scale
9027       DAG.getRegister(0, MVT::i32),        // Index
9028       DAG.getTargetConstant(0, MVT::i32),  // Disp
9029       DAG.getRegister(0, MVT::i32),        // Segment.
9030       Zero,
9031       Chain
9032     };
9033     SDNode *Res =
9034       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9035                           array_lengthof(Ops));
9036     return SDValue(Res, 0);
9037   }
9038
9039   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9040   if (!isDev)
9041     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9042
9043   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9044   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9045   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9046   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9047
9048   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9049   if (!Op1 && !Op2 && !Op3 && Op4)
9050     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9051
9052   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9053   if (Op1 && !Op2 && !Op3 && !Op4)
9054     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9055
9056   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9057   //           (MFENCE)>;
9058   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9059 }
9060
9061 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9062   EVT T = Op.getValueType();
9063   DebugLoc DL = Op.getDebugLoc();
9064   unsigned Reg = 0;
9065   unsigned size = 0;
9066   switch(T.getSimpleVT().SimpleTy) {
9067   default:
9068     assert(false && "Invalid value type!");
9069   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9070   case MVT::i16: Reg = X86::AX;  size = 2; break;
9071   case MVT::i32: Reg = X86::EAX; size = 4; break;
9072   case MVT::i64:
9073     assert(Subtarget->is64Bit() && "Node not type legal!");
9074     Reg = X86::RAX; size = 8;
9075     break;
9076   }
9077   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9078                                     Op.getOperand(2), SDValue());
9079   SDValue Ops[] = { cpIn.getValue(0),
9080                     Op.getOperand(1),
9081                     Op.getOperand(3),
9082                     DAG.getTargetConstant(size, MVT::i8),
9083                     cpIn.getValue(1) };
9084   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9085   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9086   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9087                                            Ops, 5, T, MMO);
9088   SDValue cpOut =
9089     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9090   return cpOut;
9091 }
9092
9093 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9094                                                  SelectionDAG &DAG) const {
9095   assert(Subtarget->is64Bit() && "Result not type legalized?");
9096   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9097   SDValue TheChain = Op.getOperand(0);
9098   DebugLoc dl = Op.getDebugLoc();
9099   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9100   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9101   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9102                                    rax.getValue(2));
9103   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9104                             DAG.getConstant(32, MVT::i8));
9105   SDValue Ops[] = {
9106     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9107     rdx.getValue(1)
9108   };
9109   return DAG.getMergeValues(Ops, 2, dl);
9110 }
9111
9112 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9113                                             SelectionDAG &DAG) const {
9114   EVT SrcVT = Op.getOperand(0).getValueType();
9115   EVT DstVT = Op.getValueType();
9116   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9117          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9118   assert((DstVT == MVT::i64 ||
9119           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9120          "Unexpected custom BITCAST");
9121   // i64 <=> MMX conversions are Legal.
9122   if (SrcVT==MVT::i64 && DstVT.isVector())
9123     return Op;
9124   if (DstVT==MVT::i64 && SrcVT.isVector())
9125     return Op;
9126   // MMX <=> MMX conversions are Legal.
9127   if (SrcVT.isVector() && DstVT.isVector())
9128     return Op;
9129   // All other conversions need to be expanded.
9130   return SDValue();
9131 }
9132
9133 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9134   SDNode *Node = Op.getNode();
9135   DebugLoc dl = Node->getDebugLoc();
9136   EVT T = Node->getValueType(0);
9137   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9138                               DAG.getConstant(0, T), Node->getOperand(2));
9139   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
9140                        cast<AtomicSDNode>(Node)->getMemoryVT(),
9141                        Node->getOperand(0),
9142                        Node->getOperand(1), negOp,
9143                        cast<AtomicSDNode>(Node)->getSrcValue(),
9144                        cast<AtomicSDNode>(Node)->getAlignment());
9145 }
9146
9147 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
9148   EVT VT = Op.getNode()->getValueType(0);
9149
9150   // Let legalize expand this if it isn't a legal type yet.
9151   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9152     return SDValue();
9153
9154   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9155
9156   unsigned Opc;
9157   bool ExtraOp = false;
9158   switch (Op.getOpcode()) {
9159   default: assert(0 && "Invalid code");
9160   case ISD::ADDC: Opc = X86ISD::ADD; break;
9161   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
9162   case ISD::SUBC: Opc = X86ISD::SUB; break;
9163   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
9164   }
9165
9166   if (!ExtraOp)
9167     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9168                        Op.getOperand(1));
9169   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9170                      Op.getOperand(1), Op.getOperand(2));
9171 }
9172
9173 /// LowerOperation - Provide custom lowering hooks for some operations.
9174 ///
9175 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9176   switch (Op.getOpcode()) {
9177   default: llvm_unreachable("Should not custom lower this!");
9178   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9179   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9180   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9181   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9182   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9183   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9184   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9185   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9186   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9187   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9188   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9189   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9190   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9191   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9192   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9193   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9194   case ISD::SHL_PARTS:
9195   case ISD::SRA_PARTS:
9196   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
9197   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9198   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9199   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9200   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9201   case ISD::FABS:               return LowerFABS(Op, DAG);
9202   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9203   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9204   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
9205   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9206   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9207   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9208   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9209   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9210   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9211   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9212   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9213   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9214   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9215   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9216   case ISD::FRAME_TO_ARGS_OFFSET:
9217                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9218   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9219   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9220   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9221   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9222   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9223   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9224   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9225   case ISD::SRA:
9226   case ISD::SRL:
9227   case ISD::SHL:                return LowerShift(Op, DAG);
9228   case ISD::SADDO:
9229   case ISD::UADDO:
9230   case ISD::SSUBO:
9231   case ISD::USUBO:
9232   case ISD::SMULO:
9233   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9234   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9235   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9236   case ISD::ADDC:
9237   case ISD::ADDE:
9238   case ISD::SUBC:
9239   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9240   }
9241 }
9242
9243 void X86TargetLowering::
9244 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9245                         SelectionDAG &DAG, unsigned NewOp) const {
9246   EVT T = Node->getValueType(0);
9247   DebugLoc dl = Node->getDebugLoc();
9248   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9249
9250   SDValue Chain = Node->getOperand(0);
9251   SDValue In1 = Node->getOperand(1);
9252   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9253                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9254   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9255                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9256   SDValue Ops[] = { Chain, In1, In2L, In2H };
9257   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9258   SDValue Result =
9259     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9260                             cast<MemSDNode>(Node)->getMemOperand());
9261   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9262   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9263   Results.push_back(Result.getValue(2));
9264 }
9265
9266 /// ReplaceNodeResults - Replace a node with an illegal result type
9267 /// with a new node built out of custom code.
9268 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9269                                            SmallVectorImpl<SDValue>&Results,
9270                                            SelectionDAG &DAG) const {
9271   DebugLoc dl = N->getDebugLoc();
9272   switch (N->getOpcode()) {
9273   default:
9274     assert(false && "Do not know how to custom type legalize this operation!");
9275     return;
9276   case ISD::ADDC:
9277   case ISD::ADDE:
9278   case ISD::SUBC:
9279   case ISD::SUBE:
9280     // We don't want to expand or promote these.
9281     return;
9282   case ISD::FP_TO_SINT: {
9283     std::pair<SDValue,SDValue> Vals =
9284         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9285     SDValue FIST = Vals.first, StackSlot = Vals.second;
9286     if (FIST.getNode() != 0) {
9287       EVT VT = N->getValueType(0);
9288       // Return a load from the stack slot.
9289       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9290                                     MachinePointerInfo(), false, false, 0));
9291     }
9292     return;
9293   }
9294   case ISD::READCYCLECOUNTER: {
9295     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9296     SDValue TheChain = N->getOperand(0);
9297     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9298     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9299                                      rd.getValue(1));
9300     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9301                                      eax.getValue(2));
9302     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9303     SDValue Ops[] = { eax, edx };
9304     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9305     Results.push_back(edx.getValue(1));
9306     return;
9307   }
9308   case ISD::ATOMIC_CMP_SWAP: {
9309     EVT T = N->getValueType(0);
9310     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9311     SDValue cpInL, cpInH;
9312     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9313                         DAG.getConstant(0, MVT::i32));
9314     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9315                         DAG.getConstant(1, MVT::i32));
9316     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9317     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9318                              cpInL.getValue(1));
9319     SDValue swapInL, swapInH;
9320     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9321                           DAG.getConstant(0, MVT::i32));
9322     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9323                           DAG.getConstant(1, MVT::i32));
9324     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9325                                cpInH.getValue(1));
9326     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9327                                swapInL.getValue(1));
9328     SDValue Ops[] = { swapInH.getValue(0),
9329                       N->getOperand(1),
9330                       swapInH.getValue(1) };
9331     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9332     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9333     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9334                                              Ops, 3, T, MMO);
9335     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9336                                         MVT::i32, Result.getValue(1));
9337     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9338                                         MVT::i32, cpOutL.getValue(2));
9339     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9340     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9341     Results.push_back(cpOutH.getValue(1));
9342     return;
9343   }
9344   case ISD::ATOMIC_LOAD_ADD:
9345     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9346     return;
9347   case ISD::ATOMIC_LOAD_AND:
9348     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9349     return;
9350   case ISD::ATOMIC_LOAD_NAND:
9351     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9352     return;
9353   case ISD::ATOMIC_LOAD_OR:
9354     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9355     return;
9356   case ISD::ATOMIC_LOAD_SUB:
9357     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9358     return;
9359   case ISD::ATOMIC_LOAD_XOR:
9360     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9361     return;
9362   case ISD::ATOMIC_SWAP:
9363     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9364     return;
9365   }
9366 }
9367
9368 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9369   switch (Opcode) {
9370   default: return NULL;
9371   case X86ISD::BSF:                return "X86ISD::BSF";
9372   case X86ISD::BSR:                return "X86ISD::BSR";
9373   case X86ISD::SHLD:               return "X86ISD::SHLD";
9374   case X86ISD::SHRD:               return "X86ISD::SHRD";
9375   case X86ISD::FAND:               return "X86ISD::FAND";
9376   case X86ISD::FOR:                return "X86ISD::FOR";
9377   case X86ISD::FXOR:               return "X86ISD::FXOR";
9378   case X86ISD::FSRL:               return "X86ISD::FSRL";
9379   case X86ISD::FILD:               return "X86ISD::FILD";
9380   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9381   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9382   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9383   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9384   case X86ISD::FLD:                return "X86ISD::FLD";
9385   case X86ISD::FST:                return "X86ISD::FST";
9386   case X86ISD::CALL:               return "X86ISD::CALL";
9387   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9388   case X86ISD::BT:                 return "X86ISD::BT";
9389   case X86ISD::CMP:                return "X86ISD::CMP";
9390   case X86ISD::COMI:               return "X86ISD::COMI";
9391   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9392   case X86ISD::SETCC:              return "X86ISD::SETCC";
9393   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9394   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
9395   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
9396   case X86ISD::CMOV:               return "X86ISD::CMOV";
9397   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9398   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9399   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9400   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9401   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9402   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9403   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9404   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9405   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9406   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9407   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9408   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9409   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9410   case X86ISD::PANDN:              return "X86ISD::PANDN";
9411   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9412   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9413   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9414   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9415   case X86ISD::FMAX:               return "X86ISD::FMAX";
9416   case X86ISD::FMIN:               return "X86ISD::FMIN";
9417   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9418   case X86ISD::FRCP:               return "X86ISD::FRCP";
9419   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9420   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9421   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9422   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9423   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9424   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9425   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9426   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9427   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9428   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9429   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9430   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9431   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9432   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9433   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9434   case X86ISD::VSHL:               return "X86ISD::VSHL";
9435   case X86ISD::VSRL:               return "X86ISD::VSRL";
9436   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9437   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9438   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9439   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9440   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9441   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9442   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9443   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9444   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9445   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9446   case X86ISD::ADD:                return "X86ISD::ADD";
9447   case X86ISD::SUB:                return "X86ISD::SUB";
9448   case X86ISD::ADC:                return "X86ISD::ADC";
9449   case X86ISD::SBB:                return "X86ISD::SBB";
9450   case X86ISD::SMUL:               return "X86ISD::SMUL";
9451   case X86ISD::UMUL:               return "X86ISD::UMUL";
9452   case X86ISD::INC:                return "X86ISD::INC";
9453   case X86ISD::DEC:                return "X86ISD::DEC";
9454   case X86ISD::OR:                 return "X86ISD::OR";
9455   case X86ISD::XOR:                return "X86ISD::XOR";
9456   case X86ISD::AND:                return "X86ISD::AND";
9457   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9458   case X86ISD::PTEST:              return "X86ISD::PTEST";
9459   case X86ISD::TESTP:              return "X86ISD::TESTP";
9460   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9461   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9462   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9463   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9464   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9465   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9466   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9467   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9468   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9469   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9470   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9471   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9472   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9473   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9474   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9475   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9476   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9477   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9478   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9479   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9480   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9481   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9482   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9483   case X86ISD::VUNPCKLPS:          return "X86ISD::VUNPCKLPS";
9484   case X86ISD::VUNPCKLPD:          return "X86ISD::VUNPCKLPD";
9485   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
9486   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
9487   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9488   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9489   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9490   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9491   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9492   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9493   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9494   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9495   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9496   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9497   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9498   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9499   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9500   }
9501 }
9502
9503 // isLegalAddressingMode - Return true if the addressing mode represented
9504 // by AM is legal for this target, for a load/store of the specified type.
9505 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9506                                               const Type *Ty) const {
9507   // X86 supports extremely general addressing modes.
9508   CodeModel::Model M = getTargetMachine().getCodeModel();
9509   Reloc::Model R = getTargetMachine().getRelocationModel();
9510
9511   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9512   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9513     return false;
9514
9515   if (AM.BaseGV) {
9516     unsigned GVFlags =
9517       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9518
9519     // If a reference to this global requires an extra load, we can't fold it.
9520     if (isGlobalStubReference(GVFlags))
9521       return false;
9522
9523     // If BaseGV requires a register for the PIC base, we cannot also have a
9524     // BaseReg specified.
9525     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9526       return false;
9527
9528     // If lower 4G is not available, then we must use rip-relative addressing.
9529     if ((M != CodeModel::Small || R != Reloc::Static) &&
9530         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9531       return false;
9532   }
9533
9534   switch (AM.Scale) {
9535   case 0:
9536   case 1:
9537   case 2:
9538   case 4:
9539   case 8:
9540     // These scales always work.
9541     break;
9542   case 3:
9543   case 5:
9544   case 9:
9545     // These scales are formed with basereg+scalereg.  Only accept if there is
9546     // no basereg yet.
9547     if (AM.HasBaseReg)
9548       return false;
9549     break;
9550   default:  // Other stuff never works.
9551     return false;
9552   }
9553
9554   return true;
9555 }
9556
9557
9558 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9559   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9560     return false;
9561   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9562   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9563   if (NumBits1 <= NumBits2)
9564     return false;
9565   return true;
9566 }
9567
9568 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9569   if (!VT1.isInteger() || !VT2.isInteger())
9570     return false;
9571   unsigned NumBits1 = VT1.getSizeInBits();
9572   unsigned NumBits2 = VT2.getSizeInBits();
9573   if (NumBits1 <= NumBits2)
9574     return false;
9575   return true;
9576 }
9577
9578 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9579   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9580   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9581 }
9582
9583 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9584   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9585   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9586 }
9587
9588 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9589   // i16 instructions are longer (0x66 prefix) and potentially slower.
9590   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9591 }
9592
9593 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9594 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9595 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9596 /// are assumed to be legal.
9597 bool
9598 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9599                                       EVT VT) const {
9600   // Very little shuffling can be done for 64-bit vectors right now.
9601   if (VT.getSizeInBits() == 64)
9602     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9603
9604   // FIXME: pshufb, blends, shifts.
9605   return (VT.getVectorNumElements() == 2 ||
9606           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9607           isMOVLMask(M, VT) ||
9608           isSHUFPMask(M, VT) ||
9609           isPSHUFDMask(M, VT) ||
9610           isPSHUFHWMask(M, VT) ||
9611           isPSHUFLWMask(M, VT) ||
9612           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9613           isUNPCKLMask(M, VT) ||
9614           isUNPCKHMask(M, VT) ||
9615           isUNPCKL_v_undef_Mask(M, VT) ||
9616           isUNPCKH_v_undef_Mask(M, VT));
9617 }
9618
9619 bool
9620 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9621                                           EVT VT) const {
9622   unsigned NumElts = VT.getVectorNumElements();
9623   // FIXME: This collection of masks seems suspect.
9624   if (NumElts == 2)
9625     return true;
9626   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9627     return (isMOVLMask(Mask, VT)  ||
9628             isCommutedMOVLMask(Mask, VT, true) ||
9629             isSHUFPMask(Mask, VT) ||
9630             isCommutedSHUFPMask(Mask, VT));
9631   }
9632   return false;
9633 }
9634
9635 //===----------------------------------------------------------------------===//
9636 //                           X86 Scheduler Hooks
9637 //===----------------------------------------------------------------------===//
9638
9639 // private utility function
9640 MachineBasicBlock *
9641 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9642                                                        MachineBasicBlock *MBB,
9643                                                        unsigned regOpc,
9644                                                        unsigned immOpc,
9645                                                        unsigned LoadOpc,
9646                                                        unsigned CXchgOpc,
9647                                                        unsigned notOpc,
9648                                                        unsigned EAXreg,
9649                                                        TargetRegisterClass *RC,
9650                                                        bool invSrc) const {
9651   // For the atomic bitwise operator, we generate
9652   //   thisMBB:
9653   //   newMBB:
9654   //     ld  t1 = [bitinstr.addr]
9655   //     op  t2 = t1, [bitinstr.val]
9656   //     mov EAX = t1
9657   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9658   //     bz  newMBB
9659   //     fallthrough -->nextMBB
9660   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9661   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9662   MachineFunction::iterator MBBIter = MBB;
9663   ++MBBIter;
9664
9665   /// First build the CFG
9666   MachineFunction *F = MBB->getParent();
9667   MachineBasicBlock *thisMBB = MBB;
9668   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9669   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9670   F->insert(MBBIter, newMBB);
9671   F->insert(MBBIter, nextMBB);
9672
9673   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9674   nextMBB->splice(nextMBB->begin(), thisMBB,
9675                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9676                   thisMBB->end());
9677   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9678
9679   // Update thisMBB to fall through to newMBB
9680   thisMBB->addSuccessor(newMBB);
9681
9682   // newMBB jumps to itself and fall through to nextMBB
9683   newMBB->addSuccessor(nextMBB);
9684   newMBB->addSuccessor(newMBB);
9685
9686   // Insert instructions into newMBB based on incoming instruction
9687   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9688          "unexpected number of operands");
9689   DebugLoc dl = bInstr->getDebugLoc();
9690   MachineOperand& destOper = bInstr->getOperand(0);
9691   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9692   int numArgs = bInstr->getNumOperands() - 1;
9693   for (int i=0; i < numArgs; ++i)
9694     argOpers[i] = &bInstr->getOperand(i+1);
9695
9696   // x86 address has 4 operands: base, index, scale, and displacement
9697   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9698   int valArgIndx = lastAddrIndx + 1;
9699
9700   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9701   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9702   for (int i=0; i <= lastAddrIndx; ++i)
9703     (*MIB).addOperand(*argOpers[i]);
9704
9705   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9706   if (invSrc) {
9707     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9708   }
9709   else
9710     tt = t1;
9711
9712   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9713   assert((argOpers[valArgIndx]->isReg() ||
9714           argOpers[valArgIndx]->isImm()) &&
9715          "invalid operand");
9716   if (argOpers[valArgIndx]->isReg())
9717     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9718   else
9719     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9720   MIB.addReg(tt);
9721   (*MIB).addOperand(*argOpers[valArgIndx]);
9722
9723   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9724   MIB.addReg(t1);
9725
9726   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9727   for (int i=0; i <= lastAddrIndx; ++i)
9728     (*MIB).addOperand(*argOpers[i]);
9729   MIB.addReg(t2);
9730   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9731   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9732                     bInstr->memoperands_end());
9733
9734   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9735   MIB.addReg(EAXreg);
9736
9737   // insert branch
9738   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9739
9740   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9741   return nextMBB;
9742 }
9743
9744 // private utility function:  64 bit atomics on 32 bit host.
9745 MachineBasicBlock *
9746 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9747                                                        MachineBasicBlock *MBB,
9748                                                        unsigned regOpcL,
9749                                                        unsigned regOpcH,
9750                                                        unsigned immOpcL,
9751                                                        unsigned immOpcH,
9752                                                        bool invSrc) const {
9753   // For the atomic bitwise operator, we generate
9754   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9755   //     ld t1,t2 = [bitinstr.addr]
9756   //   newMBB:
9757   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9758   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9759   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9760   //     mov ECX, EBX <- t5, t6
9761   //     mov EAX, EDX <- t1, t2
9762   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9763   //     mov t3, t4 <- EAX, EDX
9764   //     bz  newMBB
9765   //     result in out1, out2
9766   //     fallthrough -->nextMBB
9767
9768   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9769   const unsigned LoadOpc = X86::MOV32rm;
9770   const unsigned NotOpc = X86::NOT32r;
9771   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9772   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9773   MachineFunction::iterator MBBIter = MBB;
9774   ++MBBIter;
9775
9776   /// First build the CFG
9777   MachineFunction *F = MBB->getParent();
9778   MachineBasicBlock *thisMBB = MBB;
9779   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9780   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9781   F->insert(MBBIter, newMBB);
9782   F->insert(MBBIter, nextMBB);
9783
9784   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9785   nextMBB->splice(nextMBB->begin(), thisMBB,
9786                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9787                   thisMBB->end());
9788   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9789
9790   // Update thisMBB to fall through to newMBB
9791   thisMBB->addSuccessor(newMBB);
9792
9793   // newMBB jumps to itself and fall through to nextMBB
9794   newMBB->addSuccessor(nextMBB);
9795   newMBB->addSuccessor(newMBB);
9796
9797   DebugLoc dl = bInstr->getDebugLoc();
9798   // Insert instructions into newMBB based on incoming instruction
9799   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9800   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9801          "unexpected number of operands");
9802   MachineOperand& dest1Oper = bInstr->getOperand(0);
9803   MachineOperand& dest2Oper = bInstr->getOperand(1);
9804   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9805   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9806     argOpers[i] = &bInstr->getOperand(i+2);
9807
9808     // We use some of the operands multiple times, so conservatively just
9809     // clear any kill flags that might be present.
9810     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9811       argOpers[i]->setIsKill(false);
9812   }
9813
9814   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9815   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9816
9817   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9818   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9819   for (int i=0; i <= lastAddrIndx; ++i)
9820     (*MIB).addOperand(*argOpers[i]);
9821   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9822   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9823   // add 4 to displacement.
9824   for (int i=0; i <= lastAddrIndx-2; ++i)
9825     (*MIB).addOperand(*argOpers[i]);
9826   MachineOperand newOp3 = *(argOpers[3]);
9827   if (newOp3.isImm())
9828     newOp3.setImm(newOp3.getImm()+4);
9829   else
9830     newOp3.setOffset(newOp3.getOffset()+4);
9831   (*MIB).addOperand(newOp3);
9832   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9833
9834   // t3/4 are defined later, at the bottom of the loop
9835   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9836   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9837   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9838     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9839   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9840     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9841
9842   // The subsequent operations should be using the destination registers of
9843   //the PHI instructions.
9844   if (invSrc) {
9845     t1 = F->getRegInfo().createVirtualRegister(RC);
9846     t2 = F->getRegInfo().createVirtualRegister(RC);
9847     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9848     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9849   } else {
9850     t1 = dest1Oper.getReg();
9851     t2 = dest2Oper.getReg();
9852   }
9853
9854   int valArgIndx = lastAddrIndx + 1;
9855   assert((argOpers[valArgIndx]->isReg() ||
9856           argOpers[valArgIndx]->isImm()) &&
9857          "invalid operand");
9858   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9859   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9860   if (argOpers[valArgIndx]->isReg())
9861     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9862   else
9863     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9864   if (regOpcL != X86::MOV32rr)
9865     MIB.addReg(t1);
9866   (*MIB).addOperand(*argOpers[valArgIndx]);
9867   assert(argOpers[valArgIndx + 1]->isReg() ==
9868          argOpers[valArgIndx]->isReg());
9869   assert(argOpers[valArgIndx + 1]->isImm() ==
9870          argOpers[valArgIndx]->isImm());
9871   if (argOpers[valArgIndx + 1]->isReg())
9872     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9873   else
9874     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9875   if (regOpcH != X86::MOV32rr)
9876     MIB.addReg(t2);
9877   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9878
9879   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9880   MIB.addReg(t1);
9881   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9882   MIB.addReg(t2);
9883
9884   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9885   MIB.addReg(t5);
9886   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9887   MIB.addReg(t6);
9888
9889   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9890   for (int i=0; i <= lastAddrIndx; ++i)
9891     (*MIB).addOperand(*argOpers[i]);
9892
9893   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9894   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9895                     bInstr->memoperands_end());
9896
9897   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9898   MIB.addReg(X86::EAX);
9899   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9900   MIB.addReg(X86::EDX);
9901
9902   // insert branch
9903   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9904
9905   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9906   return nextMBB;
9907 }
9908
9909 // private utility function
9910 MachineBasicBlock *
9911 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9912                                                       MachineBasicBlock *MBB,
9913                                                       unsigned cmovOpc) const {
9914   // For the atomic min/max operator, we generate
9915   //   thisMBB:
9916   //   newMBB:
9917   //     ld t1 = [min/max.addr]
9918   //     mov t2 = [min/max.val]
9919   //     cmp  t1, t2
9920   //     cmov[cond] t2 = t1
9921   //     mov EAX = t1
9922   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9923   //     bz   newMBB
9924   //     fallthrough -->nextMBB
9925   //
9926   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9927   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9928   MachineFunction::iterator MBBIter = MBB;
9929   ++MBBIter;
9930
9931   /// First build the CFG
9932   MachineFunction *F = MBB->getParent();
9933   MachineBasicBlock *thisMBB = MBB;
9934   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9935   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9936   F->insert(MBBIter, newMBB);
9937   F->insert(MBBIter, nextMBB);
9938
9939   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9940   nextMBB->splice(nextMBB->begin(), thisMBB,
9941                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9942                   thisMBB->end());
9943   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9944
9945   // Update thisMBB to fall through to newMBB
9946   thisMBB->addSuccessor(newMBB);
9947
9948   // newMBB jumps to newMBB and fall through to nextMBB
9949   newMBB->addSuccessor(nextMBB);
9950   newMBB->addSuccessor(newMBB);
9951
9952   DebugLoc dl = mInstr->getDebugLoc();
9953   // Insert instructions into newMBB based on incoming instruction
9954   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9955          "unexpected number of operands");
9956   MachineOperand& destOper = mInstr->getOperand(0);
9957   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9958   int numArgs = mInstr->getNumOperands() - 1;
9959   for (int i=0; i < numArgs; ++i)
9960     argOpers[i] = &mInstr->getOperand(i+1);
9961
9962   // x86 address has 4 operands: base, index, scale, and displacement
9963   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9964   int valArgIndx = lastAddrIndx + 1;
9965
9966   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9967   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9968   for (int i=0; i <= lastAddrIndx; ++i)
9969     (*MIB).addOperand(*argOpers[i]);
9970
9971   // We only support register and immediate values
9972   assert((argOpers[valArgIndx]->isReg() ||
9973           argOpers[valArgIndx]->isImm()) &&
9974          "invalid operand");
9975
9976   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9977   if (argOpers[valArgIndx]->isReg())
9978     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9979   else
9980     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9981   (*MIB).addOperand(*argOpers[valArgIndx]);
9982
9983   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9984   MIB.addReg(t1);
9985
9986   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9987   MIB.addReg(t1);
9988   MIB.addReg(t2);
9989
9990   // Generate movc
9991   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9992   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9993   MIB.addReg(t2);
9994   MIB.addReg(t1);
9995
9996   // Cmp and exchange if none has modified the memory location
9997   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9998   for (int i=0; i <= lastAddrIndx; ++i)
9999     (*MIB).addOperand(*argOpers[i]);
10000   MIB.addReg(t3);
10001   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10002   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10003                     mInstr->memoperands_end());
10004
10005   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10006   MIB.addReg(X86::EAX);
10007
10008   // insert branch
10009   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10010
10011   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10012   return nextMBB;
10013 }
10014
10015 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10016 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10017 // in the .td file.
10018 MachineBasicBlock *
10019 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10020                             unsigned numArgs, bool memArg) const {
10021   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10022          "Target must have SSE4.2 or AVX features enabled");
10023
10024   DebugLoc dl = MI->getDebugLoc();
10025   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10026   unsigned Opc;
10027   if (!Subtarget->hasAVX()) {
10028     if (memArg)
10029       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10030     else
10031       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10032   } else {
10033     if (memArg)
10034       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10035     else
10036       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10037   }
10038
10039   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10040   for (unsigned i = 0; i < numArgs; ++i) {
10041     MachineOperand &Op = MI->getOperand(i+1);
10042     if (!(Op.isReg() && Op.isImplicit()))
10043       MIB.addOperand(Op);
10044   }
10045   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10046     .addReg(X86::XMM0);
10047
10048   MI->eraseFromParent();
10049   return BB;
10050 }
10051
10052 MachineBasicBlock *
10053 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10054   DebugLoc dl = MI->getDebugLoc();
10055   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10056
10057   // Address into RAX/EAX, other two args into ECX, EDX.
10058   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10059   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10060   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10061   for (int i = 0; i < X86::AddrNumOperands; ++i)
10062     MIB.addOperand(MI->getOperand(i));
10063
10064   unsigned ValOps = X86::AddrNumOperands;
10065   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10066     .addReg(MI->getOperand(ValOps).getReg());
10067   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10068     .addReg(MI->getOperand(ValOps+1).getReg());
10069
10070   // The instruction doesn't actually take any operands though.
10071   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10072
10073   MI->eraseFromParent(); // The pseudo is gone now.
10074   return BB;
10075 }
10076
10077 MachineBasicBlock *
10078 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
10079   DebugLoc dl = MI->getDebugLoc();
10080   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10081
10082   // First arg in ECX, the second in EAX.
10083   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10084     .addReg(MI->getOperand(0).getReg());
10085   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
10086     .addReg(MI->getOperand(1).getReg());
10087
10088   // The instruction doesn't actually take any operands though.
10089   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
10090
10091   MI->eraseFromParent(); // The pseudo is gone now.
10092   return BB;
10093 }
10094
10095 MachineBasicBlock *
10096 X86TargetLowering::EmitVAARG64WithCustomInserter(
10097                    MachineInstr *MI,
10098                    MachineBasicBlock *MBB) const {
10099   // Emit va_arg instruction on X86-64.
10100
10101   // Operands to this pseudo-instruction:
10102   // 0  ) Output        : destination address (reg)
10103   // 1-5) Input         : va_list address (addr, i64mem)
10104   // 6  ) ArgSize       : Size (in bytes) of vararg type
10105   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
10106   // 8  ) Align         : Alignment of type
10107   // 9  ) EFLAGS (implicit-def)
10108
10109   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
10110   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
10111
10112   unsigned DestReg = MI->getOperand(0).getReg();
10113   MachineOperand &Base = MI->getOperand(1);
10114   MachineOperand &Scale = MI->getOperand(2);
10115   MachineOperand &Index = MI->getOperand(3);
10116   MachineOperand &Disp = MI->getOperand(4);
10117   MachineOperand &Segment = MI->getOperand(5);
10118   unsigned ArgSize = MI->getOperand(6).getImm();
10119   unsigned ArgMode = MI->getOperand(7).getImm();
10120   unsigned Align = MI->getOperand(8).getImm();
10121
10122   // Memory Reference
10123   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
10124   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
10125   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
10126
10127   // Machine Information
10128   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10129   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10130   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
10131   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
10132   DebugLoc DL = MI->getDebugLoc();
10133
10134   // struct va_list {
10135   //   i32   gp_offset
10136   //   i32   fp_offset
10137   //   i64   overflow_area (address)
10138   //   i64   reg_save_area (address)
10139   // }
10140   // sizeof(va_list) = 24
10141   // alignment(va_list) = 8
10142
10143   unsigned TotalNumIntRegs = 6;
10144   unsigned TotalNumXMMRegs = 8;
10145   bool UseGPOffset = (ArgMode == 1);
10146   bool UseFPOffset = (ArgMode == 2);
10147   unsigned MaxOffset = TotalNumIntRegs * 8 +
10148                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
10149
10150   /* Align ArgSize to a multiple of 8 */
10151   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
10152   bool NeedsAlign = (Align > 8);
10153
10154   MachineBasicBlock *thisMBB = MBB;
10155   MachineBasicBlock *overflowMBB;
10156   MachineBasicBlock *offsetMBB;
10157   MachineBasicBlock *endMBB;
10158
10159   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
10160   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
10161   unsigned OffsetReg = 0;
10162
10163   if (!UseGPOffset && !UseFPOffset) {
10164     // If we only pull from the overflow region, we don't create a branch.
10165     // We don't need to alter control flow.
10166     OffsetDestReg = 0; // unused
10167     OverflowDestReg = DestReg;
10168
10169     offsetMBB = NULL;
10170     overflowMBB = thisMBB;
10171     endMBB = thisMBB;
10172   } else {
10173     // First emit code to check if gp_offset (or fp_offset) is below the bound.
10174     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
10175     // If not, pull from overflow_area. (branch to overflowMBB)
10176     //
10177     //       thisMBB
10178     //         |     .
10179     //         |        .
10180     //     offsetMBB   overflowMBB
10181     //         |        .
10182     //         |     .
10183     //        endMBB
10184
10185     // Registers for the PHI in endMBB
10186     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10187     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10188
10189     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10190     MachineFunction *MF = MBB->getParent();
10191     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10192     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10193     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10194
10195     MachineFunction::iterator MBBIter = MBB;
10196     ++MBBIter;
10197
10198     // Insert the new basic blocks
10199     MF->insert(MBBIter, offsetMBB);
10200     MF->insert(MBBIter, overflowMBB);
10201     MF->insert(MBBIter, endMBB);
10202
10203     // Transfer the remainder of MBB and its successor edges to endMBB.
10204     endMBB->splice(endMBB->begin(), thisMBB,
10205                     llvm::next(MachineBasicBlock::iterator(MI)),
10206                     thisMBB->end());
10207     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10208
10209     // Make offsetMBB and overflowMBB successors of thisMBB
10210     thisMBB->addSuccessor(offsetMBB);
10211     thisMBB->addSuccessor(overflowMBB);
10212
10213     // endMBB is a successor of both offsetMBB and overflowMBB
10214     offsetMBB->addSuccessor(endMBB);
10215     overflowMBB->addSuccessor(endMBB);
10216
10217     // Load the offset value into a register
10218     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10219     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10220       .addOperand(Base)
10221       .addOperand(Scale)
10222       .addOperand(Index)
10223       .addDisp(Disp, UseFPOffset ? 4 : 0)
10224       .addOperand(Segment)
10225       .setMemRefs(MMOBegin, MMOEnd);
10226
10227     // Check if there is enough room left to pull this argument.
10228     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10229       .addReg(OffsetReg)
10230       .addImm(MaxOffset + 8 - ArgSizeA8);
10231
10232     // Branch to "overflowMBB" if offset >= max
10233     // Fall through to "offsetMBB" otherwise
10234     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10235       .addMBB(overflowMBB);
10236   }
10237
10238   // In offsetMBB, emit code to use the reg_save_area.
10239   if (offsetMBB) {
10240     assert(OffsetReg != 0);
10241
10242     // Read the reg_save_area address.
10243     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10244     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10245       .addOperand(Base)
10246       .addOperand(Scale)
10247       .addOperand(Index)
10248       .addDisp(Disp, 16)
10249       .addOperand(Segment)
10250       .setMemRefs(MMOBegin, MMOEnd);
10251
10252     // Zero-extend the offset
10253     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10254       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10255         .addImm(0)
10256         .addReg(OffsetReg)
10257         .addImm(X86::sub_32bit);
10258
10259     // Add the offset to the reg_save_area to get the final address.
10260     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10261       .addReg(OffsetReg64)
10262       .addReg(RegSaveReg);
10263
10264     // Compute the offset for the next argument
10265     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10266     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10267       .addReg(OffsetReg)
10268       .addImm(UseFPOffset ? 16 : 8);
10269
10270     // Store it back into the va_list.
10271     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10272       .addOperand(Base)
10273       .addOperand(Scale)
10274       .addOperand(Index)
10275       .addDisp(Disp, UseFPOffset ? 4 : 0)
10276       .addOperand(Segment)
10277       .addReg(NextOffsetReg)
10278       .setMemRefs(MMOBegin, MMOEnd);
10279
10280     // Jump to endMBB
10281     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10282       .addMBB(endMBB);
10283   }
10284
10285   //
10286   // Emit code to use overflow area
10287   //
10288
10289   // Load the overflow_area address into a register.
10290   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10291   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10292     .addOperand(Base)
10293     .addOperand(Scale)
10294     .addOperand(Index)
10295     .addDisp(Disp, 8)
10296     .addOperand(Segment)
10297     .setMemRefs(MMOBegin, MMOEnd);
10298
10299   // If we need to align it, do so. Otherwise, just copy the address
10300   // to OverflowDestReg.
10301   if (NeedsAlign) {
10302     // Align the overflow address
10303     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10304     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10305
10306     // aligned_addr = (addr + (align-1)) & ~(align-1)
10307     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10308       .addReg(OverflowAddrReg)
10309       .addImm(Align-1);
10310
10311     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10312       .addReg(TmpReg)
10313       .addImm(~(uint64_t)(Align-1));
10314   } else {
10315     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10316       .addReg(OverflowAddrReg);
10317   }
10318
10319   // Compute the next overflow address after this argument.
10320   // (the overflow address should be kept 8-byte aligned)
10321   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10322   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10323     .addReg(OverflowDestReg)
10324     .addImm(ArgSizeA8);
10325
10326   // Store the new overflow address.
10327   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10328     .addOperand(Base)
10329     .addOperand(Scale)
10330     .addOperand(Index)
10331     .addDisp(Disp, 8)
10332     .addOperand(Segment)
10333     .addReg(NextAddrReg)
10334     .setMemRefs(MMOBegin, MMOEnd);
10335
10336   // If we branched, emit the PHI to the front of endMBB.
10337   if (offsetMBB) {
10338     BuildMI(*endMBB, endMBB->begin(), DL,
10339             TII->get(X86::PHI), DestReg)
10340       .addReg(OffsetDestReg).addMBB(offsetMBB)
10341       .addReg(OverflowDestReg).addMBB(overflowMBB);
10342   }
10343
10344   // Erase the pseudo instruction
10345   MI->eraseFromParent();
10346
10347   return endMBB;
10348 }
10349
10350 MachineBasicBlock *
10351 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10352                                                  MachineInstr *MI,
10353                                                  MachineBasicBlock *MBB) const {
10354   // Emit code to save XMM registers to the stack. The ABI says that the
10355   // number of registers to save is given in %al, so it's theoretically
10356   // possible to do an indirect jump trick to avoid saving all of them,
10357   // however this code takes a simpler approach and just executes all
10358   // of the stores if %al is non-zero. It's less code, and it's probably
10359   // easier on the hardware branch predictor, and stores aren't all that
10360   // expensive anyway.
10361
10362   // Create the new basic blocks. One block contains all the XMM stores,
10363   // and one block is the final destination regardless of whether any
10364   // stores were performed.
10365   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10366   MachineFunction *F = MBB->getParent();
10367   MachineFunction::iterator MBBIter = MBB;
10368   ++MBBIter;
10369   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10370   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10371   F->insert(MBBIter, XMMSaveMBB);
10372   F->insert(MBBIter, EndMBB);
10373
10374   // Transfer the remainder of MBB and its successor edges to EndMBB.
10375   EndMBB->splice(EndMBB->begin(), MBB,
10376                  llvm::next(MachineBasicBlock::iterator(MI)),
10377                  MBB->end());
10378   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10379
10380   // The original block will now fall through to the XMM save block.
10381   MBB->addSuccessor(XMMSaveMBB);
10382   // The XMMSaveMBB will fall through to the end block.
10383   XMMSaveMBB->addSuccessor(EndMBB);
10384
10385   // Now add the instructions.
10386   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10387   DebugLoc DL = MI->getDebugLoc();
10388
10389   unsigned CountReg = MI->getOperand(0).getReg();
10390   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10391   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10392
10393   if (!Subtarget->isTargetWin64()) {
10394     // If %al is 0, branch around the XMM save block.
10395     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10396     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10397     MBB->addSuccessor(EndMBB);
10398   }
10399
10400   // In the XMM save block, save all the XMM argument registers.
10401   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10402     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10403     MachineMemOperand *MMO =
10404       F->getMachineMemOperand(
10405           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10406         MachineMemOperand::MOStore,
10407         /*Size=*/16, /*Align=*/16);
10408     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10409       .addFrameIndex(RegSaveFrameIndex)
10410       .addImm(/*Scale=*/1)
10411       .addReg(/*IndexReg=*/0)
10412       .addImm(/*Disp=*/Offset)
10413       .addReg(/*Segment=*/0)
10414       .addReg(MI->getOperand(i).getReg())
10415       .addMemOperand(MMO);
10416   }
10417
10418   MI->eraseFromParent();   // The pseudo instruction is gone now.
10419
10420   return EndMBB;
10421 }
10422
10423 MachineBasicBlock *
10424 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10425                                      MachineBasicBlock *BB) const {
10426   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10427   DebugLoc DL = MI->getDebugLoc();
10428
10429   // To "insert" a SELECT_CC instruction, we actually have to insert the
10430   // diamond control-flow pattern.  The incoming instruction knows the
10431   // destination vreg to set, the condition code register to branch on, the
10432   // true/false values to select between, and a branch opcode to use.
10433   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10434   MachineFunction::iterator It = BB;
10435   ++It;
10436
10437   //  thisMBB:
10438   //  ...
10439   //   TrueVal = ...
10440   //   cmpTY ccX, r1, r2
10441   //   bCC copy1MBB
10442   //   fallthrough --> copy0MBB
10443   MachineBasicBlock *thisMBB = BB;
10444   MachineFunction *F = BB->getParent();
10445   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10446   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10447   F->insert(It, copy0MBB);
10448   F->insert(It, sinkMBB);
10449
10450   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10451   // live into the sink and copy blocks.
10452   const MachineFunction *MF = BB->getParent();
10453   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10454   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10455
10456   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10457     const MachineOperand &MO = MI->getOperand(I);
10458     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10459     unsigned Reg = MO.getReg();
10460     if (Reg != X86::EFLAGS) continue;
10461     copy0MBB->addLiveIn(Reg);
10462     sinkMBB->addLiveIn(Reg);
10463   }
10464
10465   // Transfer the remainder of BB and its successor edges to sinkMBB.
10466   sinkMBB->splice(sinkMBB->begin(), BB,
10467                   llvm::next(MachineBasicBlock::iterator(MI)),
10468                   BB->end());
10469   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10470
10471   // Add the true and fallthrough blocks as its successors.
10472   BB->addSuccessor(copy0MBB);
10473   BB->addSuccessor(sinkMBB);
10474
10475   // Create the conditional branch instruction.
10476   unsigned Opc =
10477     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10478   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10479
10480   //  copy0MBB:
10481   //   %FalseValue = ...
10482   //   # fallthrough to sinkMBB
10483   copy0MBB->addSuccessor(sinkMBB);
10484
10485   //  sinkMBB:
10486   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10487   //  ...
10488   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10489           TII->get(X86::PHI), MI->getOperand(0).getReg())
10490     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10491     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10492
10493   MI->eraseFromParent();   // The pseudo instruction is gone now.
10494   return sinkMBB;
10495 }
10496
10497 MachineBasicBlock *
10498 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10499                                           MachineBasicBlock *BB) const {
10500   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10501   DebugLoc DL = MI->getDebugLoc();
10502
10503   assert(!Subtarget->isTargetEnvMacho());
10504
10505   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10506   // non-trivial part is impdef of ESP.
10507
10508   if (Subtarget->isTargetWin64()) {
10509     if (Subtarget->isTargetCygMing()) {
10510       // ___chkstk(Mingw64):
10511       // Clobbers R10, R11, RAX and EFLAGS.
10512       // Updates RSP.
10513       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10514         .addExternalSymbol("___chkstk")
10515         .addReg(X86::RAX, RegState::Implicit)
10516         .addReg(X86::RSP, RegState::Implicit)
10517         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
10518         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
10519         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10520     } else {
10521       // __chkstk(MSVCRT): does not update stack pointer.
10522       // Clobbers R10, R11 and EFLAGS.
10523       // FIXME: RAX(allocated size) might be reused and not killed.
10524       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
10525         .addExternalSymbol("__chkstk")
10526         .addReg(X86::RAX, RegState::Implicit)
10527         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10528       // RAX has the offset to subtracted from RSP.
10529       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
10530         .addReg(X86::RSP)
10531         .addReg(X86::RAX);
10532     }
10533   } else {
10534     const char *StackProbeSymbol =
10535       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10536
10537     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10538       .addExternalSymbol(StackProbeSymbol)
10539       .addReg(X86::EAX, RegState::Implicit)
10540       .addReg(X86::ESP, RegState::Implicit)
10541       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10542       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10543       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10544   }
10545
10546   MI->eraseFromParent();   // The pseudo instruction is gone now.
10547   return BB;
10548 }
10549
10550 MachineBasicBlock *
10551 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10552                                       MachineBasicBlock *BB) const {
10553   // This is pretty easy.  We're taking the value that we received from
10554   // our load from the relocation, sticking it in either RDI (x86-64)
10555   // or EAX and doing an indirect call.  The return value will then
10556   // be in the normal return register.
10557   const X86InstrInfo *TII
10558     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10559   DebugLoc DL = MI->getDebugLoc();
10560   MachineFunction *F = BB->getParent();
10561
10562   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10563   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10564
10565   if (Subtarget->is64Bit()) {
10566     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10567                                       TII->get(X86::MOV64rm), X86::RDI)
10568     .addReg(X86::RIP)
10569     .addImm(0).addReg(0)
10570     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10571                       MI->getOperand(3).getTargetFlags())
10572     .addReg(0);
10573     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10574     addDirectMem(MIB, X86::RDI);
10575   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10576     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10577                                       TII->get(X86::MOV32rm), X86::EAX)
10578     .addReg(0)
10579     .addImm(0).addReg(0)
10580     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10581                       MI->getOperand(3).getTargetFlags())
10582     .addReg(0);
10583     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10584     addDirectMem(MIB, X86::EAX);
10585   } else {
10586     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10587                                       TII->get(X86::MOV32rm), X86::EAX)
10588     .addReg(TII->getGlobalBaseReg(F))
10589     .addImm(0).addReg(0)
10590     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10591                       MI->getOperand(3).getTargetFlags())
10592     .addReg(0);
10593     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10594     addDirectMem(MIB, X86::EAX);
10595   }
10596
10597   MI->eraseFromParent(); // The pseudo instruction is gone now.
10598   return BB;
10599 }
10600
10601 MachineBasicBlock *
10602 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10603                                                MachineBasicBlock *BB) const {
10604   switch (MI->getOpcode()) {
10605   default: assert(false && "Unexpected instr type to insert");
10606   case X86::TAILJMPd64:
10607   case X86::TAILJMPr64:
10608   case X86::TAILJMPm64:
10609     assert(!"TAILJMP64 would not be touched here.");
10610   case X86::TCRETURNdi64:
10611   case X86::TCRETURNri64:
10612   case X86::TCRETURNmi64:
10613     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10614     // On AMD64, additional defs should be added before register allocation.
10615     if (!Subtarget->isTargetWin64()) {
10616       MI->addRegisterDefined(X86::RSI);
10617       MI->addRegisterDefined(X86::RDI);
10618       MI->addRegisterDefined(X86::XMM6);
10619       MI->addRegisterDefined(X86::XMM7);
10620       MI->addRegisterDefined(X86::XMM8);
10621       MI->addRegisterDefined(X86::XMM9);
10622       MI->addRegisterDefined(X86::XMM10);
10623       MI->addRegisterDefined(X86::XMM11);
10624       MI->addRegisterDefined(X86::XMM12);
10625       MI->addRegisterDefined(X86::XMM13);
10626       MI->addRegisterDefined(X86::XMM14);
10627       MI->addRegisterDefined(X86::XMM15);
10628     }
10629     return BB;
10630   case X86::WIN_ALLOCA:
10631     return EmitLoweredWinAlloca(MI, BB);
10632   case X86::TLSCall_32:
10633   case X86::TLSCall_64:
10634     return EmitLoweredTLSCall(MI, BB);
10635   case X86::CMOV_GR8:
10636   case X86::CMOV_FR32:
10637   case X86::CMOV_FR64:
10638   case X86::CMOV_V4F32:
10639   case X86::CMOV_V2F64:
10640   case X86::CMOV_V2I64:
10641   case X86::CMOV_GR16:
10642   case X86::CMOV_GR32:
10643   case X86::CMOV_RFP32:
10644   case X86::CMOV_RFP64:
10645   case X86::CMOV_RFP80:
10646     return EmitLoweredSelect(MI, BB);
10647
10648   case X86::FP32_TO_INT16_IN_MEM:
10649   case X86::FP32_TO_INT32_IN_MEM:
10650   case X86::FP32_TO_INT64_IN_MEM:
10651   case X86::FP64_TO_INT16_IN_MEM:
10652   case X86::FP64_TO_INT32_IN_MEM:
10653   case X86::FP64_TO_INT64_IN_MEM:
10654   case X86::FP80_TO_INT16_IN_MEM:
10655   case X86::FP80_TO_INT32_IN_MEM:
10656   case X86::FP80_TO_INT64_IN_MEM: {
10657     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10658     DebugLoc DL = MI->getDebugLoc();
10659
10660     // Change the floating point control register to use "round towards zero"
10661     // mode when truncating to an integer value.
10662     MachineFunction *F = BB->getParent();
10663     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10664     addFrameReference(BuildMI(*BB, MI, DL,
10665                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10666
10667     // Load the old value of the high byte of the control word...
10668     unsigned OldCW =
10669       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10670     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10671                       CWFrameIdx);
10672
10673     // Set the high part to be round to zero...
10674     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10675       .addImm(0xC7F);
10676
10677     // Reload the modified control word now...
10678     addFrameReference(BuildMI(*BB, MI, DL,
10679                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10680
10681     // Restore the memory image of control word to original value
10682     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10683       .addReg(OldCW);
10684
10685     // Get the X86 opcode to use.
10686     unsigned Opc;
10687     switch (MI->getOpcode()) {
10688     default: llvm_unreachable("illegal opcode!");
10689     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10690     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10691     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10692     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10693     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10694     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10695     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10696     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10697     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10698     }
10699
10700     X86AddressMode AM;
10701     MachineOperand &Op = MI->getOperand(0);
10702     if (Op.isReg()) {
10703       AM.BaseType = X86AddressMode::RegBase;
10704       AM.Base.Reg = Op.getReg();
10705     } else {
10706       AM.BaseType = X86AddressMode::FrameIndexBase;
10707       AM.Base.FrameIndex = Op.getIndex();
10708     }
10709     Op = MI->getOperand(1);
10710     if (Op.isImm())
10711       AM.Scale = Op.getImm();
10712     Op = MI->getOperand(2);
10713     if (Op.isImm())
10714       AM.IndexReg = Op.getImm();
10715     Op = MI->getOperand(3);
10716     if (Op.isGlobal()) {
10717       AM.GV = Op.getGlobal();
10718     } else {
10719       AM.Disp = Op.getImm();
10720     }
10721     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10722                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10723
10724     // Reload the original control word now.
10725     addFrameReference(BuildMI(*BB, MI, DL,
10726                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10727
10728     MI->eraseFromParent();   // The pseudo instruction is gone now.
10729     return BB;
10730   }
10731     // String/text processing lowering.
10732   case X86::PCMPISTRM128REG:
10733   case X86::VPCMPISTRM128REG:
10734     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10735   case X86::PCMPISTRM128MEM:
10736   case X86::VPCMPISTRM128MEM:
10737     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10738   case X86::PCMPESTRM128REG:
10739   case X86::VPCMPESTRM128REG:
10740     return EmitPCMP(MI, BB, 5, false /* in mem */);
10741   case X86::PCMPESTRM128MEM:
10742   case X86::VPCMPESTRM128MEM:
10743     return EmitPCMP(MI, BB, 5, true /* in mem */);
10744
10745     // Thread synchronization.
10746   case X86::MONITOR:
10747     return EmitMonitor(MI, BB);
10748   case X86::MWAIT:
10749     return EmitMwait(MI, BB);
10750
10751     // Atomic Lowering.
10752   case X86::ATOMAND32:
10753     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10754                                                X86::AND32ri, X86::MOV32rm,
10755                                                X86::LCMPXCHG32,
10756                                                X86::NOT32r, X86::EAX,
10757                                                X86::GR32RegisterClass);
10758   case X86::ATOMOR32:
10759     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10760                                                X86::OR32ri, X86::MOV32rm,
10761                                                X86::LCMPXCHG32,
10762                                                X86::NOT32r, X86::EAX,
10763                                                X86::GR32RegisterClass);
10764   case X86::ATOMXOR32:
10765     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10766                                                X86::XOR32ri, X86::MOV32rm,
10767                                                X86::LCMPXCHG32,
10768                                                X86::NOT32r, X86::EAX,
10769                                                X86::GR32RegisterClass);
10770   case X86::ATOMNAND32:
10771     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10772                                                X86::AND32ri, X86::MOV32rm,
10773                                                X86::LCMPXCHG32,
10774                                                X86::NOT32r, X86::EAX,
10775                                                X86::GR32RegisterClass, true);
10776   case X86::ATOMMIN32:
10777     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10778   case X86::ATOMMAX32:
10779     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10780   case X86::ATOMUMIN32:
10781     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10782   case X86::ATOMUMAX32:
10783     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10784
10785   case X86::ATOMAND16:
10786     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10787                                                X86::AND16ri, X86::MOV16rm,
10788                                                X86::LCMPXCHG16,
10789                                                X86::NOT16r, X86::AX,
10790                                                X86::GR16RegisterClass);
10791   case X86::ATOMOR16:
10792     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10793                                                X86::OR16ri, X86::MOV16rm,
10794                                                X86::LCMPXCHG16,
10795                                                X86::NOT16r, X86::AX,
10796                                                X86::GR16RegisterClass);
10797   case X86::ATOMXOR16:
10798     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10799                                                X86::XOR16ri, X86::MOV16rm,
10800                                                X86::LCMPXCHG16,
10801                                                X86::NOT16r, X86::AX,
10802                                                X86::GR16RegisterClass);
10803   case X86::ATOMNAND16:
10804     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10805                                                X86::AND16ri, X86::MOV16rm,
10806                                                X86::LCMPXCHG16,
10807                                                X86::NOT16r, X86::AX,
10808                                                X86::GR16RegisterClass, true);
10809   case X86::ATOMMIN16:
10810     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10811   case X86::ATOMMAX16:
10812     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10813   case X86::ATOMUMIN16:
10814     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10815   case X86::ATOMUMAX16:
10816     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10817
10818   case X86::ATOMAND8:
10819     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10820                                                X86::AND8ri, X86::MOV8rm,
10821                                                X86::LCMPXCHG8,
10822                                                X86::NOT8r, X86::AL,
10823                                                X86::GR8RegisterClass);
10824   case X86::ATOMOR8:
10825     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10826                                                X86::OR8ri, X86::MOV8rm,
10827                                                X86::LCMPXCHG8,
10828                                                X86::NOT8r, X86::AL,
10829                                                X86::GR8RegisterClass);
10830   case X86::ATOMXOR8:
10831     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10832                                                X86::XOR8ri, X86::MOV8rm,
10833                                                X86::LCMPXCHG8,
10834                                                X86::NOT8r, X86::AL,
10835                                                X86::GR8RegisterClass);
10836   case X86::ATOMNAND8:
10837     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10838                                                X86::AND8ri, X86::MOV8rm,
10839                                                X86::LCMPXCHG8,
10840                                                X86::NOT8r, X86::AL,
10841                                                X86::GR8RegisterClass, true);
10842   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10843   // This group is for 64-bit host.
10844   case X86::ATOMAND64:
10845     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10846                                                X86::AND64ri32, X86::MOV64rm,
10847                                                X86::LCMPXCHG64,
10848                                                X86::NOT64r, X86::RAX,
10849                                                X86::GR64RegisterClass);
10850   case X86::ATOMOR64:
10851     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10852                                                X86::OR64ri32, X86::MOV64rm,
10853                                                X86::LCMPXCHG64,
10854                                                X86::NOT64r, X86::RAX,
10855                                                X86::GR64RegisterClass);
10856   case X86::ATOMXOR64:
10857     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10858                                                X86::XOR64ri32, X86::MOV64rm,
10859                                                X86::LCMPXCHG64,
10860                                                X86::NOT64r, X86::RAX,
10861                                                X86::GR64RegisterClass);
10862   case X86::ATOMNAND64:
10863     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10864                                                X86::AND64ri32, X86::MOV64rm,
10865                                                X86::LCMPXCHG64,
10866                                                X86::NOT64r, X86::RAX,
10867                                                X86::GR64RegisterClass, true);
10868   case X86::ATOMMIN64:
10869     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10870   case X86::ATOMMAX64:
10871     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10872   case X86::ATOMUMIN64:
10873     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10874   case X86::ATOMUMAX64:
10875     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10876
10877   // This group does 64-bit operations on a 32-bit host.
10878   case X86::ATOMAND6432:
10879     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10880                                                X86::AND32rr, X86::AND32rr,
10881                                                X86::AND32ri, X86::AND32ri,
10882                                                false);
10883   case X86::ATOMOR6432:
10884     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10885                                                X86::OR32rr, X86::OR32rr,
10886                                                X86::OR32ri, X86::OR32ri,
10887                                                false);
10888   case X86::ATOMXOR6432:
10889     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10890                                                X86::XOR32rr, X86::XOR32rr,
10891                                                X86::XOR32ri, X86::XOR32ri,
10892                                                false);
10893   case X86::ATOMNAND6432:
10894     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10895                                                X86::AND32rr, X86::AND32rr,
10896                                                X86::AND32ri, X86::AND32ri,
10897                                                true);
10898   case X86::ATOMADD6432:
10899     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10900                                                X86::ADD32rr, X86::ADC32rr,
10901                                                X86::ADD32ri, X86::ADC32ri,
10902                                                false);
10903   case X86::ATOMSUB6432:
10904     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10905                                                X86::SUB32rr, X86::SBB32rr,
10906                                                X86::SUB32ri, X86::SBB32ri,
10907                                                false);
10908   case X86::ATOMSWAP6432:
10909     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10910                                                X86::MOV32rr, X86::MOV32rr,
10911                                                X86::MOV32ri, X86::MOV32ri,
10912                                                false);
10913   case X86::VASTART_SAVE_XMM_REGS:
10914     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10915
10916   case X86::VAARG_64:
10917     return EmitVAARG64WithCustomInserter(MI, BB);
10918   }
10919 }
10920
10921 //===----------------------------------------------------------------------===//
10922 //                           X86 Optimization Hooks
10923 //===----------------------------------------------------------------------===//
10924
10925 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10926                                                        const APInt &Mask,
10927                                                        APInt &KnownZero,
10928                                                        APInt &KnownOne,
10929                                                        const SelectionDAG &DAG,
10930                                                        unsigned Depth) const {
10931   unsigned Opc = Op.getOpcode();
10932   assert((Opc >= ISD::BUILTIN_OP_END ||
10933           Opc == ISD::INTRINSIC_WO_CHAIN ||
10934           Opc == ISD::INTRINSIC_W_CHAIN ||
10935           Opc == ISD::INTRINSIC_VOID) &&
10936          "Should use MaskedValueIsZero if you don't know whether Op"
10937          " is a target node!");
10938
10939   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10940   switch (Opc) {
10941   default: break;
10942   case X86ISD::ADD:
10943   case X86ISD::SUB:
10944   case X86ISD::ADC:
10945   case X86ISD::SBB:
10946   case X86ISD::SMUL:
10947   case X86ISD::UMUL:
10948   case X86ISD::INC:
10949   case X86ISD::DEC:
10950   case X86ISD::OR:
10951   case X86ISD::XOR:
10952   case X86ISD::AND:
10953     // These nodes' second result is a boolean.
10954     if (Op.getResNo() == 0)
10955       break;
10956     // Fallthrough
10957   case X86ISD::SETCC:
10958     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10959                                        Mask.getBitWidth() - 1);
10960     break;
10961   }
10962 }
10963
10964 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10965                                                          unsigned Depth) const {
10966   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10967   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10968     return Op.getValueType().getScalarType().getSizeInBits();
10969
10970   // Fallback case.
10971   return 1;
10972 }
10973
10974 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10975 /// node is a GlobalAddress + offset.
10976 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10977                                        const GlobalValue* &GA,
10978                                        int64_t &Offset) const {
10979   if (N->getOpcode() == X86ISD::Wrapper) {
10980     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10981       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10982       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10983       return true;
10984     }
10985   }
10986   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10987 }
10988
10989 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10990 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10991 /// if the load addresses are consecutive, non-overlapping, and in the right
10992 /// order.
10993 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10994                                      TargetLowering::DAGCombinerInfo &DCI) {
10995   DebugLoc dl = N->getDebugLoc();
10996   EVT VT = N->getValueType(0);
10997
10998   if (VT.getSizeInBits() != 128)
10999     return SDValue();
11000
11001   // Don't create instructions with illegal types after legalize types has run.
11002   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11003   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
11004     return SDValue();
11005
11006   SmallVector<SDValue, 16> Elts;
11007   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
11008     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
11009
11010   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
11011 }
11012
11013 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
11014 /// generation and convert it from being a bunch of shuffles and extracts
11015 /// to a simple store and scalar loads to extract the elements.
11016 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
11017                                                 const TargetLowering &TLI) {
11018   SDValue InputVector = N->getOperand(0);
11019
11020   // Only operate on vectors of 4 elements, where the alternative shuffling
11021   // gets to be more expensive.
11022   if (InputVector.getValueType() != MVT::v4i32)
11023     return SDValue();
11024
11025   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
11026   // single use which is a sign-extend or zero-extend, and all elements are
11027   // used.
11028   SmallVector<SDNode *, 4> Uses;
11029   unsigned ExtractedElements = 0;
11030   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
11031        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
11032     if (UI.getUse().getResNo() != InputVector.getResNo())
11033       return SDValue();
11034
11035     SDNode *Extract = *UI;
11036     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11037       return SDValue();
11038
11039     if (Extract->getValueType(0) != MVT::i32)
11040       return SDValue();
11041     if (!Extract->hasOneUse())
11042       return SDValue();
11043     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
11044         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
11045       return SDValue();
11046     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
11047       return SDValue();
11048
11049     // Record which element was extracted.
11050     ExtractedElements |=
11051       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
11052
11053     Uses.push_back(Extract);
11054   }
11055
11056   // If not all the elements were used, this may not be worthwhile.
11057   if (ExtractedElements != 15)
11058     return SDValue();
11059
11060   // Ok, we've now decided to do the transformation.
11061   DebugLoc dl = InputVector.getDebugLoc();
11062
11063   // Store the value to a temporary stack slot.
11064   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
11065   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
11066                             MachinePointerInfo(), false, false, 0);
11067
11068   // Replace each use (extract) with a load of the appropriate element.
11069   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
11070        UE = Uses.end(); UI != UE; ++UI) {
11071     SDNode *Extract = *UI;
11072
11073     // cOMpute the element's address.
11074     SDValue Idx = Extract->getOperand(1);
11075     unsigned EltSize =
11076         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
11077     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
11078     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
11079
11080     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
11081                                      StackPtr, OffsetVal);
11082
11083     // Load the scalar.
11084     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
11085                                      ScalarAddr, MachinePointerInfo(),
11086                                      false, false, 0);
11087
11088     // Replace the exact with the load.
11089     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
11090   }
11091
11092   // The replacement was made in place; don't return anything.
11093   return SDValue();
11094 }
11095
11096 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
11097 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
11098                                     const X86Subtarget *Subtarget) {
11099   DebugLoc DL = N->getDebugLoc();
11100   SDValue Cond = N->getOperand(0);
11101   // Get the LHS/RHS of the select.
11102   SDValue LHS = N->getOperand(1);
11103   SDValue RHS = N->getOperand(2);
11104
11105   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
11106   // instructions match the semantics of the common C idiom x<y?x:y but not
11107   // x<=y?x:y, because of how they handle negative zero (which can be
11108   // ignored in unsafe-math mode).
11109   if (Subtarget->hasSSE2() &&
11110       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
11111       Cond.getOpcode() == ISD::SETCC) {
11112     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
11113
11114     unsigned Opcode = 0;
11115     // Check for x CC y ? x : y.
11116     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
11117         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
11118       switch (CC) {
11119       default: break;
11120       case ISD::SETULT:
11121         // Converting this to a min would handle NaNs incorrectly, and swapping
11122         // the operands would cause it to handle comparisons between positive
11123         // and negative zero incorrectly.
11124         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11125           if (!UnsafeFPMath &&
11126               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11127             break;
11128           std::swap(LHS, RHS);
11129         }
11130         Opcode = X86ISD::FMIN;
11131         break;
11132       case ISD::SETOLE:
11133         // Converting this to a min would handle comparisons between positive
11134         // and negative zero incorrectly.
11135         if (!UnsafeFPMath &&
11136             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
11137           break;
11138         Opcode = X86ISD::FMIN;
11139         break;
11140       case ISD::SETULE:
11141         // Converting this to a min would handle both negative zeros and NaNs
11142         // incorrectly, but we can swap the operands to fix both.
11143         std::swap(LHS, RHS);
11144       case ISD::SETOLT:
11145       case ISD::SETLT:
11146       case ISD::SETLE:
11147         Opcode = X86ISD::FMIN;
11148         break;
11149
11150       case ISD::SETOGE:
11151         // Converting this to a max would handle comparisons between positive
11152         // and negative zero incorrectly.
11153         if (!UnsafeFPMath &&
11154             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
11155           break;
11156         Opcode = X86ISD::FMAX;
11157         break;
11158       case ISD::SETUGT:
11159         // Converting this to a max would handle NaNs incorrectly, and swapping
11160         // the operands would cause it to handle comparisons between positive
11161         // and negative zero incorrectly.
11162         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
11163           if (!UnsafeFPMath &&
11164               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
11165             break;
11166           std::swap(LHS, RHS);
11167         }
11168         Opcode = X86ISD::FMAX;
11169         break;
11170       case ISD::SETUGE:
11171         // Converting this to a max would handle both negative zeros and NaNs
11172         // incorrectly, but we can swap the operands to fix both.
11173         std::swap(LHS, RHS);
11174       case ISD::SETOGT:
11175       case ISD::SETGT:
11176       case ISD::SETGE:
11177         Opcode = X86ISD::FMAX;
11178         break;
11179       }
11180     // Check for x CC y ? y : x -- a min/max with reversed arms.
11181     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
11182                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
11183       switch (CC) {
11184       default: break;
11185       case ISD::SETOGE:
11186         // Converting this to a min would handle comparisons between positive
11187         // and negative zero incorrectly, and swapping the operands would
11188         // cause it to handle NaNs incorrectly.
11189         if (!UnsafeFPMath &&
11190             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
11191           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11192             break;
11193           std::swap(LHS, RHS);
11194         }
11195         Opcode = X86ISD::FMIN;
11196         break;
11197       case ISD::SETUGT:
11198         // Converting this to a min would handle NaNs incorrectly.
11199         if (!UnsafeFPMath &&
11200             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
11201           break;
11202         Opcode = X86ISD::FMIN;
11203         break;
11204       case ISD::SETUGE:
11205         // Converting this to a min would handle both negative zeros and NaNs
11206         // incorrectly, but we can swap the operands to fix both.
11207         std::swap(LHS, RHS);
11208       case ISD::SETOGT:
11209       case ISD::SETGT:
11210       case ISD::SETGE:
11211         Opcode = X86ISD::FMIN;
11212         break;
11213
11214       case ISD::SETULT:
11215         // Converting this to a max would handle NaNs incorrectly.
11216         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11217           break;
11218         Opcode = X86ISD::FMAX;
11219         break;
11220       case ISD::SETOLE:
11221         // Converting this to a max would handle comparisons between positive
11222         // and negative zero incorrectly, and swapping the operands would
11223         // cause it to handle NaNs incorrectly.
11224         if (!UnsafeFPMath &&
11225             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11226           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11227             break;
11228           std::swap(LHS, RHS);
11229         }
11230         Opcode = X86ISD::FMAX;
11231         break;
11232       case ISD::SETULE:
11233         // Converting this to a max would handle both negative zeros and NaNs
11234         // incorrectly, but we can swap the operands to fix both.
11235         std::swap(LHS, RHS);
11236       case ISD::SETOLT:
11237       case ISD::SETLT:
11238       case ISD::SETLE:
11239         Opcode = X86ISD::FMAX;
11240         break;
11241       }
11242     }
11243
11244     if (Opcode)
11245       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11246   }
11247
11248   // If this is a select between two integer constants, try to do some
11249   // optimizations.
11250   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11251     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11252       // Don't do this for crazy integer types.
11253       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11254         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11255         // so that TrueC (the true value) is larger than FalseC.
11256         bool NeedsCondInvert = false;
11257
11258         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11259             // Efficiently invertible.
11260             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11261              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11262               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11263           NeedsCondInvert = true;
11264           std::swap(TrueC, FalseC);
11265         }
11266
11267         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11268         if (FalseC->getAPIntValue() == 0 &&
11269             TrueC->getAPIntValue().isPowerOf2()) {
11270           if (NeedsCondInvert) // Invert the condition if needed.
11271             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11272                                DAG.getConstant(1, Cond.getValueType()));
11273
11274           // Zero extend the condition if needed.
11275           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11276
11277           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11278           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11279                              DAG.getConstant(ShAmt, MVT::i8));
11280         }
11281
11282         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11283         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11284           if (NeedsCondInvert) // Invert the condition if needed.
11285             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11286                                DAG.getConstant(1, Cond.getValueType()));
11287
11288           // Zero extend the condition if needed.
11289           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11290                              FalseC->getValueType(0), Cond);
11291           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11292                              SDValue(FalseC, 0));
11293         }
11294
11295         // Optimize cases that will turn into an LEA instruction.  This requires
11296         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11297         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11298           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11299           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11300
11301           bool isFastMultiplier = false;
11302           if (Diff < 10) {
11303             switch ((unsigned char)Diff) {
11304               default: break;
11305               case 1:  // result = add base, cond
11306               case 2:  // result = lea base(    , cond*2)
11307               case 3:  // result = lea base(cond, cond*2)
11308               case 4:  // result = lea base(    , cond*4)
11309               case 5:  // result = lea base(cond, cond*4)
11310               case 8:  // result = lea base(    , cond*8)
11311               case 9:  // result = lea base(cond, cond*8)
11312                 isFastMultiplier = true;
11313                 break;
11314             }
11315           }
11316
11317           if (isFastMultiplier) {
11318             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11319             if (NeedsCondInvert) // Invert the condition if needed.
11320               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11321                                  DAG.getConstant(1, Cond.getValueType()));
11322
11323             // Zero extend the condition if needed.
11324             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11325                                Cond);
11326             // Scale the condition by the difference.
11327             if (Diff != 1)
11328               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11329                                  DAG.getConstant(Diff, Cond.getValueType()));
11330
11331             // Add the base if non-zero.
11332             if (FalseC->getAPIntValue() != 0)
11333               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11334                                  SDValue(FalseC, 0));
11335             return Cond;
11336           }
11337         }
11338       }
11339   }
11340
11341   return SDValue();
11342 }
11343
11344 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11345 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11346                                   TargetLowering::DAGCombinerInfo &DCI) {
11347   DebugLoc DL = N->getDebugLoc();
11348
11349   // If the flag operand isn't dead, don't touch this CMOV.
11350   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11351     return SDValue();
11352
11353   SDValue FalseOp = N->getOperand(0);
11354   SDValue TrueOp = N->getOperand(1);
11355   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11356   SDValue Cond = N->getOperand(3);
11357   if (CC == X86::COND_E || CC == X86::COND_NE) {
11358     switch (Cond.getOpcode()) {
11359     default: break;
11360     case X86ISD::BSR:
11361     case X86ISD::BSF:
11362       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
11363       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
11364         return (CC == X86::COND_E) ? FalseOp : TrueOp;
11365     }
11366   }
11367
11368   // If this is a select between two integer constants, try to do some
11369   // optimizations.  Note that the operands are ordered the opposite of SELECT
11370   // operands.
11371   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
11372     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
11373       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11374       // larger than FalseC (the false value).
11375       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11376         CC = X86::GetOppositeBranchCondition(CC);
11377         std::swap(TrueC, FalseC);
11378       }
11379
11380       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11381       // This is efficient for any integer data type (including i8/i16) and
11382       // shift amount.
11383       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11384         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11385                            DAG.getConstant(CC, MVT::i8), Cond);
11386
11387         // Zero extend the condition if needed.
11388         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11389
11390         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11391         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11392                            DAG.getConstant(ShAmt, MVT::i8));
11393         if (N->getNumValues() == 2)  // Dead flag value?
11394           return DCI.CombineTo(N, Cond, SDValue());
11395         return Cond;
11396       }
11397
11398       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11399       // for any integer data type, including i8/i16.
11400       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11401         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11402                            DAG.getConstant(CC, MVT::i8), Cond);
11403
11404         // Zero extend the condition if needed.
11405         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11406                            FalseC->getValueType(0), Cond);
11407         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11408                            SDValue(FalseC, 0));
11409
11410         if (N->getNumValues() == 2)  // Dead flag value?
11411           return DCI.CombineTo(N, Cond, SDValue());
11412         return Cond;
11413       }
11414
11415       // Optimize cases that will turn into an LEA instruction.  This requires
11416       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11417       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11418         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11419         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11420
11421         bool isFastMultiplier = false;
11422         if (Diff < 10) {
11423           switch ((unsigned char)Diff) {
11424           default: break;
11425           case 1:  // result = add base, cond
11426           case 2:  // result = lea base(    , cond*2)
11427           case 3:  // result = lea base(cond, cond*2)
11428           case 4:  // result = lea base(    , cond*4)
11429           case 5:  // result = lea base(cond, cond*4)
11430           case 8:  // result = lea base(    , cond*8)
11431           case 9:  // result = lea base(cond, cond*8)
11432             isFastMultiplier = true;
11433             break;
11434           }
11435         }
11436
11437         if (isFastMultiplier) {
11438           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11439           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11440                              DAG.getConstant(CC, MVT::i8), Cond);
11441           // Zero extend the condition if needed.
11442           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11443                              Cond);
11444           // Scale the condition by the difference.
11445           if (Diff != 1)
11446             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11447                                DAG.getConstant(Diff, Cond.getValueType()));
11448
11449           // Add the base if non-zero.
11450           if (FalseC->getAPIntValue() != 0)
11451             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11452                                SDValue(FalseC, 0));
11453           if (N->getNumValues() == 2)  // Dead flag value?
11454             return DCI.CombineTo(N, Cond, SDValue());
11455           return Cond;
11456         }
11457       }
11458     }
11459   }
11460   return SDValue();
11461 }
11462
11463
11464 /// PerformMulCombine - Optimize a single multiply with constant into two
11465 /// in order to implement it with two cheaper instructions, e.g.
11466 /// LEA + SHL, LEA + LEA.
11467 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11468                                  TargetLowering::DAGCombinerInfo &DCI) {
11469   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11470     return SDValue();
11471
11472   EVT VT = N->getValueType(0);
11473   if (VT != MVT::i64)
11474     return SDValue();
11475
11476   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11477   if (!C)
11478     return SDValue();
11479   uint64_t MulAmt = C->getZExtValue();
11480   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11481     return SDValue();
11482
11483   uint64_t MulAmt1 = 0;
11484   uint64_t MulAmt2 = 0;
11485   if ((MulAmt % 9) == 0) {
11486     MulAmt1 = 9;
11487     MulAmt2 = MulAmt / 9;
11488   } else if ((MulAmt % 5) == 0) {
11489     MulAmt1 = 5;
11490     MulAmt2 = MulAmt / 5;
11491   } else if ((MulAmt % 3) == 0) {
11492     MulAmt1 = 3;
11493     MulAmt2 = MulAmt / 3;
11494   }
11495   if (MulAmt2 &&
11496       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11497     DebugLoc DL = N->getDebugLoc();
11498
11499     if (isPowerOf2_64(MulAmt2) &&
11500         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11501       // If second multiplifer is pow2, issue it first. We want the multiply by
11502       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11503       // is an add.
11504       std::swap(MulAmt1, MulAmt2);
11505
11506     SDValue NewMul;
11507     if (isPowerOf2_64(MulAmt1))
11508       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11509                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11510     else
11511       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11512                            DAG.getConstant(MulAmt1, VT));
11513
11514     if (isPowerOf2_64(MulAmt2))
11515       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11516                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11517     else
11518       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11519                            DAG.getConstant(MulAmt2, VT));
11520
11521     // Do not add new nodes to DAG combiner worklist.
11522     DCI.CombineTo(N, NewMul, false);
11523   }
11524   return SDValue();
11525 }
11526
11527 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11528   SDValue N0 = N->getOperand(0);
11529   SDValue N1 = N->getOperand(1);
11530   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11531   EVT VT = N0.getValueType();
11532
11533   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11534   // since the result of setcc_c is all zero's or all ones.
11535   if (N1C && N0.getOpcode() == ISD::AND &&
11536       N0.getOperand(1).getOpcode() == ISD::Constant) {
11537     SDValue N00 = N0.getOperand(0);
11538     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11539         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11540           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11541          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11542       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11543       APInt ShAmt = N1C->getAPIntValue();
11544       Mask = Mask.shl(ShAmt);
11545       if (Mask != 0)
11546         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11547                            N00, DAG.getConstant(Mask, VT));
11548     }
11549   }
11550
11551   return SDValue();
11552 }
11553
11554 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11555 ///                       when possible.
11556 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11557                                    const X86Subtarget *Subtarget) {
11558   EVT VT = N->getValueType(0);
11559   if (!VT.isVector() && VT.isInteger() &&
11560       N->getOpcode() == ISD::SHL)
11561     return PerformSHLCombine(N, DAG);
11562
11563   // On X86 with SSE2 support, we can transform this to a vector shift if
11564   // all elements are shifted by the same amount.  We can't do this in legalize
11565   // because the a constant vector is typically transformed to a constant pool
11566   // so we have no knowledge of the shift amount.
11567   if (!Subtarget->hasSSE2())
11568     return SDValue();
11569
11570   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11571     return SDValue();
11572
11573   SDValue ShAmtOp = N->getOperand(1);
11574   EVT EltVT = VT.getVectorElementType();
11575   DebugLoc DL = N->getDebugLoc();
11576   SDValue BaseShAmt = SDValue();
11577   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11578     unsigned NumElts = VT.getVectorNumElements();
11579     unsigned i = 0;
11580     for (; i != NumElts; ++i) {
11581       SDValue Arg = ShAmtOp.getOperand(i);
11582       if (Arg.getOpcode() == ISD::UNDEF) continue;
11583       BaseShAmt = Arg;
11584       break;
11585     }
11586     for (; i != NumElts; ++i) {
11587       SDValue Arg = ShAmtOp.getOperand(i);
11588       if (Arg.getOpcode() == ISD::UNDEF) continue;
11589       if (Arg != BaseShAmt) {
11590         return SDValue();
11591       }
11592     }
11593   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11594              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11595     SDValue InVec = ShAmtOp.getOperand(0);
11596     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11597       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11598       unsigned i = 0;
11599       for (; i != NumElts; ++i) {
11600         SDValue Arg = InVec.getOperand(i);
11601         if (Arg.getOpcode() == ISD::UNDEF) continue;
11602         BaseShAmt = Arg;
11603         break;
11604       }
11605     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11606        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11607          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11608          if (C->getZExtValue() == SplatIdx)
11609            BaseShAmt = InVec.getOperand(1);
11610        }
11611     }
11612     if (BaseShAmt.getNode() == 0)
11613       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11614                               DAG.getIntPtrConstant(0));
11615   } else
11616     return SDValue();
11617
11618   // The shift amount is an i32.
11619   if (EltVT.bitsGT(MVT::i32))
11620     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11621   else if (EltVT.bitsLT(MVT::i32))
11622     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11623
11624   // The shift amount is identical so we can do a vector shift.
11625   SDValue  ValOp = N->getOperand(0);
11626   switch (N->getOpcode()) {
11627   default:
11628     llvm_unreachable("Unknown shift opcode!");
11629     break;
11630   case ISD::SHL:
11631     if (VT == MVT::v2i64)
11632       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11633                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11634                          ValOp, BaseShAmt);
11635     if (VT == MVT::v4i32)
11636       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11637                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11638                          ValOp, BaseShAmt);
11639     if (VT == MVT::v8i16)
11640       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11641                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11642                          ValOp, BaseShAmt);
11643     break;
11644   case ISD::SRA:
11645     if (VT == MVT::v4i32)
11646       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11647                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11648                          ValOp, BaseShAmt);
11649     if (VT == MVT::v8i16)
11650       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11651                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11652                          ValOp, BaseShAmt);
11653     break;
11654   case ISD::SRL:
11655     if (VT == MVT::v2i64)
11656       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11657                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11658                          ValOp, BaseShAmt);
11659     if (VT == MVT::v4i32)
11660       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11661                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11662                          ValOp, BaseShAmt);
11663     if (VT ==  MVT::v8i16)
11664       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11665                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11666                          ValOp, BaseShAmt);
11667     break;
11668   }
11669   return SDValue();
11670 }
11671
11672
11673 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
11674 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
11675 // and friends.  Likewise for OR -> CMPNEQSS.
11676 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
11677                             TargetLowering::DAGCombinerInfo &DCI,
11678                             const X86Subtarget *Subtarget) {
11679   unsigned opcode;
11680
11681   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
11682   // we're requiring SSE2 for both.
11683   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
11684     SDValue N0 = N->getOperand(0);
11685     SDValue N1 = N->getOperand(1);
11686     SDValue CMP    = N0->getOperand(1);
11687     SDValue CMP0   = CMP->getOperand(0);
11688     SDValue CMP1   = CMP->getOperand(1);
11689     EVT     VT     = CMP0.getValueType();
11690     DebugLoc DL    = N->getDebugLoc();
11691
11692     if (VT == MVT::f32 || VT == MVT::f64) {
11693       bool ExpectingFlags = false;
11694       // Check for any users that want flags:
11695       for (SDNode::use_iterator UI = N->use_begin(),
11696              UE = N->use_end();
11697            !ExpectingFlags && UI != UE; ++UI)
11698         switch (UI->getOpcode()) {
11699         default:
11700         case ISD::BR_CC:
11701         case ISD::BRCOND:
11702         case ISD::SELECT:
11703           ExpectingFlags = true;
11704           break;
11705         case ISD::CopyToReg:
11706         case ISD::SIGN_EXTEND:
11707         case ISD::ZERO_EXTEND:
11708         case ISD::ANY_EXTEND:
11709           break;
11710         }
11711
11712       if (!ExpectingFlags) {
11713         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
11714         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
11715
11716         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
11717           X86::CondCode tmp = cc0;
11718           cc0 = cc1;
11719           cc1 = tmp;
11720         }
11721
11722         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
11723             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
11724           bool is64BitFP = (CMP0.getValueType() == MVT::f64);
11725           X86ISD::NodeType NTOperator = is64BitFP ?
11726             X86ISD::FSETCCsd : X86ISD::FSETCCss;
11727           // FIXME: need symbolic constants for these magic numbers.
11728           // See X86ATTInstPrinter.cpp:printSSECC().
11729           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
11730           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP0, CMP1,
11731                                               DAG.getConstant(x86cc, MVT::i8));
11732           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
11733                                               OnesOrZeroesF);
11734           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
11735                                       DAG.getConstant(1, MVT::i32));
11736           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
11737           return OneBitOfTruth;
11738         }
11739       }
11740     }
11741   }
11742   return SDValue();
11743 }
11744
11745 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11746                                  TargetLowering::DAGCombinerInfo &DCI,
11747                                  const X86Subtarget *Subtarget) {
11748   if (DCI.isBeforeLegalizeOps())
11749     return SDValue();
11750
11751   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11752   if (R.getNode())
11753     return R;
11754
11755   // Want to form PANDN nodes, in the hopes of then easily combining them with
11756   // OR and AND nodes to form PBLEND/PSIGN.
11757   EVT VT = N->getValueType(0);
11758   if (VT != MVT::v2i64)
11759     return SDValue();
11760
11761   SDValue N0 = N->getOperand(0);
11762   SDValue N1 = N->getOperand(1);
11763   DebugLoc DL = N->getDebugLoc();
11764
11765   // Check LHS for vnot
11766   if (N0.getOpcode() == ISD::XOR &&
11767       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11768     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11769
11770   // Check RHS for vnot
11771   if (N1.getOpcode() == ISD::XOR &&
11772       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11773     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11774
11775   return SDValue();
11776 }
11777
11778 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11779                                 TargetLowering::DAGCombinerInfo &DCI,
11780                                 const X86Subtarget *Subtarget) {
11781   if (DCI.isBeforeLegalizeOps())
11782     return SDValue();
11783
11784   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
11785   if (R.getNode())
11786     return R;
11787
11788   EVT VT = N->getValueType(0);
11789   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11790     return SDValue();
11791
11792   SDValue N0 = N->getOperand(0);
11793   SDValue N1 = N->getOperand(1);
11794
11795   // look for psign/blend
11796   if (Subtarget->hasSSSE3()) {
11797     if (VT == MVT::v2i64) {
11798       // Canonicalize pandn to RHS
11799       if (N0.getOpcode() == X86ISD::PANDN)
11800         std::swap(N0, N1);
11801       // or (and (m, x), (pandn m, y))
11802       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11803         SDValue Mask = N1.getOperand(0);
11804         SDValue X    = N1.getOperand(1);
11805         SDValue Y;
11806         if (N0.getOperand(0) == Mask)
11807           Y = N0.getOperand(1);
11808         if (N0.getOperand(1) == Mask)
11809           Y = N0.getOperand(0);
11810
11811         // Check to see if the mask appeared in both the AND and PANDN and
11812         if (!Y.getNode())
11813           return SDValue();
11814
11815         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11816         if (Mask.getOpcode() != ISD::BITCAST ||
11817             X.getOpcode() != ISD::BITCAST ||
11818             Y.getOpcode() != ISD::BITCAST)
11819           return SDValue();
11820
11821         // Look through mask bitcast.
11822         Mask = Mask.getOperand(0);
11823         EVT MaskVT = Mask.getValueType();
11824
11825         // Validate that the Mask operand is a vector sra node.  The sra node
11826         // will be an intrinsic.
11827         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11828           return SDValue();
11829
11830         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11831         // there is no psrai.b
11832         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11833         case Intrinsic::x86_sse2_psrai_w:
11834         case Intrinsic::x86_sse2_psrai_d:
11835           break;
11836         default: return SDValue();
11837         }
11838
11839         // Check that the SRA is all signbits.
11840         SDValue SraC = Mask.getOperand(2);
11841         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11842         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11843         if ((SraAmt + 1) != EltBits)
11844           return SDValue();
11845
11846         DebugLoc DL = N->getDebugLoc();
11847
11848         // Now we know we at least have a plendvb with the mask val.  See if
11849         // we can form a psignb/w/d.
11850         // psign = x.type == y.type == mask.type && y = sub(0, x);
11851         X = X.getOperand(0);
11852         Y = Y.getOperand(0);
11853         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11854             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11855             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11856           unsigned Opc = 0;
11857           switch (EltBits) {
11858           case 8: Opc = X86ISD::PSIGNB; break;
11859           case 16: Opc = X86ISD::PSIGNW; break;
11860           case 32: Opc = X86ISD::PSIGND; break;
11861           default: break;
11862           }
11863           if (Opc) {
11864             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11865             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11866           }
11867         }
11868         // PBLENDVB only available on SSE 4.1
11869         if (!Subtarget->hasSSE41())
11870           return SDValue();
11871
11872         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11873         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11874         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11875         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11876         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11877       }
11878     }
11879   }
11880
11881   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11882   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11883     std::swap(N0, N1);
11884   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11885     return SDValue();
11886   if (!N0.hasOneUse() || !N1.hasOneUse())
11887     return SDValue();
11888
11889   SDValue ShAmt0 = N0.getOperand(1);
11890   if (ShAmt0.getValueType() != MVT::i8)
11891     return SDValue();
11892   SDValue ShAmt1 = N1.getOperand(1);
11893   if (ShAmt1.getValueType() != MVT::i8)
11894     return SDValue();
11895   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11896     ShAmt0 = ShAmt0.getOperand(0);
11897   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11898     ShAmt1 = ShAmt1.getOperand(0);
11899
11900   DebugLoc DL = N->getDebugLoc();
11901   unsigned Opc = X86ISD::SHLD;
11902   SDValue Op0 = N0.getOperand(0);
11903   SDValue Op1 = N1.getOperand(0);
11904   if (ShAmt0.getOpcode() == ISD::SUB) {
11905     Opc = X86ISD::SHRD;
11906     std::swap(Op0, Op1);
11907     std::swap(ShAmt0, ShAmt1);
11908   }
11909
11910   unsigned Bits = VT.getSizeInBits();
11911   if (ShAmt1.getOpcode() == ISD::SUB) {
11912     SDValue Sum = ShAmt1.getOperand(0);
11913     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11914       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11915       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11916         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11917       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11918         return DAG.getNode(Opc, DL, VT,
11919                            Op0, Op1,
11920                            DAG.getNode(ISD::TRUNCATE, DL,
11921                                        MVT::i8, ShAmt0));
11922     }
11923   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11924     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11925     if (ShAmt0C &&
11926         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11927       return DAG.getNode(Opc, DL, VT,
11928                          N0.getOperand(0), N1.getOperand(0),
11929                          DAG.getNode(ISD::TRUNCATE, DL,
11930                                        MVT::i8, ShAmt0));
11931   }
11932
11933   return SDValue();
11934 }
11935
11936 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11937 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11938                                    const X86Subtarget *Subtarget) {
11939   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11940   // the FP state in cases where an emms may be missing.
11941   // A preferable solution to the general problem is to figure out the right
11942   // places to insert EMMS.  This qualifies as a quick hack.
11943
11944   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11945   StoreSDNode *St = cast<StoreSDNode>(N);
11946   EVT VT = St->getValue().getValueType();
11947   if (VT.getSizeInBits() != 64)
11948     return SDValue();
11949
11950   const Function *F = DAG.getMachineFunction().getFunction();
11951   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11952   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11953     && Subtarget->hasSSE2();
11954   if ((VT.isVector() ||
11955        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11956       isa<LoadSDNode>(St->getValue()) &&
11957       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11958       St->getChain().hasOneUse() && !St->isVolatile()) {
11959     SDNode* LdVal = St->getValue().getNode();
11960     LoadSDNode *Ld = 0;
11961     int TokenFactorIndex = -1;
11962     SmallVector<SDValue, 8> Ops;
11963     SDNode* ChainVal = St->getChain().getNode();
11964     // Must be a store of a load.  We currently handle two cases:  the load
11965     // is a direct child, and it's under an intervening TokenFactor.  It is
11966     // possible to dig deeper under nested TokenFactors.
11967     if (ChainVal == LdVal)
11968       Ld = cast<LoadSDNode>(St->getChain());
11969     else if (St->getValue().hasOneUse() &&
11970              ChainVal->getOpcode() == ISD::TokenFactor) {
11971       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11972         if (ChainVal->getOperand(i).getNode() == LdVal) {
11973           TokenFactorIndex = i;
11974           Ld = cast<LoadSDNode>(St->getValue());
11975         } else
11976           Ops.push_back(ChainVal->getOperand(i));
11977       }
11978     }
11979
11980     if (!Ld || !ISD::isNormalLoad(Ld))
11981       return SDValue();
11982
11983     // If this is not the MMX case, i.e. we are just turning i64 load/store
11984     // into f64 load/store, avoid the transformation if there are multiple
11985     // uses of the loaded value.
11986     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11987       return SDValue();
11988
11989     DebugLoc LdDL = Ld->getDebugLoc();
11990     DebugLoc StDL = N->getDebugLoc();
11991     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11992     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11993     // pair instead.
11994     if (Subtarget->is64Bit() || F64IsLegal) {
11995       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11996       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11997                                   Ld->getPointerInfo(), Ld->isVolatile(),
11998                                   Ld->isNonTemporal(), Ld->getAlignment());
11999       SDValue NewChain = NewLd.getValue(1);
12000       if (TokenFactorIndex != -1) {
12001         Ops.push_back(NewChain);
12002         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12003                                Ops.size());
12004       }
12005       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
12006                           St->getPointerInfo(),
12007                           St->isVolatile(), St->isNonTemporal(),
12008                           St->getAlignment());
12009     }
12010
12011     // Otherwise, lower to two pairs of 32-bit loads / stores.
12012     SDValue LoAddr = Ld->getBasePtr();
12013     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
12014                                  DAG.getConstant(4, MVT::i32));
12015
12016     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
12017                                Ld->getPointerInfo(),
12018                                Ld->isVolatile(), Ld->isNonTemporal(),
12019                                Ld->getAlignment());
12020     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
12021                                Ld->getPointerInfo().getWithOffset(4),
12022                                Ld->isVolatile(), Ld->isNonTemporal(),
12023                                MinAlign(Ld->getAlignment(), 4));
12024
12025     SDValue NewChain = LoLd.getValue(1);
12026     if (TokenFactorIndex != -1) {
12027       Ops.push_back(LoLd);
12028       Ops.push_back(HiLd);
12029       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
12030                              Ops.size());
12031     }
12032
12033     LoAddr = St->getBasePtr();
12034     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
12035                          DAG.getConstant(4, MVT::i32));
12036
12037     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
12038                                 St->getPointerInfo(),
12039                                 St->isVolatile(), St->isNonTemporal(),
12040                                 St->getAlignment());
12041     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
12042                                 St->getPointerInfo().getWithOffset(4),
12043                                 St->isVolatile(),
12044                                 St->isNonTemporal(),
12045                                 MinAlign(St->getAlignment(), 4));
12046     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
12047   }
12048   return SDValue();
12049 }
12050
12051 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
12052 /// X86ISD::FXOR nodes.
12053 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
12054   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
12055   // F[X]OR(0.0, x) -> x
12056   // F[X]OR(x, 0.0) -> x
12057   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12058     if (C->getValueAPF().isPosZero())
12059       return N->getOperand(1);
12060   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12061     if (C->getValueAPF().isPosZero())
12062       return N->getOperand(0);
12063   return SDValue();
12064 }
12065
12066 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
12067 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
12068   // FAND(0.0, x) -> 0.0
12069   // FAND(x, 0.0) -> 0.0
12070   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
12071     if (C->getValueAPF().isPosZero())
12072       return N->getOperand(0);
12073   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
12074     if (C->getValueAPF().isPosZero())
12075       return N->getOperand(1);
12076   return SDValue();
12077 }
12078
12079 static SDValue PerformBTCombine(SDNode *N,
12080                                 SelectionDAG &DAG,
12081                                 TargetLowering::DAGCombinerInfo &DCI) {
12082   // BT ignores high bits in the bit index operand.
12083   SDValue Op1 = N->getOperand(1);
12084   if (Op1.hasOneUse()) {
12085     unsigned BitWidth = Op1.getValueSizeInBits();
12086     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
12087     APInt KnownZero, KnownOne;
12088     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12089                                           !DCI.isBeforeLegalizeOps());
12090     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12091     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
12092         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
12093       DCI.CommitTargetLoweringOpt(TLO);
12094   }
12095   return SDValue();
12096 }
12097
12098 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
12099   SDValue Op = N->getOperand(0);
12100   if (Op.getOpcode() == ISD::BITCAST)
12101     Op = Op.getOperand(0);
12102   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
12103   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
12104       VT.getVectorElementType().getSizeInBits() ==
12105       OpVT.getVectorElementType().getSizeInBits()) {
12106     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
12107   }
12108   return SDValue();
12109 }
12110
12111 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
12112   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
12113   //           (and (i32 x86isd::setcc_carry), 1)
12114   // This eliminates the zext. This transformation is necessary because
12115   // ISD::SETCC is always legalized to i8.
12116   DebugLoc dl = N->getDebugLoc();
12117   SDValue N0 = N->getOperand(0);
12118   EVT VT = N->getValueType(0);
12119   if (N0.getOpcode() == ISD::AND &&
12120       N0.hasOneUse() &&
12121       N0.getOperand(0).hasOneUse()) {
12122     SDValue N00 = N0.getOperand(0);
12123     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
12124       return SDValue();
12125     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
12126     if (!C || C->getZExtValue() != 1)
12127       return SDValue();
12128     return DAG.getNode(ISD::AND, dl, VT,
12129                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
12130                                    N00.getOperand(0), N00.getOperand(1)),
12131                        DAG.getConstant(1, VT));
12132   }
12133
12134   return SDValue();
12135 }
12136
12137 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
12138 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
12139   unsigned X86CC = N->getConstantOperandVal(0);
12140   SDValue EFLAG = N->getOperand(1);
12141   DebugLoc DL = N->getDebugLoc();
12142
12143   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
12144   // a zext and produces an all-ones bit which is more useful than 0/1 in some
12145   // cases.
12146   if (X86CC == X86::COND_B)
12147     return DAG.getNode(ISD::AND, DL, MVT::i8,
12148                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
12149                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
12150                        DAG.getConstant(1, MVT::i8));
12151
12152   return SDValue();
12153 }
12154
12155 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
12156 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
12157                                  X86TargetLowering::DAGCombinerInfo &DCI) {
12158   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
12159   // the result is either zero or one (depending on the input carry bit).
12160   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
12161   if (X86::isZeroNode(N->getOperand(0)) &&
12162       X86::isZeroNode(N->getOperand(1)) &&
12163       // We don't have a good way to replace an EFLAGS use, so only do this when
12164       // dead right now.
12165       SDValue(N, 1).use_empty()) {
12166     DebugLoc DL = N->getDebugLoc();
12167     EVT VT = N->getValueType(0);
12168     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
12169     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
12170                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
12171                                            DAG.getConstant(X86::COND_B,MVT::i8),
12172                                            N->getOperand(2)),
12173                                DAG.getConstant(1, VT));
12174     return DCI.CombineTo(N, Res1, CarryOut);
12175   }
12176
12177   return SDValue();
12178 }
12179
12180 // fold (add Y, (sete  X, 0)) -> adc  0, Y
12181 //      (add Y, (setne X, 0)) -> sbb -1, Y
12182 //      (sub (sete  X, 0), Y) -> sbb  0, Y
12183 //      (sub (setne X, 0), Y) -> adc -1, Y
12184 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
12185   DebugLoc DL = N->getDebugLoc();
12186
12187   // Look through ZExts.
12188   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
12189   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
12190     return SDValue();
12191
12192   SDValue SetCC = Ext.getOperand(0);
12193   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
12194     return SDValue();
12195
12196   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
12197   if (CC != X86::COND_E && CC != X86::COND_NE)
12198     return SDValue();
12199
12200   SDValue Cmp = SetCC.getOperand(1);
12201   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
12202       !X86::isZeroNode(Cmp.getOperand(1)) ||
12203       !Cmp.getOperand(0).getValueType().isInteger())
12204     return SDValue();
12205
12206   SDValue CmpOp0 = Cmp.getOperand(0);
12207   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
12208                                DAG.getConstant(1, CmpOp0.getValueType()));
12209
12210   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
12211   if (CC == X86::COND_NE)
12212     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
12213                        DL, OtherVal.getValueType(), OtherVal,
12214                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
12215   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
12216                      DL, OtherVal.getValueType(), OtherVal,
12217                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
12218 }
12219
12220 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
12221                                              DAGCombinerInfo &DCI) const {
12222   SelectionDAG &DAG = DCI.DAG;
12223   switch (N->getOpcode()) {
12224   default: break;
12225   case ISD::EXTRACT_VECTOR_ELT:
12226     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
12227   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
12228   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
12229   case ISD::ADD:
12230   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
12231   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
12232   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
12233   case ISD::SHL:
12234   case ISD::SRA:
12235   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
12236   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
12237   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
12238   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
12239   case X86ISD::FXOR:
12240   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
12241   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
12242   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
12243   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
12244   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
12245   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
12246   case X86ISD::SHUFPS:      // Handle all target specific shuffles
12247   case X86ISD::SHUFPD:
12248   case X86ISD::PALIGN:
12249   case X86ISD::PUNPCKHBW:
12250   case X86ISD::PUNPCKHWD:
12251   case X86ISD::PUNPCKHDQ:
12252   case X86ISD::PUNPCKHQDQ:
12253   case X86ISD::UNPCKHPS:
12254   case X86ISD::UNPCKHPD:
12255   case X86ISD::PUNPCKLBW:
12256   case X86ISD::PUNPCKLWD:
12257   case X86ISD::PUNPCKLDQ:
12258   case X86ISD::PUNPCKLQDQ:
12259   case X86ISD::UNPCKLPS:
12260   case X86ISD::UNPCKLPD:
12261   case X86ISD::VUNPCKLPS:
12262   case X86ISD::VUNPCKLPD:
12263   case X86ISD::VUNPCKLPSY:
12264   case X86ISD::VUNPCKLPDY:
12265   case X86ISD::MOVHLPS:
12266   case X86ISD::MOVLHPS:
12267   case X86ISD::PSHUFD:
12268   case X86ISD::PSHUFHW:
12269   case X86ISD::PSHUFLW:
12270   case X86ISD::MOVSS:
12271   case X86ISD::MOVSD:
12272   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
12273   }
12274
12275   return SDValue();
12276 }
12277
12278 /// isTypeDesirableForOp - Return true if the target has native support for
12279 /// the specified value type and it is 'desirable' to use the type for the
12280 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
12281 /// instruction encodings are longer and some i16 instructions are slow.
12282 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
12283   if (!isTypeLegal(VT))
12284     return false;
12285   if (VT != MVT::i16)
12286     return true;
12287
12288   switch (Opc) {
12289   default:
12290     return true;
12291   case ISD::LOAD:
12292   case ISD::SIGN_EXTEND:
12293   case ISD::ZERO_EXTEND:
12294   case ISD::ANY_EXTEND:
12295   case ISD::SHL:
12296   case ISD::SRL:
12297   case ISD::SUB:
12298   case ISD::ADD:
12299   case ISD::MUL:
12300   case ISD::AND:
12301   case ISD::OR:
12302   case ISD::XOR:
12303     return false;
12304   }
12305 }
12306
12307 /// IsDesirableToPromoteOp - This method query the target whether it is
12308 /// beneficial for dag combiner to promote the specified node. If true, it
12309 /// should return the desired promotion type by reference.
12310 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12311   EVT VT = Op.getValueType();
12312   if (VT != MVT::i16)
12313     return false;
12314
12315   bool Promote = false;
12316   bool Commute = false;
12317   switch (Op.getOpcode()) {
12318   default: break;
12319   case ISD::LOAD: {
12320     LoadSDNode *LD = cast<LoadSDNode>(Op);
12321     // If the non-extending load has a single use and it's not live out, then it
12322     // might be folded.
12323     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12324                                                      Op.hasOneUse()*/) {
12325       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12326              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12327         // The only case where we'd want to promote LOAD (rather then it being
12328         // promoted as an operand is when it's only use is liveout.
12329         if (UI->getOpcode() != ISD::CopyToReg)
12330           return false;
12331       }
12332     }
12333     Promote = true;
12334     break;
12335   }
12336   case ISD::SIGN_EXTEND:
12337   case ISD::ZERO_EXTEND:
12338   case ISD::ANY_EXTEND:
12339     Promote = true;
12340     break;
12341   case ISD::SHL:
12342   case ISD::SRL: {
12343     SDValue N0 = Op.getOperand(0);
12344     // Look out for (store (shl (load), x)).
12345     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12346       return false;
12347     Promote = true;
12348     break;
12349   }
12350   case ISD::ADD:
12351   case ISD::MUL:
12352   case ISD::AND:
12353   case ISD::OR:
12354   case ISD::XOR:
12355     Commute = true;
12356     // fallthrough
12357   case ISD::SUB: {
12358     SDValue N0 = Op.getOperand(0);
12359     SDValue N1 = Op.getOperand(1);
12360     if (!Commute && MayFoldLoad(N1))
12361       return false;
12362     // Avoid disabling potential load folding opportunities.
12363     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12364       return false;
12365     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12366       return false;
12367     Promote = true;
12368   }
12369   }
12370
12371   PVT = MVT::i32;
12372   return Promote;
12373 }
12374
12375 //===----------------------------------------------------------------------===//
12376 //                           X86 Inline Assembly Support
12377 //===----------------------------------------------------------------------===//
12378
12379 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12380   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12381
12382   std::string AsmStr = IA->getAsmString();
12383
12384   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12385   SmallVector<StringRef, 4> AsmPieces;
12386   SplitString(AsmStr, AsmPieces, ";\n");
12387
12388   switch (AsmPieces.size()) {
12389   default: return false;
12390   case 1:
12391     AsmStr = AsmPieces[0];
12392     AsmPieces.clear();
12393     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12394
12395     // FIXME: this should verify that we are targeting a 486 or better.  If not,
12396     // we will turn this bswap into something that will be lowered to logical ops
12397     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12398     // so don't worry about this.
12399     // bswap $0
12400     if (AsmPieces.size() == 2 &&
12401         (AsmPieces[0] == "bswap" ||
12402          AsmPieces[0] == "bswapq" ||
12403          AsmPieces[0] == "bswapl") &&
12404         (AsmPieces[1] == "$0" ||
12405          AsmPieces[1] == "${0:q}")) {
12406       // No need to check constraints, nothing other than the equivalent of
12407       // "=r,0" would be valid here.
12408       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12409       if (!Ty || Ty->getBitWidth() % 16 != 0)
12410         return false;
12411       return IntrinsicLowering::LowerToByteSwap(CI);
12412     }
12413     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12414     if (CI->getType()->isIntegerTy(16) &&
12415         AsmPieces.size() == 3 &&
12416         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12417         AsmPieces[1] == "$$8," &&
12418         AsmPieces[2] == "${0:w}" &&
12419         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12420       AsmPieces.clear();
12421       const std::string &ConstraintsStr = IA->getConstraintString();
12422       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12423       std::sort(AsmPieces.begin(), AsmPieces.end());
12424       if (AsmPieces.size() == 4 &&
12425           AsmPieces[0] == "~{cc}" &&
12426           AsmPieces[1] == "~{dirflag}" &&
12427           AsmPieces[2] == "~{flags}" &&
12428           AsmPieces[3] == "~{fpsr}") {
12429         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12430         if (!Ty || Ty->getBitWidth() % 16 != 0)
12431           return false;
12432         return IntrinsicLowering::LowerToByteSwap(CI);
12433       }
12434     }
12435     break;
12436   case 3:
12437     if (CI->getType()->isIntegerTy(32) &&
12438         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12439       SmallVector<StringRef, 4> Words;
12440       SplitString(AsmPieces[0], Words, " \t,");
12441       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12442           Words[2] == "${0:w}") {
12443         Words.clear();
12444         SplitString(AsmPieces[1], Words, " \t,");
12445         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12446             Words[2] == "$0") {
12447           Words.clear();
12448           SplitString(AsmPieces[2], Words, " \t,");
12449           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12450               Words[2] == "${0:w}") {
12451             AsmPieces.clear();
12452             const std::string &ConstraintsStr = IA->getConstraintString();
12453             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12454             std::sort(AsmPieces.begin(), AsmPieces.end());
12455             if (AsmPieces.size() == 4 &&
12456                 AsmPieces[0] == "~{cc}" &&
12457                 AsmPieces[1] == "~{dirflag}" &&
12458                 AsmPieces[2] == "~{flags}" &&
12459                 AsmPieces[3] == "~{fpsr}") {
12460               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12461               if (!Ty || Ty->getBitWidth() % 16 != 0)
12462                 return false;
12463               return IntrinsicLowering::LowerToByteSwap(CI);
12464             }
12465           }
12466         }
12467       }
12468     }
12469
12470     if (CI->getType()->isIntegerTy(64)) {
12471       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12472       if (Constraints.size() >= 2 &&
12473           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12474           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12475         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12476         SmallVector<StringRef, 4> Words;
12477         SplitString(AsmPieces[0], Words, " \t");
12478         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12479           Words.clear();
12480           SplitString(AsmPieces[1], Words, " \t");
12481           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12482             Words.clear();
12483             SplitString(AsmPieces[2], Words, " \t,");
12484             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12485                 Words[2] == "%edx") {
12486               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12487               if (!Ty || Ty->getBitWidth() % 16 != 0)
12488                 return false;
12489               return IntrinsicLowering::LowerToByteSwap(CI);
12490             }
12491           }
12492         }
12493       }
12494     }
12495     break;
12496   }
12497   return false;
12498 }
12499
12500
12501
12502 /// getConstraintType - Given a constraint letter, return the type of
12503 /// constraint it is for this target.
12504 X86TargetLowering::ConstraintType
12505 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12506   if (Constraint.size() == 1) {
12507     switch (Constraint[0]) {
12508     case 'R':
12509     case 'q':
12510     case 'Q':
12511     case 'f':
12512     case 't':
12513     case 'u':
12514     case 'y':
12515     case 'x':
12516     case 'Y':
12517       return C_RegisterClass;
12518     case 'a':
12519     case 'b':
12520     case 'c':
12521     case 'd':
12522     case 'S':
12523     case 'D':
12524     case 'A':
12525       return C_Register;
12526     case 'I':
12527     case 'J':
12528     case 'K':
12529     case 'L':
12530     case 'M':
12531     case 'N':
12532     case 'G':
12533     case 'C':
12534     case 'e':
12535     case 'Z':
12536       return C_Other;
12537     default:
12538       break;
12539     }
12540   }
12541   return TargetLowering::getConstraintType(Constraint);
12542 }
12543
12544 /// Examine constraint type and operand type and determine a weight value.
12545 /// This object must already have been set up with the operand type
12546 /// and the current alternative constraint selected.
12547 TargetLowering::ConstraintWeight
12548   X86TargetLowering::getSingleConstraintMatchWeight(
12549     AsmOperandInfo &info, const char *constraint) const {
12550   ConstraintWeight weight = CW_Invalid;
12551   Value *CallOperandVal = info.CallOperandVal;
12552     // If we don't have a value, we can't do a match,
12553     // but allow it at the lowest weight.
12554   if (CallOperandVal == NULL)
12555     return CW_Default;
12556   const Type *type = CallOperandVal->getType();
12557   // Look at the constraint type.
12558   switch (*constraint) {
12559   default:
12560     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12561   case 'R':
12562   case 'q':
12563   case 'Q':
12564   case 'a':
12565   case 'b':
12566   case 'c':
12567   case 'd':
12568   case 'S':
12569   case 'D':
12570   case 'A':
12571     if (CallOperandVal->getType()->isIntegerTy())
12572       weight = CW_SpecificReg;
12573     break;
12574   case 'f':
12575   case 't':
12576   case 'u':
12577       if (type->isFloatingPointTy())
12578         weight = CW_SpecificReg;
12579       break;
12580   case 'y':
12581       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12582         weight = CW_SpecificReg;
12583       break;
12584   case 'x':
12585   case 'Y':
12586     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12587       weight = CW_Register;
12588     break;
12589   case 'I':
12590     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12591       if (C->getZExtValue() <= 31)
12592         weight = CW_Constant;
12593     }
12594     break;
12595   case 'J':
12596     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12597       if (C->getZExtValue() <= 63)
12598         weight = CW_Constant;
12599     }
12600     break;
12601   case 'K':
12602     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12603       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12604         weight = CW_Constant;
12605     }
12606     break;
12607   case 'L':
12608     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12609       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12610         weight = CW_Constant;
12611     }
12612     break;
12613   case 'M':
12614     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12615       if (C->getZExtValue() <= 3)
12616         weight = CW_Constant;
12617     }
12618     break;
12619   case 'N':
12620     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12621       if (C->getZExtValue() <= 0xff)
12622         weight = CW_Constant;
12623     }
12624     break;
12625   case 'G':
12626   case 'C':
12627     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12628       weight = CW_Constant;
12629     }
12630     break;
12631   case 'e':
12632     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12633       if ((C->getSExtValue() >= -0x80000000LL) &&
12634           (C->getSExtValue() <= 0x7fffffffLL))
12635         weight = CW_Constant;
12636     }
12637     break;
12638   case 'Z':
12639     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12640       if (C->getZExtValue() <= 0xffffffff)
12641         weight = CW_Constant;
12642     }
12643     break;
12644   }
12645   return weight;
12646 }
12647
12648 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12649 /// with another that has more specific requirements based on the type of the
12650 /// corresponding operand.
12651 const char *X86TargetLowering::
12652 LowerXConstraint(EVT ConstraintVT) const {
12653   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12654   // 'f' like normal targets.
12655   if (ConstraintVT.isFloatingPoint()) {
12656     if (Subtarget->hasXMMInt())
12657       return "Y";
12658     if (Subtarget->hasXMM())
12659       return "x";
12660   }
12661
12662   return TargetLowering::LowerXConstraint(ConstraintVT);
12663 }
12664
12665 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12666 /// vector.  If it is invalid, don't add anything to Ops.
12667 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12668                                                      char Constraint,
12669                                                      std::vector<SDValue>&Ops,
12670                                                      SelectionDAG &DAG) const {
12671   SDValue Result(0, 0);
12672
12673   switch (Constraint) {
12674   default: break;
12675   case 'I':
12676     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12677       if (C->getZExtValue() <= 31) {
12678         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12679         break;
12680       }
12681     }
12682     return;
12683   case 'J':
12684     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12685       if (C->getZExtValue() <= 63) {
12686         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12687         break;
12688       }
12689     }
12690     return;
12691   case 'K':
12692     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12693       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12694         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12695         break;
12696       }
12697     }
12698     return;
12699   case 'N':
12700     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12701       if (C->getZExtValue() <= 255) {
12702         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12703         break;
12704       }
12705     }
12706     return;
12707   case 'e': {
12708     // 32-bit signed value
12709     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12710       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12711                                            C->getSExtValue())) {
12712         // Widen to 64 bits here to get it sign extended.
12713         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12714         break;
12715       }
12716     // FIXME gcc accepts some relocatable values here too, but only in certain
12717     // memory models; it's complicated.
12718     }
12719     return;
12720   }
12721   case 'Z': {
12722     // 32-bit unsigned value
12723     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12724       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12725                                            C->getZExtValue())) {
12726         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12727         break;
12728       }
12729     }
12730     // FIXME gcc accepts some relocatable values here too, but only in certain
12731     // memory models; it's complicated.
12732     return;
12733   }
12734   case 'i': {
12735     // Literal immediates are always ok.
12736     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12737       // Widen to 64 bits here to get it sign extended.
12738       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12739       break;
12740     }
12741
12742     // In any sort of PIC mode addresses need to be computed at runtime by
12743     // adding in a register or some sort of table lookup.  These can't
12744     // be used as immediates.
12745     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12746       return;
12747
12748     // If we are in non-pic codegen mode, we allow the address of a global (with
12749     // an optional displacement) to be used with 'i'.
12750     GlobalAddressSDNode *GA = 0;
12751     int64_t Offset = 0;
12752
12753     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12754     while (1) {
12755       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12756         Offset += GA->getOffset();
12757         break;
12758       } else if (Op.getOpcode() == ISD::ADD) {
12759         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12760           Offset += C->getZExtValue();
12761           Op = Op.getOperand(0);
12762           continue;
12763         }
12764       } else if (Op.getOpcode() == ISD::SUB) {
12765         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12766           Offset += -C->getZExtValue();
12767           Op = Op.getOperand(0);
12768           continue;
12769         }
12770       }
12771
12772       // Otherwise, this isn't something we can handle, reject it.
12773       return;
12774     }
12775
12776     const GlobalValue *GV = GA->getGlobal();
12777     // If we require an extra load to get this address, as in PIC mode, we
12778     // can't accept it.
12779     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12780                                                         getTargetMachine())))
12781       return;
12782
12783     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12784                                         GA->getValueType(0), Offset);
12785     break;
12786   }
12787   }
12788
12789   if (Result.getNode()) {
12790     Ops.push_back(Result);
12791     return;
12792   }
12793   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12794 }
12795
12796 std::vector<unsigned> X86TargetLowering::
12797 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12798                                   EVT VT) const {
12799   if (Constraint.size() == 1) {
12800     // FIXME: not handling fp-stack yet!
12801     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12802     default: break;  // Unknown constraint letter
12803     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12804       if (Subtarget->is64Bit()) {
12805         if (VT == MVT::i32)
12806           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12807                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12808                                        X86::R10D,X86::R11D,X86::R12D,
12809                                        X86::R13D,X86::R14D,X86::R15D,
12810                                        X86::EBP, X86::ESP, 0);
12811         else if (VT == MVT::i16)
12812           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12813                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12814                                        X86::R10W,X86::R11W,X86::R12W,
12815                                        X86::R13W,X86::R14W,X86::R15W,
12816                                        X86::BP,  X86::SP, 0);
12817         else if (VT == MVT::i8)
12818           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12819                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12820                                        X86::R10B,X86::R11B,X86::R12B,
12821                                        X86::R13B,X86::R14B,X86::R15B,
12822                                        X86::BPL, X86::SPL, 0);
12823
12824         else if (VT == MVT::i64)
12825           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12826                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12827                                        X86::R10, X86::R11, X86::R12,
12828                                        X86::R13, X86::R14, X86::R15,
12829                                        X86::RBP, X86::RSP, 0);
12830
12831         break;
12832       }
12833       // 32-bit fallthrough
12834     case 'Q':   // Q_REGS
12835       if (VT == MVT::i32)
12836         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12837       else if (VT == MVT::i16)
12838         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12839       else if (VT == MVT::i8)
12840         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12841       else if (VT == MVT::i64)
12842         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12843       break;
12844     }
12845   }
12846
12847   return std::vector<unsigned>();
12848 }
12849
12850 std::pair<unsigned, const TargetRegisterClass*>
12851 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12852                                                 EVT VT) const {
12853   // First, see if this is a constraint that directly corresponds to an LLVM
12854   // register class.
12855   if (Constraint.size() == 1) {
12856     // GCC Constraint Letters
12857     switch (Constraint[0]) {
12858     default: break;
12859     case 'r':   // GENERAL_REGS
12860     case 'l':   // INDEX_REGS
12861       if (VT == MVT::i8)
12862         return std::make_pair(0U, X86::GR8RegisterClass);
12863       if (VT == MVT::i16)
12864         return std::make_pair(0U, X86::GR16RegisterClass);
12865       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
12866         return std::make_pair(0U, X86::GR32RegisterClass);
12867       return std::make_pair(0U, X86::GR64RegisterClass);
12868     case 'R':   // LEGACY_REGS
12869       if (VT == MVT::i8)
12870         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12871       if (VT == MVT::i16)
12872         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12873       if (VT == MVT::i32 || !Subtarget->is64Bit())
12874         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12875       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12876     case 'f':  // FP Stack registers.
12877       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12878       // value to the correct fpstack register class.
12879       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12880         return std::make_pair(0U, X86::RFP32RegisterClass);
12881       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12882         return std::make_pair(0U, X86::RFP64RegisterClass);
12883       return std::make_pair(0U, X86::RFP80RegisterClass);
12884     case 'y':   // MMX_REGS if MMX allowed.
12885       if (!Subtarget->hasMMX()) break;
12886       return std::make_pair(0U, X86::VR64RegisterClass);
12887     case 'Y':   // SSE_REGS if SSE2 allowed
12888       if (!Subtarget->hasXMMInt()) break;
12889       // FALL THROUGH.
12890     case 'x':   // SSE_REGS if SSE1 allowed
12891       if (!Subtarget->hasXMM()) break;
12892
12893       switch (VT.getSimpleVT().SimpleTy) {
12894       default: break;
12895       // Scalar SSE types.
12896       case MVT::f32:
12897       case MVT::i32:
12898         return std::make_pair(0U, X86::FR32RegisterClass);
12899       case MVT::f64:
12900       case MVT::i64:
12901         return std::make_pair(0U, X86::FR64RegisterClass);
12902       // Vector types.
12903       case MVT::v16i8:
12904       case MVT::v8i16:
12905       case MVT::v4i32:
12906       case MVT::v2i64:
12907       case MVT::v4f32:
12908       case MVT::v2f64:
12909         return std::make_pair(0U, X86::VR128RegisterClass);
12910       }
12911       break;
12912     }
12913   }
12914
12915   // Use the default implementation in TargetLowering to convert the register
12916   // constraint into a member of a register class.
12917   std::pair<unsigned, const TargetRegisterClass*> Res;
12918   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12919
12920   // Not found as a standard register?
12921   if (Res.second == 0) {
12922     // Map st(0) -> st(7) -> ST0
12923     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12924         tolower(Constraint[1]) == 's' &&
12925         tolower(Constraint[2]) == 't' &&
12926         Constraint[3] == '(' &&
12927         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12928         Constraint[5] == ')' &&
12929         Constraint[6] == '}') {
12930
12931       Res.first = X86::ST0+Constraint[4]-'0';
12932       Res.second = X86::RFP80RegisterClass;
12933       return Res;
12934     }
12935
12936     // GCC allows "st(0)" to be called just plain "st".
12937     if (StringRef("{st}").equals_lower(Constraint)) {
12938       Res.first = X86::ST0;
12939       Res.second = X86::RFP80RegisterClass;
12940       return Res;
12941     }
12942
12943     // flags -> EFLAGS
12944     if (StringRef("{flags}").equals_lower(Constraint)) {
12945       Res.first = X86::EFLAGS;
12946       Res.second = X86::CCRRegisterClass;
12947       return Res;
12948     }
12949
12950     // 'A' means EAX + EDX.
12951     if (Constraint == "A") {
12952       Res.first = X86::EAX;
12953       Res.second = X86::GR32_ADRegisterClass;
12954       return Res;
12955     }
12956     return Res;
12957   }
12958
12959   // Otherwise, check to see if this is a register class of the wrong value
12960   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12961   // turn into {ax},{dx}.
12962   if (Res.second->hasType(VT))
12963     return Res;   // Correct type already, nothing to do.
12964
12965   // All of the single-register GCC register classes map their values onto
12966   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12967   // really want an 8-bit or 32-bit register, map to the appropriate register
12968   // class and return the appropriate register.
12969   if (Res.second == X86::GR16RegisterClass) {
12970     if (VT == MVT::i8) {
12971       unsigned DestReg = 0;
12972       switch (Res.first) {
12973       default: break;
12974       case X86::AX: DestReg = X86::AL; break;
12975       case X86::DX: DestReg = X86::DL; break;
12976       case X86::CX: DestReg = X86::CL; break;
12977       case X86::BX: DestReg = X86::BL; break;
12978       }
12979       if (DestReg) {
12980         Res.first = DestReg;
12981         Res.second = X86::GR8RegisterClass;
12982       }
12983     } else if (VT == MVT::i32) {
12984       unsigned DestReg = 0;
12985       switch (Res.first) {
12986       default: break;
12987       case X86::AX: DestReg = X86::EAX; break;
12988       case X86::DX: DestReg = X86::EDX; break;
12989       case X86::CX: DestReg = X86::ECX; break;
12990       case X86::BX: DestReg = X86::EBX; break;
12991       case X86::SI: DestReg = X86::ESI; break;
12992       case X86::DI: DestReg = X86::EDI; break;
12993       case X86::BP: DestReg = X86::EBP; break;
12994       case X86::SP: DestReg = X86::ESP; break;
12995       }
12996       if (DestReg) {
12997         Res.first = DestReg;
12998         Res.second = X86::GR32RegisterClass;
12999       }
13000     } else if (VT == MVT::i64) {
13001       unsigned DestReg = 0;
13002       switch (Res.first) {
13003       default: break;
13004       case X86::AX: DestReg = X86::RAX; break;
13005       case X86::DX: DestReg = X86::RDX; break;
13006       case X86::CX: DestReg = X86::RCX; break;
13007       case X86::BX: DestReg = X86::RBX; break;
13008       case X86::SI: DestReg = X86::RSI; break;
13009       case X86::DI: DestReg = X86::RDI; break;
13010       case X86::BP: DestReg = X86::RBP; break;
13011       case X86::SP: DestReg = X86::RSP; break;
13012       }
13013       if (DestReg) {
13014         Res.first = DestReg;
13015         Res.second = X86::GR64RegisterClass;
13016       }
13017     }
13018   } else if (Res.second == X86::FR32RegisterClass ||
13019              Res.second == X86::FR64RegisterClass ||
13020              Res.second == X86::VR128RegisterClass) {
13021     // Handle references to XMM physical registers that got mapped into the
13022     // wrong class.  This can happen with constraints like {xmm0} where the
13023     // target independent register mapper will just pick the first match it can
13024     // find, ignoring the required type.
13025     if (VT == MVT::f32)
13026       Res.second = X86::FR32RegisterClass;
13027     else if (VT == MVT::f64)
13028       Res.second = X86::FR64RegisterClass;
13029     else if (X86::VR128RegisterClass->hasType(VT))
13030       Res.second = X86::VR128RegisterClass;
13031   }
13032
13033   return Res;
13034 }