[AVX] Implement 256-bit vector lowering for EXTRACT_VECTOR_ELT.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 static cl::opt<bool>
60 Disable256Bit("disable-256bit", cl::Hidden,
61               cl::desc("Disable use of 256-bit vectors"));
62
63 // Forward declarations.
64 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65                        SDValue V2);
66
67 static SDValue Insert128BitVector(SDValue Result,
68                                   SDValue Vec,
69                                   SDValue Idx,
70                                   SelectionDAG &DAG,
71                                   DebugLoc dl);
72
73 static SDValue Extract128BitVector(SDValue Vec,
74                                    SDValue Idx,
75                                    SelectionDAG &DAG,
76                                    DebugLoc dl);
77
78 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG);
79
80
81 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
82 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
83 /// simple subregister reference.  Idx is an index in the 128 bits we
84 /// want.  It need not be aligned to a 128-bit bounday.  That makes
85 /// lowering EXTRACT_VECTOR_ELT operations easier.
86 static SDValue Extract128BitVector(SDValue Vec,
87                                    SDValue Idx,
88                                    SelectionDAG &DAG,
89                                    DebugLoc dl) {
90   EVT VT = Vec.getValueType();
91   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
92
93   EVT ElVT = VT.getVectorElementType();
94
95   int Factor = VT.getSizeInBits() / 128;
96
97   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(),
98                                   ElVT,
99                                   VT.getVectorNumElements() / Factor);
100
101   // Extract from UNDEF is UNDEF.
102   if (Vec.getOpcode() == ISD::UNDEF)
103     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
104
105   if (isa<ConstantSDNode>(Idx)) {
106     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
107
108     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
109     // we can match to VEXTRACTF128.
110     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
111
112     // This is the index of the first element of the 128-bit chunk
113     // we want.
114     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
115                                  * ElemsPerChunk);
116
117     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
118
119     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
120                                  VecIdx);
121
122     return Result;
123   }
124
125   return SDValue();
126 }
127
128 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
129 /// sets things up to match to an AVX VINSERTF128 instruction or a
130 /// simple superregister reference.  Idx is an index in the 128 bits
131 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
132 /// lowering INSERT_VECTOR_ELT operations easier.
133 static SDValue Insert128BitVector(SDValue Result,
134                                   SDValue Vec,
135                                   SDValue Idx,
136                                   SelectionDAG &DAG,
137                                   DebugLoc dl) {
138   if (isa<ConstantSDNode>(Idx)) {
139     EVT VT = Vec.getValueType();
140     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
141
142     EVT ElVT = VT.getVectorElementType();
143
144     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
145
146     EVT ResultVT = Result.getValueType();
147
148     // Insert the relevant 128 bits.
149     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
150
151     // This is the index of the first element of the 128-bit chunk
152     // we want.
153     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
154                                  * ElemsPerChunk);
155
156     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
157
158     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
159                          VecIdx);
160     return Result;
161   }
162
163   return SDValue();
164 }
165
166 /// Given two vectors, concat them.
167 static SDValue ConcatVectors(SDValue Lower, SDValue Upper, SelectionDAG &DAG) {
168   DebugLoc dl = Lower.getDebugLoc();
169
170   assert(Lower.getValueType() == Upper.getValueType() && "Mismatched vectors!");
171
172   EVT VT = EVT::getVectorVT(*DAG.getContext(),
173                             Lower.getValueType().getVectorElementType(),
174                             Lower.getValueType().getVectorNumElements() * 2);
175
176   // TODO: Generalize to arbitrary vector length (this assumes 256-bit vectors).
177   assert(VT.getSizeInBits() == 256 && "Unsupported vector concat!");
178
179   // Insert the upper subvector.
180   SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Upper,
181                                    DAG.getConstant(
182                                      // This is half the length of the result
183                                      // vector.  Start inserting the upper 128
184                                      // bits here.
185                                      Lower.getValueType().getVectorNumElements(),
186                                      MVT::i32),
187                                    DAG, dl);
188
189   // Insert the lower subvector.
190   Vec = Insert128BitVector(Vec, Lower, DAG.getConstant(0, MVT::i32), DAG, dl);
191   return Vec;
192 }
193
194 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
195   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
196   bool is64Bit = Subtarget->is64Bit();
197
198   if (Subtarget->isTargetEnvMacho()) {
199     if (is64Bit)
200       return new X8664_MachoTargetObjectFile();
201     return new TargetLoweringObjectFileMachO();
202   }
203
204   if (Subtarget->isTargetELF()) {
205     if (is64Bit)
206       return new X8664_ELFTargetObjectFile(TM);
207     return new X8632_ELFTargetObjectFile(TM);
208   }
209   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
210     return new TargetLoweringObjectFileCOFF();
211   llvm_unreachable("unknown subtarget type");
212 }
213
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(TM)) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasXMMInt();
218   X86ScalarSSEf32 = Subtarget->hasXMM();
219   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
220
221   RegInfo = TM.getRegisterInfo();
222   TD = getTargetData();
223
224   // Set up the TargetLowering object.
225   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
226
227   // X86 is weird, it always uses i8 for shift amounts and setcc results.
228   setShiftAmountType(MVT::i8);
229   setBooleanContents(ZeroOrOneBooleanContent);
230   setSchedulingPreference(Sched::RegPressure);
231   setStackPointerRegisterToSaveRestore(X86StackPtr);
232
233   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
234     // Setup Windows compiler runtime calls.
235     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
236     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
237     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
238     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
239     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
240     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
241     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
242     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
243   }
244
245   if (Subtarget->isTargetDarwin()) {
246     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
247     setUseUnderscoreSetJmp(false);
248     setUseUnderscoreLongJmp(false);
249   } else if (Subtarget->isTargetMingw()) {
250     // MS runtime is weird: it exports _setjmp, but longjmp!
251     setUseUnderscoreSetJmp(true);
252     setUseUnderscoreLongJmp(false);
253   } else {
254     setUseUnderscoreSetJmp(true);
255     setUseUnderscoreLongJmp(true);
256   }
257
258   // Set up the register classes.
259   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
260   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
261   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
262   if (Subtarget->is64Bit())
263     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
264
265   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
266
267   // We don't accept any truncstore of integer registers.
268   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
269   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
270   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
271   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
272   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
273   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
274
275   // SETOEQ and SETUNE require checking two conditions.
276   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
277   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
278   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
279   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
280   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
281   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
282
283   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
284   // operation.
285   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
286   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
287   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
288
289   if (Subtarget->is64Bit()) {
290     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
291     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
292   } else if (!UseSoftFloat) {
293     // We have an algorithm for SSE2->double, and we turn this into a
294     // 64-bit FILD followed by conditional FADD for other targets.
295     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
296     // We have an algorithm for SSE2, and we turn this into a 64-bit
297     // FILD for other targets.
298     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
299   }
300
301   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
302   // this operation.
303   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
304   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
305
306   if (!UseSoftFloat) {
307     // SSE has no i16 to fp conversion, only i32
308     if (X86ScalarSSEf32) {
309       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
310       // f32 and f64 cases are Legal, f80 case is not
311       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
312     } else {
313       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
314       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
315     }
316   } else {
317     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
318     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
319   }
320
321   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
322   // are Legal, f80 is custom lowered.
323   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
324   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
325
326   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
327   // this operation.
328   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
329   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
330
331   if (X86ScalarSSEf32) {
332     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
333     // f32 and f64 cases are Legal, f80 case is not
334     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
335   } else {
336     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
337     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
338   }
339
340   // Handle FP_TO_UINT by promoting the destination to a larger signed
341   // conversion.
342   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
343   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
344   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
345
346   if (Subtarget->is64Bit()) {
347     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
348     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
349   } else if (!UseSoftFloat) {
350     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
351       // Expand FP_TO_UINT into a select.
352       // FIXME: We would like to use a Custom expander here eventually to do
353       // the optimal thing for SSE vs. the default expansion in the legalizer.
354       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
355     else
356       // With SSE3 we can use fisttpll to convert to a signed i64; without
357       // SSE, we're stuck with a fistpll.
358       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
359   }
360
361   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
362   if (!X86ScalarSSEf64) {
363     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
364     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
365     if (Subtarget->is64Bit()) {
366       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
367       // Without SSE, i64->f64 goes through memory.
368       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
369     }
370   }
371
372   // Scalar integer divide and remainder are lowered to use operations that
373   // produce two results, to match the available instructions. This exposes
374   // the two-result form to trivial CSE, which is able to combine x/y and x%y
375   // into a single instruction.
376   //
377   // Scalar integer multiply-high is also lowered to use two-result
378   // operations, to match the available instructions. However, plain multiply
379   // (low) operations are left as Legal, as there are single-result
380   // instructions for this in x86. Using the two-result multiply instructions
381   // when both high and low results are needed must be arranged by dagcombine.
382   for (unsigned i = 0, e = 4; i != e; ++i) {
383     MVT VT = IntVTs[i];
384     setOperationAction(ISD::MULHS, VT, Expand);
385     setOperationAction(ISD::MULHU, VT, Expand);
386     setOperationAction(ISD::SDIV, VT, Expand);
387     setOperationAction(ISD::UDIV, VT, Expand);
388     setOperationAction(ISD::SREM, VT, Expand);
389     setOperationAction(ISD::UREM, VT, Expand);
390
391     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
392     setOperationAction(ISD::ADDC, VT, Custom);
393     setOperationAction(ISD::ADDE, VT, Custom);
394     setOperationAction(ISD::SUBC, VT, Custom);
395     setOperationAction(ISD::SUBE, VT, Custom);
396   }
397
398   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
399   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
400   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
401   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
402   if (Subtarget->is64Bit())
403     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
404   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
407   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
408   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
409   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
410   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
411   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
412
413   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
414   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
415   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
416   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
417   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
418   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
419   if (Subtarget->is64Bit()) {
420     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
421     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
422   }
423
424   if (Subtarget->hasPOPCNT()) {
425     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
426   } else {
427     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
429     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
430     if (Subtarget->is64Bit())
431       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
432   }
433
434   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
435   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
436
437   // These should be promoted to a larger select which is supported.
438   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
439   // X86 wants to expand cmov itself.
440   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
452   if (Subtarget->is64Bit()) {
453     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
454     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
455   }
456   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
457
458   // Darwin ABI issue.
459   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
460   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
462   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
463   if (Subtarget->is64Bit())
464     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
465   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
466   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
467   if (Subtarget->is64Bit()) {
468     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
469     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
470     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
471     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
472     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
473   }
474   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
475   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
477   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
481     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
482   }
483
484   if (Subtarget->hasXMM())
485     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
486
487   // We may not have a libcall for MEMBARRIER so we should lower this.
488   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
489
490   // On X86 and X86-64, atomic operations are lowered to locked instructions.
491   // Locked instructions, in turn, have implicit fence semantics (all memory
492   // operations are flushed before issuing the locked instruction, and they
493   // are not buffered), so we can fold away the common pattern of
494   // fence-atomic-fence.
495   setShouldFoldAtomicFences(true);
496
497   // Expand certain atomics
498   for (unsigned i = 0, e = 4; i != e; ++i) {
499     MVT VT = IntVTs[i];
500     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
512   }
513
514   // FIXME - use subtarget debug flags
515   if (!Subtarget->isTargetDarwin() &&
516       !Subtarget->isTargetELF() &&
517       !Subtarget->isTargetCygMing()) {
518     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
519   }
520
521   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
522   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
523   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
524   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
525   if (Subtarget->is64Bit()) {
526     setExceptionPointerRegister(X86::RAX);
527     setExceptionSelectorRegister(X86::RDX);
528   } else {
529     setExceptionPointerRegister(X86::EAX);
530     setExceptionSelectorRegister(X86::EDX);
531   }
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
533   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
534
535   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552   if (Subtarget->is64Bit())
553     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
554   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
555     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
556   else
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, 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     // We don't support sin/cos/fmod
578     setOperationAction(ISD::FSIN , MVT::f64, Expand);
579     setOperationAction(ISD::FCOS , MVT::f64, Expand);
580     setOperationAction(ISD::FSIN , MVT::f32, Expand);
581     setOperationAction(ISD::FCOS , MVT::f32, Expand);
582
583     // Expand FP immediates into loads from the stack, except for the special
584     // cases we handle.
585     addLegalFPImmediate(APFloat(+0.0)); // xorpd
586     addLegalFPImmediate(APFloat(+0.0f)); // xorps
587   } else if (!UseSoftFloat && X86ScalarSSEf32) {
588     // Use SSE for f32, x87 for f64.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
591     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
592
593     // Use ANDPS to simulate FABS.
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
600
601     // Use ANDPS and ORPS to simulate FCOPYSIGN.
602     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604
605     // We don't support sin/cos/fmod
606     setOperationAction(ISD::FSIN , MVT::f32, Expand);
607     setOperationAction(ISD::FCOS , MVT::f32, Expand);
608
609     // Special cases we handle for FP constants.
610     addLegalFPImmediate(APFloat(+0.0f)); // xorps
611     addLegalFPImmediate(APFloat(+0.0)); // FLD0
612     addLegalFPImmediate(APFloat(+1.0)); // FLD1
613     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
614     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
615
616     if (!UnsafeFPMath) {
617       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
618       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
619     }
620   } else if (!UseSoftFloat) {
621     // f32 and f64 in x87.
622     // Set up the FP register classes.
623     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
624     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
625
626     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
627     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
628     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
629     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
630
631     if (!UnsafeFPMath) {
632       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
633       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
634     }
635     addLegalFPImmediate(APFloat(+0.0)); // FLD0
636     addLegalFPImmediate(APFloat(+1.0)); // FLD1
637     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
638     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
639     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
640     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
641     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
642     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
643   }
644
645   // Long double always uses X87.
646   if (!UseSoftFloat) {
647     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
648     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
649     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
650     {
651       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
652       addLegalFPImmediate(TmpFlt);  // FLD0
653       TmpFlt.changeSign();
654       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
655
656       bool ignored;
657       APFloat TmpFlt2(+1.0);
658       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
659                       &ignored);
660       addLegalFPImmediate(TmpFlt2);  // FLD1
661       TmpFlt2.changeSign();
662       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
663     }
664
665     if (!UnsafeFPMath) {
666       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
667       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
668     }
669   }
670
671   // Always use a library call for pow.
672   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
674   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
675
676   setOperationAction(ISD::FLOG, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
678   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP, MVT::f80, Expand);
680   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
681
682   // First set operation action for all vector types to either promote
683   // (for widening) or expand (for scalarization). Then we will selectively
684   // turn on ones that can be effectively codegen'd.
685   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
686        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
687     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
705     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
834     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
835     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
836     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     // i8 and i16 vectors are custom , because the source register and source
932     // source memory operand types are not the same width.  f32 vectors are
933     // custom since the immediate controlling the insert encodes additional
934     // information.
935     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
944
945     if (Subtarget->is64Bit()) {
946       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
947       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
948     }
949   }
950
951   if (Subtarget->hasSSE42())
952     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
953
954   if (!UseSoftFloat && Subtarget->hasAVX()) {
955     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
956     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
957     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
958     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
959     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
960
961     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
962     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
963     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
964     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
965
966     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
967     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
968     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
969     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
970     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
971     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
972
973     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
974     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
975     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
976     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
977     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
978     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
979
980     // Custom lower build_vector, vector_shuffle, scalar_to_vector,
981     // insert_vector_elt extract_subvector and extract_vector_elt for
982     // 256-bit types.
983     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
984          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
985          ++i) {
986       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
987       // Do not attempt to custom lower non-256-bit vectors
988       if (!isPowerOf2_32(MVT(VT).getVectorNumElements())
989           || (MVT(VT).getSizeInBits() < 256))
990         continue;
991       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
992       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
993       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
994       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
995       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
996     }
997     // Custom-lower insert_subvector and extract_subvector based on
998     // the result type.
999     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1000          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1001          ++i) {
1002       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-256-bit vectors
1004       if (!isPowerOf2_32(MVT(VT).getVectorNumElements()))
1005         continue;
1006
1007       if (MVT(VT).getSizeInBits() == 128) {
1008         setOperationAction(ISD::EXTRACT_SUBVECTOR,  VT, Custom);
1009       }
1010       else if (MVT(VT).getSizeInBits() == 256) {
1011         setOperationAction(ISD::INSERT_SUBVECTOR,  VT, Custom);
1012       }
1013     }
1014
1015     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1016     // Don't promote loads because we need them for VPERM vector index versions.
1017
1018     for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1019          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE;
1020          VT++) {
1021       if (!isPowerOf2_32(MVT((MVT::SimpleValueType)VT).getVectorNumElements())
1022           || (MVT((MVT::SimpleValueType)VT).getSizeInBits() < 256))
1023         continue;
1024       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
1025       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v4i64);
1026       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
1027       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v4i64);
1028       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
1029       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v4i64);
1030       //setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
1031       //AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v4i64);
1032       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
1033       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v4i64);
1034     }
1035   }
1036
1037   // We want to custom lower some of our intrinsics.
1038   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1039
1040
1041   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1042   // handle type legalization for these operations here.
1043   //
1044   // FIXME: We really should do custom legalization for addition and
1045   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1046   // than generic legalization for 64-bit multiplication-with-overflow, though.
1047   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1048     // Add/Sub/Mul with overflow operations are custom lowered.
1049     MVT VT = IntVTs[i];
1050     setOperationAction(ISD::SADDO, VT, Custom);
1051     setOperationAction(ISD::UADDO, VT, Custom);
1052     setOperationAction(ISD::SSUBO, VT, Custom);
1053     setOperationAction(ISD::USUBO, VT, Custom);
1054     setOperationAction(ISD::SMULO, VT, Custom);
1055     setOperationAction(ISD::UMULO, VT, Custom);
1056   }
1057
1058   // There are no 8-bit 3-address imul/mul instructions
1059   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1060   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1061
1062   if (!Subtarget->is64Bit()) {
1063     // These libcalls are not available in 32-bit.
1064     setLibcallName(RTLIB::SHL_I128, 0);
1065     setLibcallName(RTLIB::SRL_I128, 0);
1066     setLibcallName(RTLIB::SRA_I128, 0);
1067   }
1068
1069   // We have target-specific dag combine patterns for the following nodes:
1070   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1071   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1072   setTargetDAGCombine(ISD::BUILD_VECTOR);
1073   setTargetDAGCombine(ISD::SELECT);
1074   setTargetDAGCombine(ISD::SHL);
1075   setTargetDAGCombine(ISD::SRA);
1076   setTargetDAGCombine(ISD::SRL);
1077   setTargetDAGCombine(ISD::OR);
1078   setTargetDAGCombine(ISD::AND);
1079   setTargetDAGCombine(ISD::ADD);
1080   setTargetDAGCombine(ISD::SUB);
1081   setTargetDAGCombine(ISD::STORE);
1082   setTargetDAGCombine(ISD::ZERO_EXTEND);
1083   if (Subtarget->is64Bit())
1084     setTargetDAGCombine(ISD::MUL);
1085
1086   computeRegisterProperties();
1087
1088   // On Darwin, -Os means optimize for size without hurting performance,
1089   // do not reduce the limit.
1090   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1091   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1092   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1093   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1094   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1095   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1096   setPrefLoopAlignment(16);
1097   benefitFromCodePlacementOpt = true;
1098 }
1099
1100
1101 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1102   return MVT::i8;
1103 }
1104
1105
1106 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1107 /// the desired ByVal argument alignment.
1108 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1109   if (MaxAlign == 16)
1110     return;
1111   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1112     if (VTy->getBitWidth() == 128)
1113       MaxAlign = 16;
1114   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1115     unsigned EltAlign = 0;
1116     getMaxByValAlign(ATy->getElementType(), EltAlign);
1117     if (EltAlign > MaxAlign)
1118       MaxAlign = EltAlign;
1119   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1120     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1121       unsigned EltAlign = 0;
1122       getMaxByValAlign(STy->getElementType(i), EltAlign);
1123       if (EltAlign > MaxAlign)
1124         MaxAlign = EltAlign;
1125       if (MaxAlign == 16)
1126         break;
1127     }
1128   }
1129   return;
1130 }
1131
1132 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1133 /// function arguments in the caller parameter area. For X86, aggregates
1134 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1135 /// are at 4-byte boundaries.
1136 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1137   if (Subtarget->is64Bit()) {
1138     // Max of 8 and alignment of type.
1139     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1140     if (TyAlign > 8)
1141       return TyAlign;
1142     return 8;
1143   }
1144
1145   unsigned Align = 4;
1146   if (Subtarget->hasXMM())
1147     getMaxByValAlign(Ty, Align);
1148   return Align;
1149 }
1150
1151 /// getOptimalMemOpType - Returns the target specific optimal type for load
1152 /// and store operations as a result of memset, memcpy, and memmove
1153 /// lowering. If DstAlign is zero that means it's safe to destination
1154 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1155 /// means there isn't a need to check it against alignment requirement,
1156 /// probably because the source does not need to be loaded. If
1157 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1158 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1159 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1160 /// constant so it does not need to be loaded.
1161 /// It returns EVT::Other if the type should be determined using generic
1162 /// target-independent logic.
1163 EVT
1164 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1165                                        unsigned DstAlign, unsigned SrcAlign,
1166                                        bool NonScalarIntSafe,
1167                                        bool MemcpyStrSrc,
1168                                        MachineFunction &MF) const {
1169   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1170   // linux.  This is because the stack realignment code can't handle certain
1171   // cases like PR2962.  This should be removed when PR2962 is fixed.
1172   const Function *F = MF.getFunction();
1173   if (NonScalarIntSafe &&
1174       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1175     if (Size >= 16 &&
1176         (Subtarget->isUnalignedMemAccessFast() ||
1177          ((DstAlign == 0 || DstAlign >= 16) &&
1178           (SrcAlign == 0 || SrcAlign >= 16))) &&
1179         Subtarget->getStackAlignment() >= 16) {
1180       if (Subtarget->hasSSE2())
1181         return MVT::v4i32;
1182       if (Subtarget->hasSSE1())
1183         return MVT::v4f32;
1184     } else if (!MemcpyStrSrc && Size >= 8 &&
1185                !Subtarget->is64Bit() &&
1186                Subtarget->getStackAlignment() >= 8 &&
1187                Subtarget->hasXMMInt()) {
1188       // Do not use f64 to lower memcpy if source is string constant. It's
1189       // better to use i32 to avoid the loads.
1190       return MVT::f64;
1191     }
1192   }
1193   if (Subtarget->is64Bit() && Size >= 8)
1194     return MVT::i64;
1195   return MVT::i32;
1196 }
1197
1198 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1199 /// current function.  The returned value is a member of the
1200 /// MachineJumpTableInfo::JTEntryKind enum.
1201 unsigned X86TargetLowering::getJumpTableEncoding() const {
1202   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1203   // symbol.
1204   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1205       Subtarget->isPICStyleGOT())
1206     return MachineJumpTableInfo::EK_Custom32;
1207
1208   // Otherwise, use the normal jump table encoding heuristics.
1209   return TargetLowering::getJumpTableEncoding();
1210 }
1211
1212 const MCExpr *
1213 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1214                                              const MachineBasicBlock *MBB,
1215                                              unsigned uid,MCContext &Ctx) const{
1216   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1217          Subtarget->isPICStyleGOT());
1218   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1219   // entries.
1220   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1221                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1222 }
1223
1224 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1225 /// jumptable.
1226 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1227                                                     SelectionDAG &DAG) const {
1228   if (!Subtarget->is64Bit())
1229     // This doesn't have DebugLoc associated with it, but is not really the
1230     // same as a Register.
1231     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1232   return Table;
1233 }
1234
1235 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1236 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1237 /// MCExpr.
1238 const MCExpr *X86TargetLowering::
1239 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1240                              MCContext &Ctx) const {
1241   // X86-64 uses RIP relative addressing based on the jump table label.
1242   if (Subtarget->isPICStyleRIPRel())
1243     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1244
1245   // Otherwise, the reference is relative to the PIC base.
1246   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1247 }
1248
1249 /// getFunctionAlignment - Return the Log2 alignment of this function.
1250 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1251   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1252 }
1253
1254 // FIXME: Why this routine is here? Move to RegInfo!
1255 std::pair<const TargetRegisterClass*, uint8_t>
1256 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1257   const TargetRegisterClass *RRC = 0;
1258   uint8_t Cost = 1;
1259   switch (VT.getSimpleVT().SimpleTy) {
1260   default:
1261     return TargetLowering::findRepresentativeClass(VT);
1262   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1263     RRC = (Subtarget->is64Bit()
1264            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1265     break;
1266   case MVT::x86mmx:
1267     RRC = X86::VR64RegisterClass;
1268     break;
1269   case MVT::f32: case MVT::f64:
1270   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1271   case MVT::v4f32: case MVT::v2f64:
1272   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1273   case MVT::v4f64:
1274     RRC = X86::VR128RegisterClass;
1275     break;
1276   }
1277   return std::make_pair(RRC, Cost);
1278 }
1279
1280 // FIXME: Why this routine is here? Move to RegInfo!
1281 unsigned
1282 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1283                                        MachineFunction &MF) const {
1284   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
1285
1286   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1287   switch (RC->getID()) {
1288   default:
1289     return 0;
1290   case X86::GR32RegClassID:
1291     return 4 - FPDiff;
1292   case X86::GR64RegClassID:
1293     return 8 - FPDiff;
1294   case X86::VR128RegClassID:
1295     return Subtarget->is64Bit() ? 10 : 4;
1296   case X86::VR64RegClassID:
1297     return 4;
1298   }
1299 }
1300
1301 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1302                                                unsigned &Offset) const {
1303   if (!Subtarget->isTargetLinux())
1304     return false;
1305
1306   if (Subtarget->is64Bit()) {
1307     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1308     Offset = 0x28;
1309     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1310       AddressSpace = 256;
1311     else
1312       AddressSpace = 257;
1313   } else {
1314     // %gs:0x14 on i386
1315     Offset = 0x14;
1316     AddressSpace = 256;
1317   }
1318   return true;
1319 }
1320
1321
1322 //===----------------------------------------------------------------------===//
1323 //               Return Value Calling Convention Implementation
1324 //===----------------------------------------------------------------------===//
1325
1326 #include "X86GenCallingConv.inc"
1327
1328 bool
1329 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1330                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1331                         LLVMContext &Context) const {
1332   SmallVector<CCValAssign, 16> RVLocs;
1333   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1334                  RVLocs, Context);
1335   return CCInfo.CheckReturn(Outs, RetCC_X86);
1336 }
1337
1338 SDValue
1339 X86TargetLowering::LowerReturn(SDValue Chain,
1340                                CallingConv::ID CallConv, bool isVarArg,
1341                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1342                                const SmallVectorImpl<SDValue> &OutVals,
1343                                DebugLoc dl, SelectionDAG &DAG) const {
1344   MachineFunction &MF = DAG.getMachineFunction();
1345   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1346
1347   SmallVector<CCValAssign, 16> RVLocs;
1348   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1349                  RVLocs, *DAG.getContext());
1350   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1351
1352   // Add the regs to the liveout set for the function.
1353   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1354   for (unsigned i = 0; i != RVLocs.size(); ++i)
1355     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1356       MRI.addLiveOut(RVLocs[i].getLocReg());
1357
1358   SDValue Flag;
1359
1360   SmallVector<SDValue, 6> RetOps;
1361   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1362   // Operand #1 = Bytes To Pop
1363   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1364                    MVT::i16));
1365
1366   // Copy the result values into the output registers.
1367   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1368     CCValAssign &VA = RVLocs[i];
1369     assert(VA.isRegLoc() && "Can only return in registers!");
1370     SDValue ValToCopy = OutVals[i];
1371     EVT ValVT = ValToCopy.getValueType();
1372
1373     // If this is x86-64, and we disabled SSE, we can't return FP values,
1374     // or SSE or MMX vectors.
1375     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1376          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1377           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1378       report_fatal_error("SSE register return with SSE disabled");
1379     }
1380     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1381     // llvm-gcc has never done it right and no one has noticed, so this
1382     // should be OK for now.
1383     if (ValVT == MVT::f64 &&
1384         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1385       report_fatal_error("SSE2 register return with SSE2 disabled");
1386
1387     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1388     // the RET instruction and handled by the FP Stackifier.
1389     if (VA.getLocReg() == X86::ST0 ||
1390         VA.getLocReg() == X86::ST1) {
1391       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1392       // change the value to the FP stack register class.
1393       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1394         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1395       RetOps.push_back(ValToCopy);
1396       // Don't emit a copytoreg.
1397       continue;
1398     }
1399
1400     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1401     // which is returned in RAX / RDX.
1402     if (Subtarget->is64Bit()) {
1403       if (ValVT == MVT::x86mmx) {
1404         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1405           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1406           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1407                                   ValToCopy);
1408           // If we don't have SSE2 available, convert to v4f32 so the generated
1409           // register is legal.
1410           if (!Subtarget->hasSSE2())
1411             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1412         }
1413       }
1414     }
1415
1416     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1417     Flag = Chain.getValue(1);
1418   }
1419
1420   // The x86-64 ABI for returning structs by value requires that we copy
1421   // the sret argument into %rax for the return. We saved the argument into
1422   // a virtual register in the entry block, so now we copy the value out
1423   // and into %rax.
1424   if (Subtarget->is64Bit() &&
1425       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1426     MachineFunction &MF = DAG.getMachineFunction();
1427     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1428     unsigned Reg = FuncInfo->getSRetReturnReg();
1429     assert(Reg &&
1430            "SRetReturnReg should have been set in LowerFormalArguments().");
1431     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1432
1433     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1434     Flag = Chain.getValue(1);
1435
1436     // RAX now acts like a return value.
1437     MRI.addLiveOut(X86::RAX);
1438   }
1439
1440   RetOps[0] = Chain;  // Update chain.
1441
1442   // Add the flag if we have it.
1443   if (Flag.getNode())
1444     RetOps.push_back(Flag);
1445
1446   return DAG.getNode(X86ISD::RET_FLAG, dl,
1447                      MVT::Other, &RetOps[0], RetOps.size());
1448 }
1449
1450 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1451   if (N->getNumValues() != 1)
1452     return false;
1453   if (!N->hasNUsesOfValue(1, 0))
1454     return false;
1455
1456   SDNode *Copy = *N->use_begin();
1457   if (Copy->getOpcode() != ISD::CopyToReg &&
1458       Copy->getOpcode() != ISD::FP_EXTEND)
1459     return false;
1460
1461   bool HasRet = false;
1462   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1463        UI != UE; ++UI) {
1464     if (UI->getOpcode() != X86ISD::RET_FLAG)
1465       return false;
1466     HasRet = true;
1467   }
1468
1469   return HasRet;
1470 }
1471
1472 /// LowerCallResult - Lower the result values of a call into the
1473 /// appropriate copies out of appropriate physical registers.
1474 ///
1475 SDValue
1476 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1477                                    CallingConv::ID CallConv, bool isVarArg,
1478                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1479                                    DebugLoc dl, SelectionDAG &DAG,
1480                                    SmallVectorImpl<SDValue> &InVals) const {
1481
1482   // Assign locations to each value returned by this call.
1483   SmallVector<CCValAssign, 16> RVLocs;
1484   bool Is64Bit = Subtarget->is64Bit();
1485   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1486                  RVLocs, *DAG.getContext());
1487   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1488
1489   // Copy all of the result registers out of their specified physreg.
1490   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1491     CCValAssign &VA = RVLocs[i];
1492     EVT CopyVT = VA.getValVT();
1493
1494     // If this is x86-64, and we disabled SSE, we can't return FP values
1495     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1496         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1497       report_fatal_error("SSE register return with SSE disabled");
1498     }
1499
1500     SDValue Val;
1501
1502     // If this is a call to a function that returns an fp value on the floating
1503     // point stack, we must guarantee the the value is popped from the stack, so
1504     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1505     // if the return value is not used. We use the FpGET_ST0 instructions
1506     // instead.
1507     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1508       // If we prefer to use the value in xmm registers, copy it out as f80 and
1509       // use a truncate to move it from fp stack reg to xmm reg.
1510       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1511       bool isST0 = VA.getLocReg() == X86::ST0;
1512       unsigned Opc = 0;
1513       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1514       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1515       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1516       SDValue Ops[] = { Chain, InFlag };
1517       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1518                                          Ops, 2), 1);
1519       Val = Chain.getValue(0);
1520
1521       // Round the f80 to the right size, which also moves it to the appropriate
1522       // xmm register.
1523       if (CopyVT != VA.getValVT())
1524         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1525                           // This truncation won't change the value.
1526                           DAG.getIntPtrConstant(1));
1527     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1528       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1529       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1530         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1531                                    MVT::v2i64, InFlag).getValue(1);
1532         Val = Chain.getValue(0);
1533         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1534                           Val, DAG.getConstant(0, MVT::i64));
1535       } else {
1536         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1537                                    MVT::i64, InFlag).getValue(1);
1538         Val = Chain.getValue(0);
1539       }
1540       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1541     } else {
1542       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1543                                  CopyVT, InFlag).getValue(1);
1544       Val = Chain.getValue(0);
1545     }
1546     InFlag = Chain.getValue(2);
1547     InVals.push_back(Val);
1548   }
1549
1550   return Chain;
1551 }
1552
1553
1554 //===----------------------------------------------------------------------===//
1555 //                C & StdCall & Fast Calling Convention implementation
1556 //===----------------------------------------------------------------------===//
1557 //  StdCall calling convention seems to be standard for many Windows' API
1558 //  routines and around. It differs from C calling convention just a little:
1559 //  callee should clean up the stack, not caller. Symbols should be also
1560 //  decorated in some fancy way :) It doesn't support any vector arguments.
1561 //  For info on fast calling convention see Fast Calling Convention (tail call)
1562 //  implementation LowerX86_32FastCCCallTo.
1563
1564 /// CallIsStructReturn - Determines whether a call uses struct return
1565 /// semantics.
1566 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1567   if (Outs.empty())
1568     return false;
1569
1570   return Outs[0].Flags.isSRet();
1571 }
1572
1573 /// ArgsAreStructReturn - Determines whether a function uses struct
1574 /// return semantics.
1575 static bool
1576 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1577   if (Ins.empty())
1578     return false;
1579
1580   return Ins[0].Flags.isSRet();
1581 }
1582
1583 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1584 /// by "Src" to address "Dst" with size and alignment information specified by
1585 /// the specific parameter attribute. The copy will be passed as a byval
1586 /// function parameter.
1587 static SDValue
1588 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1589                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1590                           DebugLoc dl) {
1591   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1592
1593   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1594                        /*isVolatile*/false, /*AlwaysInline=*/true,
1595                        MachinePointerInfo(), MachinePointerInfo());
1596 }
1597
1598 /// IsTailCallConvention - Return true if the calling convention is one that
1599 /// supports tail call optimization.
1600 static bool IsTailCallConvention(CallingConv::ID CC) {
1601   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1602 }
1603
1604 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1605 /// a tailcall target by changing its ABI.
1606 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1607   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1608 }
1609
1610 SDValue
1611 X86TargetLowering::LowerMemArgument(SDValue Chain,
1612                                     CallingConv::ID CallConv,
1613                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1614                                     DebugLoc dl, SelectionDAG &DAG,
1615                                     const CCValAssign &VA,
1616                                     MachineFrameInfo *MFI,
1617                                     unsigned i) const {
1618   // Create the nodes corresponding to a load from this parameter slot.
1619   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1620   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1621   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1622   EVT ValVT;
1623
1624   // If value is passed by pointer we have address passed instead of the value
1625   // itself.
1626   if (VA.getLocInfo() == CCValAssign::Indirect)
1627     ValVT = VA.getLocVT();
1628   else
1629     ValVT = VA.getValVT();
1630
1631   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1632   // changed with more analysis.
1633   // In case of tail call optimization mark all arguments mutable. Since they
1634   // could be overwritten by lowering of arguments in case of a tail call.
1635   if (Flags.isByVal()) {
1636     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1637                                     VA.getLocMemOffset(), isImmutable);
1638     return DAG.getFrameIndex(FI, getPointerTy());
1639   } else {
1640     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1641                                     VA.getLocMemOffset(), isImmutable);
1642     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1643     return DAG.getLoad(ValVT, dl, Chain, FIN,
1644                        MachinePointerInfo::getFixedStack(FI),
1645                        false, false, 0);
1646   }
1647 }
1648
1649 SDValue
1650 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1651                                         CallingConv::ID CallConv,
1652                                         bool isVarArg,
1653                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1654                                         DebugLoc dl,
1655                                         SelectionDAG &DAG,
1656                                         SmallVectorImpl<SDValue> &InVals)
1657                                           const {
1658   MachineFunction &MF = DAG.getMachineFunction();
1659   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1660
1661   const Function* Fn = MF.getFunction();
1662   if (Fn->hasExternalLinkage() &&
1663       Subtarget->isTargetCygMing() &&
1664       Fn->getName() == "main")
1665     FuncInfo->setForceFramePointer(true);
1666
1667   MachineFrameInfo *MFI = MF.getFrameInfo();
1668   bool Is64Bit = Subtarget->is64Bit();
1669   bool IsWin64 = Subtarget->isTargetWin64();
1670
1671   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1672          "Var args not supported with calling convention fastcc or ghc");
1673
1674   // Assign locations to all of the incoming arguments.
1675   SmallVector<CCValAssign, 16> ArgLocs;
1676   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1677                  ArgLocs, *DAG.getContext());
1678
1679   // Allocate shadow area for Win64
1680   if (IsWin64) {
1681     CCInfo.AllocateStack(32, 8);
1682   }
1683
1684   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1685
1686   unsigned LastVal = ~0U;
1687   SDValue ArgValue;
1688   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1689     CCValAssign &VA = ArgLocs[i];
1690     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1691     // places.
1692     assert(VA.getValNo() != LastVal &&
1693            "Don't support value assigned to multiple locs yet");
1694     LastVal = VA.getValNo();
1695
1696     if (VA.isRegLoc()) {
1697       EVT RegVT = VA.getLocVT();
1698       TargetRegisterClass *RC = NULL;
1699       if (RegVT == MVT::i32)
1700         RC = X86::GR32RegisterClass;
1701       else if (Is64Bit && RegVT == MVT::i64)
1702         RC = X86::GR64RegisterClass;
1703       else if (RegVT == MVT::f32)
1704         RC = X86::FR32RegisterClass;
1705       else if (RegVT == MVT::f64)
1706         RC = X86::FR64RegisterClass;
1707       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1708         RC = X86::VR256RegisterClass;
1709       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1710         RC = X86::VR128RegisterClass;
1711       else if (RegVT == MVT::x86mmx)
1712         RC = X86::VR64RegisterClass;
1713       else
1714         llvm_unreachable("Unknown argument type!");
1715
1716       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC, dl);
1717       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1718
1719       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1720       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1721       // right size.
1722       if (VA.getLocInfo() == CCValAssign::SExt)
1723         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1724                                DAG.getValueType(VA.getValVT()));
1725       else if (VA.getLocInfo() == CCValAssign::ZExt)
1726         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1727                                DAG.getValueType(VA.getValVT()));
1728       else if (VA.getLocInfo() == CCValAssign::BCvt)
1729         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1730
1731       if (VA.isExtInLoc()) {
1732         // Handle MMX values passed in XMM regs.
1733         if (RegVT.isVector()) {
1734           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1735                                  ArgValue);
1736         } else
1737           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1738       }
1739     } else {
1740       assert(VA.isMemLoc());
1741       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1742     }
1743
1744     // If value is passed via pointer - do a load.
1745     if (VA.getLocInfo() == CCValAssign::Indirect)
1746       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1747                              MachinePointerInfo(), false, false, 0);
1748
1749     InVals.push_back(ArgValue);
1750   }
1751
1752   // The x86-64 ABI for returning structs by value requires that we copy
1753   // the sret argument into %rax for the return. Save the argument into
1754   // a virtual register so that we can access it from the return points.
1755   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1756     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1757     unsigned Reg = FuncInfo->getSRetReturnReg();
1758     if (!Reg) {
1759       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1760       FuncInfo->setSRetReturnReg(Reg);
1761     }
1762     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1763     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1764   }
1765
1766   unsigned StackSize = CCInfo.getNextStackOffset();
1767   // Align stack specially for tail calls.
1768   if (FuncIsMadeTailCallSafe(CallConv))
1769     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1770
1771   // If the function takes variable number of arguments, make a frame index for
1772   // the start of the first vararg value... for expansion of llvm.va_start.
1773   if (isVarArg) {
1774     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1775                     CallConv != CallingConv::X86_ThisCall))) {
1776       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1777     }
1778     if (Is64Bit) {
1779       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1780
1781       // FIXME: We should really autogenerate these arrays
1782       static const unsigned GPR64ArgRegsWin64[] = {
1783         X86::RCX, X86::RDX, X86::R8,  X86::R9
1784       };
1785       static const unsigned GPR64ArgRegs64Bit[] = {
1786         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1787       };
1788       static const unsigned XMMArgRegs64Bit[] = {
1789         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1790         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1791       };
1792       const unsigned *GPR64ArgRegs;
1793       unsigned NumXMMRegs = 0;
1794
1795       if (IsWin64) {
1796         // The XMM registers which might contain var arg parameters are shadowed
1797         // in their paired GPR.  So we only need to save the GPR to their home
1798         // slots.
1799         TotalNumIntRegs = 4;
1800         GPR64ArgRegs = GPR64ArgRegsWin64;
1801       } else {
1802         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1803         GPR64ArgRegs = GPR64ArgRegs64Bit;
1804
1805         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1806       }
1807       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1808                                                        TotalNumIntRegs);
1809
1810       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1811       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1812              "SSE register cannot be used when SSE is disabled!");
1813       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1814              "SSE register cannot be used when SSE is disabled!");
1815       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1816         // Kernel mode asks for SSE to be disabled, so don't push them
1817         // on the stack.
1818         TotalNumXMMRegs = 0;
1819
1820       if (IsWin64) {
1821         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1822         // Get to the caller-allocated home save location.  Add 8 to account
1823         // for the return address.
1824         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1825         FuncInfo->setRegSaveFrameIndex(
1826           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1827         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1828       } else {
1829         // For X86-64, if there are vararg parameters that are passed via
1830         // registers, then we must store them to their spots on the stack so they
1831         // may be loaded by deferencing the result of va_next.
1832         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1833         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1834         FuncInfo->setRegSaveFrameIndex(
1835           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1836                                false));
1837       }
1838
1839       // Store the integer parameter registers.
1840       SmallVector<SDValue, 8> MemOps;
1841       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1842                                         getPointerTy());
1843       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1844       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1845         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1846                                   DAG.getIntPtrConstant(Offset));
1847         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1848                                      X86::GR64RegisterClass, dl);
1849         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1850         SDValue Store =
1851           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1852                        MachinePointerInfo::getFixedStack(
1853                          FuncInfo->getRegSaveFrameIndex(), Offset),
1854                        false, false, 0);
1855         MemOps.push_back(Store);
1856         Offset += 8;
1857       }
1858
1859       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1860         // Now store the XMM (fp + vector) parameter registers.
1861         SmallVector<SDValue, 11> SaveXMMOps;
1862         SaveXMMOps.push_back(Chain);
1863
1864         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass, dl);
1865         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1866         SaveXMMOps.push_back(ALVal);
1867
1868         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1869                                FuncInfo->getRegSaveFrameIndex()));
1870         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1871                                FuncInfo->getVarArgsFPOffset()));
1872
1873         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1874           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1875                                        X86::VR128RegisterClass, dl);
1876           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1877           SaveXMMOps.push_back(Val);
1878         }
1879         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1880                                      MVT::Other,
1881                                      &SaveXMMOps[0], SaveXMMOps.size()));
1882       }
1883
1884       if (!MemOps.empty())
1885         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1886                             &MemOps[0], MemOps.size());
1887     }
1888   }
1889
1890   // Some CCs need callee pop.
1891   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1892     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1893   } else {
1894     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1895     // If this is an sret function, the return should pop the hidden pointer.
1896     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1897       FuncInfo->setBytesToPopOnReturn(4);
1898   }
1899
1900   if (!Is64Bit) {
1901     // RegSaveFrameIndex is X86-64 only.
1902     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1903     if (CallConv == CallingConv::X86_FastCall ||
1904         CallConv == CallingConv::X86_ThisCall)
1905       // fastcc functions can't have varargs.
1906       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1907   }
1908
1909   return Chain;
1910 }
1911
1912 SDValue
1913 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1914                                     SDValue StackPtr, SDValue Arg,
1915                                     DebugLoc dl, SelectionDAG &DAG,
1916                                     const CCValAssign &VA,
1917                                     ISD::ArgFlagsTy Flags) const {
1918   unsigned LocMemOffset = VA.getLocMemOffset();
1919   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1920   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1921   if (Flags.isByVal())
1922     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1923
1924   return DAG.getStore(Chain, dl, Arg, PtrOff,
1925                       MachinePointerInfo::getStack(LocMemOffset),
1926                       false, false, 0);
1927 }
1928
1929 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1930 /// optimization is performed and it is required.
1931 SDValue
1932 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1933                                            SDValue &OutRetAddr, SDValue Chain,
1934                                            bool IsTailCall, bool Is64Bit,
1935                                            int FPDiff, DebugLoc dl) const {
1936   // Adjust the Return address stack slot.
1937   EVT VT = getPointerTy();
1938   OutRetAddr = getReturnAddressFrameIndex(DAG);
1939
1940   // Load the "old" Return address.
1941   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1942                            false, false, 0);
1943   return SDValue(OutRetAddr.getNode(), 1);
1944 }
1945
1946 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1947 /// optimization is performed and it is required (FPDiff!=0).
1948 static SDValue
1949 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1950                          SDValue Chain, SDValue RetAddrFrIdx,
1951                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1952   // Store the return address to the appropriate stack slot.
1953   if (!FPDiff) return Chain;
1954   // Calculate the new stack slot for the return address.
1955   int SlotSize = Is64Bit ? 8 : 4;
1956   int NewReturnAddrFI =
1957     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1958   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1959   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1960   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1961                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1962                        false, false, 0);
1963   return Chain;
1964 }
1965
1966 SDValue
1967 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1968                              CallingConv::ID CallConv, bool isVarArg,
1969                              bool &isTailCall,
1970                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1971                              const SmallVectorImpl<SDValue> &OutVals,
1972                              const SmallVectorImpl<ISD::InputArg> &Ins,
1973                              DebugLoc dl, SelectionDAG &DAG,
1974                              SmallVectorImpl<SDValue> &InVals) const {
1975   MachineFunction &MF = DAG.getMachineFunction();
1976   bool Is64Bit        = Subtarget->is64Bit();
1977   bool IsWin64        = Subtarget->isTargetWin64();
1978   bool IsStructRet    = CallIsStructReturn(Outs);
1979   bool IsSibcall      = false;
1980
1981   if (isTailCall) {
1982     // Check if it's really possible to do a tail call.
1983     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1984                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1985                                                    Outs, OutVals, Ins, DAG);
1986
1987     // Sibcalls are automatically detected tailcalls which do not require
1988     // ABI changes.
1989     if (!GuaranteedTailCallOpt && isTailCall)
1990       IsSibcall = true;
1991
1992     if (isTailCall)
1993       ++NumTailCalls;
1994   }
1995
1996   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1997          "Var args not supported with calling convention fastcc or ghc");
1998
1999   // Analyze operands of the call, assigning locations to each operand.
2000   SmallVector<CCValAssign, 16> ArgLocs;
2001   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
2002                  ArgLocs, *DAG.getContext());
2003
2004   // Allocate shadow area for Win64
2005   if (IsWin64) {
2006     CCInfo.AllocateStack(32, 8);
2007   }
2008
2009   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2010
2011   // Get a count of how many bytes are to be pushed on the stack.
2012   unsigned NumBytes = CCInfo.getNextStackOffset();
2013   if (IsSibcall)
2014     // This is a sibcall. The memory operands are available in caller's
2015     // own caller's stack.
2016     NumBytes = 0;
2017   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2018     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2019
2020   int FPDiff = 0;
2021   if (isTailCall && !IsSibcall) {
2022     // Lower arguments at fp - stackoffset + fpdiff.
2023     unsigned NumBytesCallerPushed =
2024       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2025     FPDiff = NumBytesCallerPushed - NumBytes;
2026
2027     // Set the delta of movement of the returnaddr stackslot.
2028     // But only set if delta is greater than previous delta.
2029     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2030       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2031   }
2032
2033   if (!IsSibcall)
2034     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2035
2036   SDValue RetAddrFrIdx;
2037   // Load return adress for tail calls.
2038   if (isTailCall && FPDiff)
2039     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2040                                     Is64Bit, FPDiff, dl);
2041
2042   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2043   SmallVector<SDValue, 8> MemOpChains;
2044   SDValue StackPtr;
2045
2046   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2047   // of tail call optimization arguments are handle later.
2048   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2049     CCValAssign &VA = ArgLocs[i];
2050     EVT RegVT = VA.getLocVT();
2051     SDValue Arg = OutVals[i];
2052     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2053     bool isByVal = Flags.isByVal();
2054
2055     // Promote the value if needed.
2056     switch (VA.getLocInfo()) {
2057     default: llvm_unreachable("Unknown loc info!");
2058     case CCValAssign::Full: break;
2059     case CCValAssign::SExt:
2060       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2061       break;
2062     case CCValAssign::ZExt:
2063       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2064       break;
2065     case CCValAssign::AExt:
2066       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2067         // Special case: passing MMX values in XMM registers.
2068         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2069         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2070         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2071       } else
2072         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2073       break;
2074     case CCValAssign::BCvt:
2075       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2076       break;
2077     case CCValAssign::Indirect: {
2078       // Store the argument.
2079       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2080       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2081       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2082                            MachinePointerInfo::getFixedStack(FI),
2083                            false, false, 0);
2084       Arg = SpillSlot;
2085       break;
2086     }
2087     }
2088
2089     if (VA.isRegLoc()) {
2090       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2091       if (isVarArg && IsWin64) {
2092         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2093         // shadow reg if callee is a varargs function.
2094         unsigned ShadowReg = 0;
2095         switch (VA.getLocReg()) {
2096         case X86::XMM0: ShadowReg = X86::RCX; break;
2097         case X86::XMM1: ShadowReg = X86::RDX; break;
2098         case X86::XMM2: ShadowReg = X86::R8; break;
2099         case X86::XMM3: ShadowReg = X86::R9; break;
2100         }
2101         if (ShadowReg)
2102           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2103       }
2104     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2105       assert(VA.isMemLoc());
2106       if (StackPtr.getNode() == 0)
2107         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2108       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2109                                              dl, DAG, VA, Flags));
2110     }
2111   }
2112
2113   if (!MemOpChains.empty())
2114     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115                         &MemOpChains[0], MemOpChains.size());
2116
2117   // Build a sequence of copy-to-reg nodes chained together with token chain
2118   // and flag operands which copy the outgoing args into registers.
2119   SDValue InFlag;
2120   // Tail call byval lowering might overwrite argument registers so in case of
2121   // tail call optimization the copies to registers are lowered later.
2122   if (!isTailCall)
2123     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2124       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2125                                RegsToPass[i].second, InFlag);
2126       InFlag = Chain.getValue(1);
2127     }
2128
2129   if (Subtarget->isPICStyleGOT()) {
2130     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2131     // GOT pointer.
2132     if (!isTailCall) {
2133       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2134                                DAG.getNode(X86ISD::GlobalBaseReg,
2135                                            DebugLoc(), getPointerTy()),
2136                                InFlag);
2137       InFlag = Chain.getValue(1);
2138     } else {
2139       // If we are tail calling and generating PIC/GOT style code load the
2140       // address of the callee into ECX. The value in ecx is used as target of
2141       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2142       // for tail calls on PIC/GOT architectures. Normally we would just put the
2143       // address of GOT into ebx and then call target@PLT. But for tail calls
2144       // ebx would be restored (since ebx is callee saved) before jumping to the
2145       // target@PLT.
2146
2147       // Note: The actual moving to ECX is done further down.
2148       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2149       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2150           !G->getGlobal()->hasProtectedVisibility())
2151         Callee = LowerGlobalAddress(Callee, DAG);
2152       else if (isa<ExternalSymbolSDNode>(Callee))
2153         Callee = LowerExternalSymbol(Callee, DAG);
2154     }
2155   }
2156
2157   if (Is64Bit && isVarArg && !IsWin64) {
2158     // From AMD64 ABI document:
2159     // For calls that may call functions that use varargs or stdargs
2160     // (prototype-less calls or calls to functions containing ellipsis (...) in
2161     // the declaration) %al is used as hidden argument to specify the number
2162     // of SSE registers used. The contents of %al do not need to match exactly
2163     // the number of registers, but must be an ubound on the number of SSE
2164     // registers used and is in the range 0 - 8 inclusive.
2165
2166     // Count the number of XMM registers allocated.
2167     static const unsigned XMMArgRegs[] = {
2168       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2169       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2170     };
2171     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2172     assert((Subtarget->hasXMM() || !NumXMMRegs)
2173            && "SSE registers cannot be used when SSE is disabled");
2174
2175     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2176                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2177     InFlag = Chain.getValue(1);
2178   }
2179
2180
2181   // For tail calls lower the arguments to the 'real' stack slot.
2182   if (isTailCall) {
2183     // Force all the incoming stack arguments to be loaded from the stack
2184     // before any new outgoing arguments are stored to the stack, because the
2185     // outgoing stack slots may alias the incoming argument stack slots, and
2186     // the alias isn't otherwise explicit. This is slightly more conservative
2187     // than necessary, because it means that each store effectively depends
2188     // on every argument instead of just those arguments it would clobber.
2189     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2190
2191     SmallVector<SDValue, 8> MemOpChains2;
2192     SDValue FIN;
2193     int FI = 0;
2194     // Do not flag preceeding copytoreg stuff together with the following stuff.
2195     InFlag = SDValue();
2196     if (GuaranteedTailCallOpt) {
2197       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2198         CCValAssign &VA = ArgLocs[i];
2199         if (VA.isRegLoc())
2200           continue;
2201         assert(VA.isMemLoc());
2202         SDValue Arg = OutVals[i];
2203         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2204         // Create frame index.
2205         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2206         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2207         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2208         FIN = DAG.getFrameIndex(FI, getPointerTy());
2209
2210         if (Flags.isByVal()) {
2211           // Copy relative to framepointer.
2212           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2213           if (StackPtr.getNode() == 0)
2214             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2215                                           getPointerTy());
2216           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2217
2218           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2219                                                            ArgChain,
2220                                                            Flags, DAG, dl));
2221         } else {
2222           // Store relative to framepointer.
2223           MemOpChains2.push_back(
2224             DAG.getStore(ArgChain, dl, Arg, FIN,
2225                          MachinePointerInfo::getFixedStack(FI),
2226                          false, false, 0));
2227         }
2228       }
2229     }
2230
2231     if (!MemOpChains2.empty())
2232       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2233                           &MemOpChains2[0], MemOpChains2.size());
2234
2235     // Copy arguments to their registers.
2236     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2237       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2238                                RegsToPass[i].second, InFlag);
2239       InFlag = Chain.getValue(1);
2240     }
2241     InFlag =SDValue();
2242
2243     // Store the return address to the appropriate stack slot.
2244     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2245                                      FPDiff, dl);
2246   }
2247
2248   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2249     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2250     // In the 64-bit large code model, we have to make all calls
2251     // through a register, since the call instruction's 32-bit
2252     // pc-relative offset may not be large enough to hold the whole
2253     // address.
2254   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2255     // If the callee is a GlobalAddress node (quite common, every direct call
2256     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2257     // it.
2258
2259     // We should use extra load for direct calls to dllimported functions in
2260     // non-JIT mode.
2261     const GlobalValue *GV = G->getGlobal();
2262     if (!GV->hasDLLImportLinkage()) {
2263       unsigned char OpFlags = 0;
2264
2265       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2266       // external symbols most go through the PLT in PIC mode.  If the symbol
2267       // has hidden or protected visibility, or if it is static or local, then
2268       // we don't need to use the PLT - we can directly call it.
2269       if (Subtarget->isTargetELF() &&
2270           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2271           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2272         OpFlags = X86II::MO_PLT;
2273       } else if (Subtarget->isPICStyleStubAny() &&
2274                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2275                  Subtarget->getDarwinVers() < 9) {
2276         // PC-relative references to external symbols should go through $stub,
2277         // unless we're building with the leopard linker or later, which
2278         // automatically synthesizes these stubs.
2279         OpFlags = X86II::MO_DARWIN_STUB;
2280       }
2281
2282       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2283                                           G->getOffset(), OpFlags);
2284     }
2285   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2286     unsigned char OpFlags = 0;
2287
2288     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2289     // external symbols should go through the PLT.
2290     if (Subtarget->isTargetELF() &&
2291         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2292       OpFlags = X86II::MO_PLT;
2293     } else if (Subtarget->isPICStyleStubAny() &&
2294                Subtarget->getDarwinVers() < 9) {
2295       // PC-relative references to external symbols should go through $stub,
2296       // unless we're building with the leopard linker or later, which
2297       // automatically synthesizes these stubs.
2298       OpFlags = X86II::MO_DARWIN_STUB;
2299     }
2300
2301     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2302                                          OpFlags);
2303   }
2304
2305   // Returns a chain & a flag for retval copy to use.
2306   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2307   SmallVector<SDValue, 8> Ops;
2308
2309   if (!IsSibcall && isTailCall) {
2310     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2311                            DAG.getIntPtrConstant(0, true), InFlag);
2312     InFlag = Chain.getValue(1);
2313   }
2314
2315   Ops.push_back(Chain);
2316   Ops.push_back(Callee);
2317
2318   if (isTailCall)
2319     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2320
2321   // Add argument registers to the end of the list so that they are known live
2322   // into the call.
2323   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2324     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2325                                   RegsToPass[i].second.getValueType()));
2326
2327   // Add an implicit use GOT pointer in EBX.
2328   if (!isTailCall && Subtarget->isPICStyleGOT())
2329     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2330
2331   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2332   if (Is64Bit && isVarArg && !IsWin64)
2333     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2334
2335   if (InFlag.getNode())
2336     Ops.push_back(InFlag);
2337
2338   if (isTailCall) {
2339     // We used to do:
2340     //// If this is the first return lowered for this function, add the regs
2341     //// to the liveout set for the function.
2342     // This isn't right, although it's probably harmless on x86; liveouts
2343     // should be computed from returns not tail calls.  Consider a void
2344     // function making a tail call to a function returning int.
2345     return DAG.getNode(X86ISD::TC_RETURN, dl,
2346                        NodeTys, &Ops[0], Ops.size());
2347   }
2348
2349   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2350   InFlag = Chain.getValue(1);
2351
2352   // Create the CALLSEQ_END node.
2353   unsigned NumBytesForCalleeToPush;
2354   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2355     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2356   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2357     // If this is a call to a struct-return function, the callee
2358     // pops the hidden struct pointer, so we have to push it back.
2359     // This is common for Darwin/X86, Linux & Mingw32 targets.
2360     NumBytesForCalleeToPush = 4;
2361   else
2362     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2363
2364   // Returns a flag for retval copy to use.
2365   if (!IsSibcall) {
2366     Chain = DAG.getCALLSEQ_END(Chain,
2367                                DAG.getIntPtrConstant(NumBytes, true),
2368                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2369                                                      true),
2370                                InFlag);
2371     InFlag = Chain.getValue(1);
2372   }
2373
2374   // Handle result values, copying them out of physregs into vregs that we
2375   // return.
2376   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2377                          Ins, dl, DAG, InVals);
2378 }
2379
2380
2381 //===----------------------------------------------------------------------===//
2382 //                Fast Calling Convention (tail call) implementation
2383 //===----------------------------------------------------------------------===//
2384
2385 //  Like std call, callee cleans arguments, convention except that ECX is
2386 //  reserved for storing the tail called function address. Only 2 registers are
2387 //  free for argument passing (inreg). Tail call optimization is performed
2388 //  provided:
2389 //                * tailcallopt is enabled
2390 //                * caller/callee are fastcc
2391 //  On X86_64 architecture with GOT-style position independent code only local
2392 //  (within module) calls are supported at the moment.
2393 //  To keep the stack aligned according to platform abi the function
2394 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2395 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2396 //  If a tail called function callee has more arguments than the caller the
2397 //  caller needs to make sure that there is room to move the RETADDR to. This is
2398 //  achieved by reserving an area the size of the argument delta right after the
2399 //  original REtADDR, but before the saved framepointer or the spilled registers
2400 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2401 //  stack layout:
2402 //    arg1
2403 //    arg2
2404 //    RETADDR
2405 //    [ new RETADDR
2406 //      move area ]
2407 //    (possible EBP)
2408 //    ESI
2409 //    EDI
2410 //    local1 ..
2411
2412 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2413 /// for a 16 byte align requirement.
2414 unsigned
2415 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2416                                                SelectionDAG& DAG) const {
2417   MachineFunction &MF = DAG.getMachineFunction();
2418   const TargetMachine &TM = MF.getTarget();
2419   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2420   unsigned StackAlignment = TFI.getStackAlignment();
2421   uint64_t AlignMask = StackAlignment - 1;
2422   int64_t Offset = StackSize;
2423   uint64_t SlotSize = TD->getPointerSize();
2424   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2425     // Number smaller than 12 so just add the difference.
2426     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2427   } else {
2428     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2429     Offset = ((~AlignMask) & Offset) + StackAlignment +
2430       (StackAlignment-SlotSize);
2431   }
2432   return Offset;
2433 }
2434
2435 /// MatchingStackOffset - Return true if the given stack call argument is
2436 /// already available in the same position (relatively) of the caller's
2437 /// incoming argument stack.
2438 static
2439 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2440                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2441                          const X86InstrInfo *TII) {
2442   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2443   int FI = INT_MAX;
2444   if (Arg.getOpcode() == ISD::CopyFromReg) {
2445     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2446     if (!TargetRegisterInfo::isVirtualRegister(VR))
2447       return false;
2448     MachineInstr *Def = MRI->getVRegDef(VR);
2449     if (!Def)
2450       return false;
2451     if (!Flags.isByVal()) {
2452       if (!TII->isLoadFromStackSlot(Def, FI))
2453         return false;
2454     } else {
2455       unsigned Opcode = Def->getOpcode();
2456       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2457           Def->getOperand(1).isFI()) {
2458         FI = Def->getOperand(1).getIndex();
2459         Bytes = Flags.getByValSize();
2460       } else
2461         return false;
2462     }
2463   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2464     if (Flags.isByVal())
2465       // ByVal argument is passed in as a pointer but it's now being
2466       // dereferenced. e.g.
2467       // define @foo(%struct.X* %A) {
2468       //   tail call @bar(%struct.X* byval %A)
2469       // }
2470       return false;
2471     SDValue Ptr = Ld->getBasePtr();
2472     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2473     if (!FINode)
2474       return false;
2475     FI = FINode->getIndex();
2476   } else
2477     return false;
2478
2479   assert(FI != INT_MAX);
2480   if (!MFI->isFixedObjectIndex(FI))
2481     return false;
2482   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2483 }
2484
2485 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2486 /// for tail call optimization. Targets which want to do tail call
2487 /// optimization should implement this function.
2488 bool
2489 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2490                                                      CallingConv::ID CalleeCC,
2491                                                      bool isVarArg,
2492                                                      bool isCalleeStructRet,
2493                                                      bool isCallerStructRet,
2494                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2495                                     const SmallVectorImpl<SDValue> &OutVals,
2496                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2497                                                      SelectionDAG& DAG) const {
2498   if (!IsTailCallConvention(CalleeCC) &&
2499       CalleeCC != CallingConv::C)
2500     return false;
2501
2502   // If -tailcallopt is specified, make fastcc functions tail-callable.
2503   const MachineFunction &MF = DAG.getMachineFunction();
2504   const Function *CallerF = DAG.getMachineFunction().getFunction();
2505   CallingConv::ID CallerCC = CallerF->getCallingConv();
2506   bool CCMatch = CallerCC == CalleeCC;
2507
2508   if (GuaranteedTailCallOpt) {
2509     if (IsTailCallConvention(CalleeCC) && CCMatch)
2510       return true;
2511     return false;
2512   }
2513
2514   // Look for obvious safe cases to perform tail call optimization that do not
2515   // require ABI changes. This is what gcc calls sibcall.
2516
2517   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2518   // emit a special epilogue.
2519   if (RegInfo->needsStackRealignment(MF))
2520     return false;
2521
2522   // Do not sibcall optimize vararg calls unless the call site is not passing
2523   // any arguments.
2524   if (isVarArg && !Outs.empty())
2525     return false;
2526
2527   // Also avoid sibcall optimization if either caller or callee uses struct
2528   // return semantics.
2529   if (isCalleeStructRet || isCallerStructRet)
2530     return false;
2531
2532   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2533   // Therefore if it's not used by the call it is not safe to optimize this into
2534   // a sibcall.
2535   bool Unused = false;
2536   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2537     if (!Ins[i].Used) {
2538       Unused = true;
2539       break;
2540     }
2541   }
2542   if (Unused) {
2543     SmallVector<CCValAssign, 16> RVLocs;
2544     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2545                    RVLocs, *DAG.getContext());
2546     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2547     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2548       CCValAssign &VA = RVLocs[i];
2549       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2550         return false;
2551     }
2552   }
2553
2554   // If the calling conventions do not match, then we'd better make sure the
2555   // results are returned in the same way as what the caller expects.
2556   if (!CCMatch) {
2557     SmallVector<CCValAssign, 16> RVLocs1;
2558     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2559                     RVLocs1, *DAG.getContext());
2560     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2561
2562     SmallVector<CCValAssign, 16> RVLocs2;
2563     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2564                     RVLocs2, *DAG.getContext());
2565     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2566
2567     if (RVLocs1.size() != RVLocs2.size())
2568       return false;
2569     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2570       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2571         return false;
2572       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2573         return false;
2574       if (RVLocs1[i].isRegLoc()) {
2575         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2576           return false;
2577       } else {
2578         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2579           return false;
2580       }
2581     }
2582   }
2583
2584   // If the callee takes no arguments then go on to check the results of the
2585   // call.
2586   if (!Outs.empty()) {
2587     // Check if stack adjustment is needed. For now, do not do this if any
2588     // argument is passed on the stack.
2589     SmallVector<CCValAssign, 16> ArgLocs;
2590     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2591                    ArgLocs, *DAG.getContext());
2592
2593     // Allocate shadow area for Win64
2594     if (Subtarget->isTargetWin64()) {
2595       CCInfo.AllocateStack(32, 8);
2596     }
2597
2598     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2599     if (CCInfo.getNextStackOffset()) {
2600       MachineFunction &MF = DAG.getMachineFunction();
2601       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2602         return false;
2603
2604       // Check if the arguments are already laid out in the right way as
2605       // the caller's fixed stack objects.
2606       MachineFrameInfo *MFI = MF.getFrameInfo();
2607       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2608       const X86InstrInfo *TII =
2609         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2610       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2611         CCValAssign &VA = ArgLocs[i];
2612         SDValue Arg = OutVals[i];
2613         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2614         if (VA.getLocInfo() == CCValAssign::Indirect)
2615           return false;
2616         if (!VA.isRegLoc()) {
2617           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2618                                    MFI, MRI, TII))
2619             return false;
2620         }
2621       }
2622     }
2623
2624     // If the tailcall address may be in a register, then make sure it's
2625     // possible to register allocate for it. In 32-bit, the call address can
2626     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2627     // callee-saved registers are restored. These happen to be the same
2628     // registers used to pass 'inreg' arguments so watch out for those.
2629     if (!Subtarget->is64Bit() &&
2630         !isa<GlobalAddressSDNode>(Callee) &&
2631         !isa<ExternalSymbolSDNode>(Callee)) {
2632       unsigned NumInRegs = 0;
2633       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2634         CCValAssign &VA = ArgLocs[i];
2635         if (!VA.isRegLoc())
2636           continue;
2637         unsigned Reg = VA.getLocReg();
2638         switch (Reg) {
2639         default: break;
2640         case X86::EAX: case X86::EDX: case X86::ECX:
2641           if (++NumInRegs == 3)
2642             return false;
2643           break;
2644         }
2645       }
2646     }
2647   }
2648
2649   // An stdcall caller is expected to clean up its arguments; the callee
2650   // isn't going to do that.
2651   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2652     return false;
2653
2654   return true;
2655 }
2656
2657 FastISel *
2658 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2659   return X86::createFastISel(funcInfo);
2660 }
2661
2662
2663 //===----------------------------------------------------------------------===//
2664 //                           Other Lowering Hooks
2665 //===----------------------------------------------------------------------===//
2666
2667 static bool MayFoldLoad(SDValue Op) {
2668   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2669 }
2670
2671 static bool MayFoldIntoStore(SDValue Op) {
2672   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2673 }
2674
2675 static bool isTargetShuffle(unsigned Opcode) {
2676   switch(Opcode) {
2677   default: return false;
2678   case X86ISD::PSHUFD:
2679   case X86ISD::PSHUFHW:
2680   case X86ISD::PSHUFLW:
2681   case X86ISD::SHUFPD:
2682   case X86ISD::PALIGN:
2683   case X86ISD::SHUFPS:
2684   case X86ISD::MOVLHPS:
2685   case X86ISD::MOVLHPD:
2686   case X86ISD::MOVHLPS:
2687   case X86ISD::MOVLPS:
2688   case X86ISD::MOVLPD:
2689   case X86ISD::MOVSHDUP:
2690   case X86ISD::MOVSLDUP:
2691   case X86ISD::MOVDDUP:
2692   case X86ISD::MOVSS:
2693   case X86ISD::MOVSD:
2694   case X86ISD::UNPCKLPS:
2695   case X86ISD::UNPCKLPD:
2696   case X86ISD::PUNPCKLWD:
2697   case X86ISD::PUNPCKLBW:
2698   case X86ISD::PUNPCKLDQ:
2699   case X86ISD::PUNPCKLQDQ:
2700   case X86ISD::UNPCKHPS:
2701   case X86ISD::UNPCKHPD:
2702   case X86ISD::PUNPCKHWD:
2703   case X86ISD::PUNPCKHBW:
2704   case X86ISD::PUNPCKHDQ:
2705   case X86ISD::PUNPCKHQDQ:
2706     return true;
2707   }
2708   return false;
2709 }
2710
2711 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2712                                                SDValue V1, SelectionDAG &DAG) {
2713   switch(Opc) {
2714   default: llvm_unreachable("Unknown x86 shuffle node");
2715   case X86ISD::MOVSHDUP:
2716   case X86ISD::MOVSLDUP:
2717   case X86ISD::MOVDDUP:
2718     return DAG.getNode(Opc, dl, VT, V1);
2719   }
2720
2721   return SDValue();
2722 }
2723
2724 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2725                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2726   switch(Opc) {
2727   default: llvm_unreachable("Unknown x86 shuffle node");
2728   case X86ISD::PSHUFD:
2729   case X86ISD::PSHUFHW:
2730   case X86ISD::PSHUFLW:
2731     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2732   }
2733
2734   return SDValue();
2735 }
2736
2737 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2738                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2739   switch(Opc) {
2740   default: llvm_unreachable("Unknown x86 shuffle node");
2741   case X86ISD::PALIGN:
2742   case X86ISD::SHUFPD:
2743   case X86ISD::SHUFPS:
2744     return DAG.getNode(Opc, dl, VT, V1, V2,
2745                        DAG.getConstant(TargetMask, MVT::i8));
2746   }
2747   return SDValue();
2748 }
2749
2750 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2751                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2752   switch(Opc) {
2753   default: llvm_unreachable("Unknown x86 shuffle node");
2754   case X86ISD::MOVLHPS:
2755   case X86ISD::MOVLHPD:
2756   case X86ISD::MOVHLPS:
2757   case X86ISD::MOVLPS:
2758   case X86ISD::MOVLPD:
2759   case X86ISD::MOVSS:
2760   case X86ISD::MOVSD:
2761   case X86ISD::UNPCKLPS:
2762   case X86ISD::UNPCKLPD:
2763   case X86ISD::PUNPCKLWD:
2764   case X86ISD::PUNPCKLBW:
2765   case X86ISD::PUNPCKLDQ:
2766   case X86ISD::PUNPCKLQDQ:
2767   case X86ISD::UNPCKHPS:
2768   case X86ISD::UNPCKHPD:
2769   case X86ISD::PUNPCKHWD:
2770   case X86ISD::PUNPCKHBW:
2771   case X86ISD::PUNPCKHDQ:
2772   case X86ISD::PUNPCKHQDQ:
2773     return DAG.getNode(Opc, dl, VT, V1, V2);
2774   }
2775   return SDValue();
2776 }
2777
2778 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2779   MachineFunction &MF = DAG.getMachineFunction();
2780   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2781   int ReturnAddrIndex = FuncInfo->getRAIndex();
2782
2783   if (ReturnAddrIndex == 0) {
2784     // Set up a frame object for the return address.
2785     uint64_t SlotSize = TD->getPointerSize();
2786     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2787                                                            false);
2788     FuncInfo->setRAIndex(ReturnAddrIndex);
2789   }
2790
2791   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2792 }
2793
2794
2795 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2796                                        bool hasSymbolicDisplacement) {
2797   // Offset should fit into 32 bit immediate field.
2798   if (!isInt<32>(Offset))
2799     return false;
2800
2801   // If we don't have a symbolic displacement - we don't have any extra
2802   // restrictions.
2803   if (!hasSymbolicDisplacement)
2804     return true;
2805
2806   // FIXME: Some tweaks might be needed for medium code model.
2807   if (M != CodeModel::Small && M != CodeModel::Kernel)
2808     return false;
2809
2810   // For small code model we assume that latest object is 16MB before end of 31
2811   // bits boundary. We may also accept pretty large negative constants knowing
2812   // that all objects are in the positive half of address space.
2813   if (M == CodeModel::Small && Offset < 16*1024*1024)
2814     return true;
2815
2816   // For kernel code model we know that all object resist in the negative half
2817   // of 32bits address space. We may not accept negative offsets, since they may
2818   // be just off and we may accept pretty large positive ones.
2819   if (M == CodeModel::Kernel && Offset > 0)
2820     return true;
2821
2822   return false;
2823 }
2824
2825 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2826 /// specific condition code, returning the condition code and the LHS/RHS of the
2827 /// comparison to make.
2828 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2829                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2830   if (!isFP) {
2831     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2832       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2833         // X > -1   -> X == 0, jump !sign.
2834         RHS = DAG.getConstant(0, RHS.getValueType());
2835         return X86::COND_NS;
2836       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2837         // X < 0   -> X == 0, jump on sign.
2838         return X86::COND_S;
2839       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2840         // X < 1   -> X <= 0
2841         RHS = DAG.getConstant(0, RHS.getValueType());
2842         return X86::COND_LE;
2843       }
2844     }
2845
2846     switch (SetCCOpcode) {
2847     default: llvm_unreachable("Invalid integer condition!");
2848     case ISD::SETEQ:  return X86::COND_E;
2849     case ISD::SETGT:  return X86::COND_G;
2850     case ISD::SETGE:  return X86::COND_GE;
2851     case ISD::SETLT:  return X86::COND_L;
2852     case ISD::SETLE:  return X86::COND_LE;
2853     case ISD::SETNE:  return X86::COND_NE;
2854     case ISD::SETULT: return X86::COND_B;
2855     case ISD::SETUGT: return X86::COND_A;
2856     case ISD::SETULE: return X86::COND_BE;
2857     case ISD::SETUGE: return X86::COND_AE;
2858     }
2859   }
2860
2861   // First determine if it is required or is profitable to flip the operands.
2862
2863   // If LHS is a foldable load, but RHS is not, flip the condition.
2864   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2865       !ISD::isNON_EXTLoad(RHS.getNode())) {
2866     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2867     std::swap(LHS, RHS);
2868   }
2869
2870   switch (SetCCOpcode) {
2871   default: break;
2872   case ISD::SETOLT:
2873   case ISD::SETOLE:
2874   case ISD::SETUGT:
2875   case ISD::SETUGE:
2876     std::swap(LHS, RHS);
2877     break;
2878   }
2879
2880   // On a floating point condition, the flags are set as follows:
2881   // ZF  PF  CF   op
2882   //  0 | 0 | 0 | X > Y
2883   //  0 | 0 | 1 | X < Y
2884   //  1 | 0 | 0 | X == Y
2885   //  1 | 1 | 1 | unordered
2886   switch (SetCCOpcode) {
2887   default: llvm_unreachable("Condcode should be pre-legalized away");
2888   case ISD::SETUEQ:
2889   case ISD::SETEQ:   return X86::COND_E;
2890   case ISD::SETOLT:              // flipped
2891   case ISD::SETOGT:
2892   case ISD::SETGT:   return X86::COND_A;
2893   case ISD::SETOLE:              // flipped
2894   case ISD::SETOGE:
2895   case ISD::SETGE:   return X86::COND_AE;
2896   case ISD::SETUGT:              // flipped
2897   case ISD::SETULT:
2898   case ISD::SETLT:   return X86::COND_B;
2899   case ISD::SETUGE:              // flipped
2900   case ISD::SETULE:
2901   case ISD::SETLE:   return X86::COND_BE;
2902   case ISD::SETONE:
2903   case ISD::SETNE:   return X86::COND_NE;
2904   case ISD::SETUO:   return X86::COND_P;
2905   case ISD::SETO:    return X86::COND_NP;
2906   case ISD::SETOEQ:
2907   case ISD::SETUNE:  return X86::COND_INVALID;
2908   }
2909 }
2910
2911 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2912 /// code. Current x86 isa includes the following FP cmov instructions:
2913 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2914 static bool hasFPCMov(unsigned X86CC) {
2915   switch (X86CC) {
2916   default:
2917     return false;
2918   case X86::COND_B:
2919   case X86::COND_BE:
2920   case X86::COND_E:
2921   case X86::COND_P:
2922   case X86::COND_A:
2923   case X86::COND_AE:
2924   case X86::COND_NE:
2925   case X86::COND_NP:
2926     return true;
2927   }
2928 }
2929
2930 /// isFPImmLegal - Returns true if the target can instruction select the
2931 /// specified FP immediate natively. If false, the legalizer will
2932 /// materialize the FP immediate as a load from a constant pool.
2933 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2934   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2935     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2936       return true;
2937   }
2938   return false;
2939 }
2940
2941 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2942 /// the specified range (L, H].
2943 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2944   return (Val < 0) || (Val >= Low && Val < Hi);
2945 }
2946
2947 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2948 /// specified value.
2949 static bool isUndefOrEqual(int Val, int CmpVal) {
2950   if (Val < 0 || Val == CmpVal)
2951     return true;
2952   return false;
2953 }
2954
2955 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2956 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2957 /// the second operand.
2958 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2959   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2960     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2961   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2962     return (Mask[0] < 2 && Mask[1] < 2);
2963   return false;
2964 }
2965
2966 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2967   SmallVector<int, 8> M;
2968   N->getMask(M);
2969   return ::isPSHUFDMask(M, N->getValueType(0));
2970 }
2971
2972 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2973 /// is suitable for input to PSHUFHW.
2974 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2975   if (VT != MVT::v8i16)
2976     return false;
2977
2978   // Lower quadword copied in order or undef.
2979   for (int i = 0; i != 4; ++i)
2980     if (Mask[i] >= 0 && Mask[i] != i)
2981       return false;
2982
2983   // Upper quadword shuffled.
2984   for (int i = 4; i != 8; ++i)
2985     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2986       return false;
2987
2988   return true;
2989 }
2990
2991 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2992   SmallVector<int, 8> M;
2993   N->getMask(M);
2994   return ::isPSHUFHWMask(M, N->getValueType(0));
2995 }
2996
2997 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2998 /// is suitable for input to PSHUFLW.
2999 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3000   if (VT != MVT::v8i16)
3001     return false;
3002
3003   // Upper quadword copied in order.
3004   for (int i = 4; i != 8; ++i)
3005     if (Mask[i] >= 0 && Mask[i] != i)
3006       return false;
3007
3008   // Lower quadword shuffled.
3009   for (int i = 0; i != 4; ++i)
3010     if (Mask[i] >= 4)
3011       return false;
3012
3013   return true;
3014 }
3015
3016 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3017   SmallVector<int, 8> M;
3018   N->getMask(M);
3019   return ::isPSHUFLWMask(M, N->getValueType(0));
3020 }
3021
3022 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3023 /// is suitable for input to PALIGNR.
3024 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3025                           bool hasSSSE3) {
3026   int i, e = VT.getVectorNumElements();
3027
3028   // Do not handle v2i64 / v2f64 shuffles with palignr.
3029   if (e < 4 || !hasSSSE3)
3030     return false;
3031
3032   for (i = 0; i != e; ++i)
3033     if (Mask[i] >= 0)
3034       break;
3035
3036   // All undef, not a palignr.
3037   if (i == e)
3038     return false;
3039
3040   // Determine if it's ok to perform a palignr with only the LHS, since we
3041   // don't have access to the actual shuffle elements to see if RHS is undef.
3042   bool Unary = Mask[i] < (int)e;
3043   bool NeedsUnary = false;
3044
3045   int s = Mask[i] - i;
3046
3047   // Check the rest of the elements to see if they are consecutive.
3048   for (++i; i != e; ++i) {
3049     int m = Mask[i];
3050     if (m < 0)
3051       continue;
3052
3053     Unary = Unary && (m < (int)e);
3054     NeedsUnary = NeedsUnary || (m < s);
3055
3056     if (NeedsUnary && !Unary)
3057       return false;
3058     if (Unary && m != ((s+i) & (e-1)))
3059       return false;
3060     if (!Unary && m != (s+i))
3061       return false;
3062   }
3063   return true;
3064 }
3065
3066 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
3067   SmallVector<int, 8> M;
3068   N->getMask(M);
3069   return ::isPALIGNRMask(M, N->getValueType(0), true);
3070 }
3071
3072 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3073 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
3074 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3075   int NumElems = VT.getVectorNumElements();
3076   if (NumElems != 2 && NumElems != 4)
3077     return false;
3078
3079   int Half = NumElems / 2;
3080   for (int i = 0; i < Half; ++i)
3081     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3082       return false;
3083   for (int i = Half; i < NumElems; ++i)
3084     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3085       return false;
3086
3087   return true;
3088 }
3089
3090 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3091   SmallVector<int, 8> M;
3092   N->getMask(M);
3093   return ::isSHUFPMask(M, N->getValueType(0));
3094 }
3095
3096 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3097 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3098 /// half elements to come from vector 1 (which would equal the dest.) and
3099 /// the upper half to come from vector 2.
3100 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3101   int NumElems = VT.getVectorNumElements();
3102
3103   if (NumElems != 2 && NumElems != 4)
3104     return false;
3105
3106   int Half = NumElems / 2;
3107   for (int i = 0; i < Half; ++i)
3108     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3109       return false;
3110   for (int i = Half; i < NumElems; ++i)
3111     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3112       return false;
3113   return true;
3114 }
3115
3116 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3117   SmallVector<int, 8> M;
3118   N->getMask(M);
3119   return isCommutedSHUFPMask(M, N->getValueType(0));
3120 }
3121
3122 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3123 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3124 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3125   if (N->getValueType(0).getVectorNumElements() != 4)
3126     return false;
3127
3128   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3129   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3130          isUndefOrEqual(N->getMaskElt(1), 7) &&
3131          isUndefOrEqual(N->getMaskElt(2), 2) &&
3132          isUndefOrEqual(N->getMaskElt(3), 3);
3133 }
3134
3135 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3136 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3137 /// <2, 3, 2, 3>
3138 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3139   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3140
3141   if (NumElems != 4)
3142     return false;
3143
3144   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3145   isUndefOrEqual(N->getMaskElt(1), 3) &&
3146   isUndefOrEqual(N->getMaskElt(2), 2) &&
3147   isUndefOrEqual(N->getMaskElt(3), 3);
3148 }
3149
3150 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3151 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3152 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3153   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3154
3155   if (NumElems != 2 && NumElems != 4)
3156     return false;
3157
3158   for (unsigned i = 0; i < NumElems/2; ++i)
3159     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3160       return false;
3161
3162   for (unsigned i = NumElems/2; i < NumElems; ++i)
3163     if (!isUndefOrEqual(N->getMaskElt(i), i))
3164       return false;
3165
3166   return true;
3167 }
3168
3169 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3170 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3171 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3172   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3173
3174   if (NumElems != 2 && NumElems != 4)
3175     return false;
3176
3177   for (unsigned i = 0; i < NumElems/2; ++i)
3178     if (!isUndefOrEqual(N->getMaskElt(i), i))
3179       return false;
3180
3181   for (unsigned i = 0; i < NumElems/2; ++i)
3182     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3183       return false;
3184
3185   return true;
3186 }
3187
3188 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3189 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3190 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3191                          bool V2IsSplat = false) {
3192   int NumElts = VT.getVectorNumElements();
3193   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3194     return false;
3195
3196   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3197     int BitI  = Mask[i];
3198     int BitI1 = Mask[i+1];
3199     if (!isUndefOrEqual(BitI, j))
3200       return false;
3201     if (V2IsSplat) {
3202       if (!isUndefOrEqual(BitI1, NumElts))
3203         return false;
3204     } else {
3205       if (!isUndefOrEqual(BitI1, j + NumElts))
3206         return false;
3207     }
3208   }
3209   return true;
3210 }
3211
3212 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3213   SmallVector<int, 8> M;
3214   N->getMask(M);
3215   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3216 }
3217
3218 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3219 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3220 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3221                          bool V2IsSplat = false) {
3222   int NumElts = VT.getVectorNumElements();
3223   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3224     return false;
3225
3226   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3227     int BitI  = Mask[i];
3228     int BitI1 = Mask[i+1];
3229     if (!isUndefOrEqual(BitI, j + NumElts/2))
3230       return false;
3231     if (V2IsSplat) {
3232       if (isUndefOrEqual(BitI1, NumElts))
3233         return false;
3234     } else {
3235       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3236         return false;
3237     }
3238   }
3239   return true;
3240 }
3241
3242 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3243   SmallVector<int, 8> M;
3244   N->getMask(M);
3245   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3246 }
3247
3248 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3249 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3250 /// <0, 0, 1, 1>
3251 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3252   int NumElems = VT.getVectorNumElements();
3253   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3254     return false;
3255
3256   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3257     int BitI  = Mask[i];
3258     int BitI1 = Mask[i+1];
3259     if (!isUndefOrEqual(BitI, j))
3260       return false;
3261     if (!isUndefOrEqual(BitI1, j))
3262       return false;
3263   }
3264   return true;
3265 }
3266
3267 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3268   SmallVector<int, 8> M;
3269   N->getMask(M);
3270   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3271 }
3272
3273 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3274 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3275 /// <2, 2, 3, 3>
3276 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3277   int NumElems = VT.getVectorNumElements();
3278   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3279     return false;
3280
3281   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3282     int BitI  = Mask[i];
3283     int BitI1 = Mask[i+1];
3284     if (!isUndefOrEqual(BitI, j))
3285       return false;
3286     if (!isUndefOrEqual(BitI1, j))
3287       return false;
3288   }
3289   return true;
3290 }
3291
3292 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3293   SmallVector<int, 8> M;
3294   N->getMask(M);
3295   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3296 }
3297
3298 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3299 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3300 /// MOVSD, and MOVD, i.e. setting the lowest element.
3301 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3302   if (VT.getVectorElementType().getSizeInBits() < 32)
3303     return false;
3304
3305   int NumElts = VT.getVectorNumElements();
3306
3307   if (!isUndefOrEqual(Mask[0], NumElts))
3308     return false;
3309
3310   for (int i = 1; i < NumElts; ++i)
3311     if (!isUndefOrEqual(Mask[i], i))
3312       return false;
3313
3314   return true;
3315 }
3316
3317 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3318   SmallVector<int, 8> M;
3319   N->getMask(M);
3320   return ::isMOVLMask(M, N->getValueType(0));
3321 }
3322
3323 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3324 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3325 /// element of vector 2 and the other elements to come from vector 1 in order.
3326 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3327                                bool V2IsSplat = false, bool V2IsUndef = false) {
3328   int NumOps = VT.getVectorNumElements();
3329   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3330     return false;
3331
3332   if (!isUndefOrEqual(Mask[0], 0))
3333     return false;
3334
3335   for (int i = 1; i < NumOps; ++i)
3336     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3337           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3338           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3339       return false;
3340
3341   return true;
3342 }
3343
3344 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3345                            bool V2IsUndef = false) {
3346   SmallVector<int, 8> M;
3347   N->getMask(M);
3348   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3349 }
3350
3351 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3352 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3353 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3354   if (N->getValueType(0).getVectorNumElements() != 4)
3355     return false;
3356
3357   // Expect 1, 1, 3, 3
3358   for (unsigned i = 0; i < 2; ++i) {
3359     int Elt = N->getMaskElt(i);
3360     if (Elt >= 0 && Elt != 1)
3361       return false;
3362   }
3363
3364   bool HasHi = false;
3365   for (unsigned i = 2; i < 4; ++i) {
3366     int Elt = N->getMaskElt(i);
3367     if (Elt >= 0 && Elt != 3)
3368       return false;
3369     if (Elt == 3)
3370       HasHi = true;
3371   }
3372   // Don't use movshdup if it can be done with a shufps.
3373   // FIXME: verify that matching u, u, 3, 3 is what we want.
3374   return HasHi;
3375 }
3376
3377 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3378 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3379 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3380   if (N->getValueType(0).getVectorNumElements() != 4)
3381     return false;
3382
3383   // Expect 0, 0, 2, 2
3384   for (unsigned i = 0; i < 2; ++i)
3385     if (N->getMaskElt(i) > 0)
3386       return false;
3387
3388   bool HasHi = false;
3389   for (unsigned i = 2; i < 4; ++i) {
3390     int Elt = N->getMaskElt(i);
3391     if (Elt >= 0 && Elt != 2)
3392       return false;
3393     if (Elt == 2)
3394       HasHi = true;
3395   }
3396   // Don't use movsldup if it can be done with a shufps.
3397   return HasHi;
3398 }
3399
3400 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3401 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3402 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3403   int e = N->getValueType(0).getVectorNumElements() / 2;
3404
3405   for (int i = 0; i < e; ++i)
3406     if (!isUndefOrEqual(N->getMaskElt(i), i))
3407       return false;
3408   for (int i = 0; i < e; ++i)
3409     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3410       return false;
3411   return true;
3412 }
3413
3414 /// isVEXTRACTF128Index - Return true if the specified
3415 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3416 /// suitable for input to VEXTRACTF128.
3417 bool X86::isVEXTRACTF128Index(SDNode *N) {
3418   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3419     return false;
3420
3421   // The index should be aligned on a 128-bit boundary.
3422   uint64_t Index =
3423     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3424
3425   unsigned VL = N->getValueType(0).getVectorNumElements();
3426   unsigned VBits = N->getValueType(0).getSizeInBits();
3427   unsigned ElSize = VBits / VL;
3428   bool Result = (Index * ElSize) % 128 == 0;
3429
3430   return Result;
3431 }
3432
3433 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3434 /// operand specifies a subvector insert that is suitable for input to
3435 /// VINSERTF128.
3436 bool X86::isVINSERTF128Index(SDNode *N) {
3437   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3438     return false;
3439
3440   // The index should be aligned on a 128-bit boundary.
3441   uint64_t Index =
3442     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3443
3444   unsigned VL = N->getValueType(0).getVectorNumElements();
3445   unsigned VBits = N->getValueType(0).getSizeInBits();
3446   unsigned ElSize = VBits / VL;
3447   bool Result = (Index * ElSize) % 128 == 0;
3448
3449   return Result;
3450 }
3451
3452 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3453 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3454 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3455   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3456   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3457
3458   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3459   unsigned Mask = 0;
3460   for (int i = 0; i < NumOperands; ++i) {
3461     int Val = SVOp->getMaskElt(NumOperands-i-1);
3462     if (Val < 0) Val = 0;
3463     if (Val >= NumOperands) Val -= NumOperands;
3464     Mask |= Val;
3465     if (i != NumOperands - 1)
3466       Mask <<= Shift;
3467   }
3468   return Mask;
3469 }
3470
3471 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3472 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3473 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3474   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3475   unsigned Mask = 0;
3476   // 8 nodes, but we only care about the last 4.
3477   for (unsigned i = 7; i >= 4; --i) {
3478     int Val = SVOp->getMaskElt(i);
3479     if (Val >= 0)
3480       Mask |= (Val - 4);
3481     if (i != 4)
3482       Mask <<= 2;
3483   }
3484   return Mask;
3485 }
3486
3487 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3488 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3489 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3490   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3491   unsigned Mask = 0;
3492   // 8 nodes, but we only care about the first 4.
3493   for (int i = 3; i >= 0; --i) {
3494     int Val = SVOp->getMaskElt(i);
3495     if (Val >= 0)
3496       Mask |= Val;
3497     if (i != 0)
3498       Mask <<= 2;
3499   }
3500   return Mask;
3501 }
3502
3503 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3504 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3505 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3506   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3507   EVT VVT = N->getValueType(0);
3508   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3509   int Val = 0;
3510
3511   unsigned i, e;
3512   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3513     Val = SVOp->getMaskElt(i);
3514     if (Val >= 0)
3515       break;
3516   }
3517   return (Val - i) * EltSize;
3518 }
3519
3520 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3521 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3522 /// instructions.
3523 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3524   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3525     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3526
3527   uint64_t Index =
3528     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3529
3530   EVT VecVT = N->getOperand(0).getValueType();
3531   EVT ElVT = VecVT.getVectorElementType();
3532
3533   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3534
3535   return Index / NumElemsPerChunk;
3536 }
3537
3538 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3539 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3540 /// instructions.
3541 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3542   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3543     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3544
3545   uint64_t Index =
3546     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3547
3548   EVT VecVT = N->getValueType(0);
3549   EVT ElVT = VecVT.getVectorElementType();
3550
3551   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3552
3553   return Index / NumElemsPerChunk;
3554 }
3555
3556 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3557 /// constant +0.0.
3558 bool X86::isZeroNode(SDValue Elt) {
3559   return ((isa<ConstantSDNode>(Elt) &&
3560            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3561           (isa<ConstantFPSDNode>(Elt) &&
3562            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3563 }
3564
3565 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3566 /// their permute mask.
3567 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3568                                     SelectionDAG &DAG) {
3569   EVT VT = SVOp->getValueType(0);
3570   unsigned NumElems = VT.getVectorNumElements();
3571   SmallVector<int, 8> MaskVec;
3572
3573   for (unsigned i = 0; i != NumElems; ++i) {
3574     int idx = SVOp->getMaskElt(i);
3575     if (idx < 0)
3576       MaskVec.push_back(idx);
3577     else if (idx < (int)NumElems)
3578       MaskVec.push_back(idx + NumElems);
3579     else
3580       MaskVec.push_back(idx - NumElems);
3581   }
3582   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3583                               SVOp->getOperand(0), &MaskVec[0]);
3584 }
3585
3586 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3587 /// the two vector operands have swapped position.
3588 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3589   unsigned NumElems = VT.getVectorNumElements();
3590   for (unsigned i = 0; i != NumElems; ++i) {
3591     int idx = Mask[i];
3592     if (idx < 0)
3593       continue;
3594     else if (idx < (int)NumElems)
3595       Mask[i] = idx + NumElems;
3596     else
3597       Mask[i] = idx - NumElems;
3598   }
3599 }
3600
3601 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3602 /// match movhlps. The lower half elements should come from upper half of
3603 /// V1 (and in order), and the upper half elements should come from the upper
3604 /// half of V2 (and in order).
3605 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3606   if (Op->getValueType(0).getVectorNumElements() != 4)
3607     return false;
3608   for (unsigned i = 0, e = 2; i != e; ++i)
3609     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3610       return false;
3611   for (unsigned i = 2; i != 4; ++i)
3612     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3613       return false;
3614   return true;
3615 }
3616
3617 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3618 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3619 /// required.
3620 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3621   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3622     return false;
3623   N = N->getOperand(0).getNode();
3624   if (!ISD::isNON_EXTLoad(N))
3625     return false;
3626   if (LD)
3627     *LD = cast<LoadSDNode>(N);
3628   return true;
3629 }
3630
3631 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3632 /// match movlp{s|d}. The lower half elements should come from lower half of
3633 /// V1 (and in order), and the upper half elements should come from the upper
3634 /// half of V2 (and in order). And since V1 will become the source of the
3635 /// MOVLP, it must be either a vector load or a scalar load to vector.
3636 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3637                                ShuffleVectorSDNode *Op) {
3638   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3639     return false;
3640   // Is V2 is a vector load, don't do this transformation. We will try to use
3641   // load folding shufps op.
3642   if (ISD::isNON_EXTLoad(V2))
3643     return false;
3644
3645   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3646
3647   if (NumElems != 2 && NumElems != 4)
3648     return false;
3649   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3650     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3651       return false;
3652   for (unsigned i = NumElems/2; i != NumElems; ++i)
3653     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3654       return false;
3655   return true;
3656 }
3657
3658 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3659 /// all the same.
3660 static bool isSplatVector(SDNode *N) {
3661   if (N->getOpcode() != ISD::BUILD_VECTOR)
3662     return false;
3663
3664   SDValue SplatValue = N->getOperand(0);
3665   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3666     if (N->getOperand(i) != SplatValue)
3667       return false;
3668   return true;
3669 }
3670
3671 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3672 /// to an zero vector.
3673 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3674 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3675   SDValue V1 = N->getOperand(0);
3676   SDValue V2 = N->getOperand(1);
3677   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3678   for (unsigned i = 0; i != NumElems; ++i) {
3679     int Idx = N->getMaskElt(i);
3680     if (Idx >= (int)NumElems) {
3681       unsigned Opc = V2.getOpcode();
3682       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3683         continue;
3684       if (Opc != ISD::BUILD_VECTOR ||
3685           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3686         return false;
3687     } else if (Idx >= 0) {
3688       unsigned Opc = V1.getOpcode();
3689       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3690         continue;
3691       if (Opc != ISD::BUILD_VECTOR ||
3692           !X86::isZeroNode(V1.getOperand(Idx)))
3693         return false;
3694     }
3695   }
3696   return true;
3697 }
3698
3699 /// getZeroVector - Returns a vector of specified type with all zero elements.
3700 ///
3701 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3702                              DebugLoc dl) {
3703   assert(VT.isVector() && "Expected a vector type");
3704
3705   // Always build SSE zero vectors as <4 x i32> bitcasted
3706   // to their dest type. This ensures they get CSE'd.
3707   SDValue Vec;
3708   if (VT.getSizeInBits() == 128) {  // SSE
3709     if (HasSSE2) {  // SSE2
3710       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3711       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3712     } else { // SSE1
3713       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3714       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3715     }
3716   } else if (VT.getSizeInBits() == 256) { // AVX
3717     // 256-bit logic and arithmetic instructions in AVX are
3718     // all floating-point, no support for integer ops. Default
3719     // to emitting fp zeroed vectors then.
3720     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3721     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3722     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3723   }
3724   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3725 }
3726
3727 /// getOnesVector - Returns a vector of specified type with all bits set.
3728 ///
3729 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3730   assert(VT.isVector() && "Expected a vector type");
3731
3732   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3733   // type.  This ensures they get CSE'd.
3734   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3735   SDValue Vec;
3736   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3737   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3738 }
3739
3740
3741 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3742 /// that point to V2 points to its first element.
3743 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3744   EVT VT = SVOp->getValueType(0);
3745   unsigned NumElems = VT.getVectorNumElements();
3746
3747   bool Changed = false;
3748   SmallVector<int, 8> MaskVec;
3749   SVOp->getMask(MaskVec);
3750
3751   for (unsigned i = 0; i != NumElems; ++i) {
3752     if (MaskVec[i] > (int)NumElems) {
3753       MaskVec[i] = NumElems;
3754       Changed = true;
3755     }
3756   }
3757   if (Changed)
3758     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3759                                 SVOp->getOperand(1), &MaskVec[0]);
3760   return SDValue(SVOp, 0);
3761 }
3762
3763 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3764 /// operation of specified width.
3765 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3766                        SDValue V2) {
3767   unsigned NumElems = VT.getVectorNumElements();
3768   SmallVector<int, 8> Mask;
3769   Mask.push_back(NumElems);
3770   for (unsigned i = 1; i != NumElems; ++i)
3771     Mask.push_back(i);
3772   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3773 }
3774
3775 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3776 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3777                           SDValue V2) {
3778   unsigned NumElems = VT.getVectorNumElements();
3779   SmallVector<int, 8> Mask;
3780   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3781     Mask.push_back(i);
3782     Mask.push_back(i + NumElems);
3783   }
3784   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3785 }
3786
3787 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3788 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3789                           SDValue V2) {
3790   unsigned NumElems = VT.getVectorNumElements();
3791   unsigned Half = NumElems/2;
3792   SmallVector<int, 8> Mask;
3793   for (unsigned i = 0; i != Half; ++i) {
3794     Mask.push_back(i + Half);
3795     Mask.push_back(i + NumElems + Half);
3796   }
3797   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3798 }
3799
3800 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3801 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3802   EVT PVT = MVT::v4f32;
3803   EVT VT = SV->getValueType(0);
3804   DebugLoc dl = SV->getDebugLoc();
3805   SDValue V1 = SV->getOperand(0);
3806   int NumElems = VT.getVectorNumElements();
3807   int EltNo = SV->getSplatIndex();
3808
3809   // unpack elements to the correct location
3810   while (NumElems > 4) {
3811     if (EltNo < NumElems/2) {
3812       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3813     } else {
3814       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3815       EltNo -= NumElems/2;
3816     }
3817     NumElems >>= 1;
3818   }
3819
3820   // Perform the splat.
3821   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3822   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3823   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3824   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3825 }
3826
3827 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3828 /// vector of zero or undef vector.  This produces a shuffle where the low
3829 /// element of V2 is swizzled into the zero/undef vector, landing at element
3830 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3831 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3832                                              bool isZero, bool HasSSE2,
3833                                              SelectionDAG &DAG) {
3834   EVT VT = V2.getValueType();
3835   SDValue V1 = isZero
3836     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3837   unsigned NumElems = VT.getVectorNumElements();
3838   SmallVector<int, 16> MaskVec;
3839   for (unsigned i = 0; i != NumElems; ++i)
3840     // If this is the insertion idx, put the low elt of V2 here.
3841     MaskVec.push_back(i == Idx ? NumElems : i);
3842   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3843 }
3844
3845 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3846 /// element of the result of the vector shuffle.
3847 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3848                             unsigned Depth) {
3849   if (Depth == 6)
3850     return SDValue();  // Limit search depth.
3851
3852   SDValue V = SDValue(N, 0);
3853   EVT VT = V.getValueType();
3854   unsigned Opcode = V.getOpcode();
3855
3856   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3857   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3858     Index = SV->getMaskElt(Index);
3859
3860     if (Index < 0)
3861       return DAG.getUNDEF(VT.getVectorElementType());
3862
3863     int NumElems = VT.getVectorNumElements();
3864     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3865     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3866   }
3867
3868   // Recurse into target specific vector shuffles to find scalars.
3869   if (isTargetShuffle(Opcode)) {
3870     int NumElems = VT.getVectorNumElements();
3871     SmallVector<unsigned, 16> ShuffleMask;
3872     SDValue ImmN;
3873
3874     switch(Opcode) {
3875     case X86ISD::SHUFPS:
3876     case X86ISD::SHUFPD:
3877       ImmN = N->getOperand(N->getNumOperands()-1);
3878       DecodeSHUFPSMask(NumElems,
3879                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3880                        ShuffleMask);
3881       break;
3882     case X86ISD::PUNPCKHBW:
3883     case X86ISD::PUNPCKHWD:
3884     case X86ISD::PUNPCKHDQ:
3885     case X86ISD::PUNPCKHQDQ:
3886       DecodePUNPCKHMask(NumElems, ShuffleMask);
3887       break;
3888     case X86ISD::UNPCKHPS:
3889     case X86ISD::UNPCKHPD:
3890       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3891       break;
3892     case X86ISD::PUNPCKLBW:
3893     case X86ISD::PUNPCKLWD:
3894     case X86ISD::PUNPCKLDQ:
3895     case X86ISD::PUNPCKLQDQ:
3896       DecodePUNPCKLMask(NumElems, ShuffleMask);
3897       break;
3898     case X86ISD::UNPCKLPS:
3899     case X86ISD::UNPCKLPD:
3900       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3901       break;
3902     case X86ISD::MOVHLPS:
3903       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3904       break;
3905     case X86ISD::MOVLHPS:
3906       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3907       break;
3908     case X86ISD::PSHUFD:
3909       ImmN = N->getOperand(N->getNumOperands()-1);
3910       DecodePSHUFMask(NumElems,
3911                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3912                       ShuffleMask);
3913       break;
3914     case X86ISD::PSHUFHW:
3915       ImmN = N->getOperand(N->getNumOperands()-1);
3916       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3917                         ShuffleMask);
3918       break;
3919     case X86ISD::PSHUFLW:
3920       ImmN = N->getOperand(N->getNumOperands()-1);
3921       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3922                         ShuffleMask);
3923       break;
3924     case X86ISD::MOVSS:
3925     case X86ISD::MOVSD: {
3926       // The index 0 always comes from the first element of the second source,
3927       // this is why MOVSS and MOVSD are used in the first place. The other
3928       // elements come from the other positions of the first source vector.
3929       unsigned OpNum = (Index == 0) ? 1 : 0;
3930       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3931                                  Depth+1);
3932     }
3933     default:
3934       assert("not implemented for target shuffle node");
3935       return SDValue();
3936     }
3937
3938     Index = ShuffleMask[Index];
3939     if (Index < 0)
3940       return DAG.getUNDEF(VT.getVectorElementType());
3941
3942     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3943     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3944                                Depth+1);
3945   }
3946
3947   // Actual nodes that may contain scalar elements
3948   if (Opcode == ISD::BITCAST) {
3949     V = V.getOperand(0);
3950     EVT SrcVT = V.getValueType();
3951     unsigned NumElems = VT.getVectorNumElements();
3952
3953     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3954       return SDValue();
3955   }
3956
3957   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3958     return (Index == 0) ? V.getOperand(0)
3959                           : DAG.getUNDEF(VT.getVectorElementType());
3960
3961   if (V.getOpcode() == ISD::BUILD_VECTOR)
3962     return V.getOperand(Index);
3963
3964   return SDValue();
3965 }
3966
3967 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3968 /// shuffle operation which come from a consecutively from a zero. The
3969 /// search can start in two diferent directions, from left or right.
3970 static
3971 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3972                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3973   int i = 0;
3974
3975   while (i < NumElems) {
3976     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3977     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3978     if (!(Elt.getNode() &&
3979          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3980       break;
3981     ++i;
3982   }
3983
3984   return i;
3985 }
3986
3987 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3988 /// MaskE correspond consecutively to elements from one of the vector operands,
3989 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3990 static
3991 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3992                               int OpIdx, int NumElems, unsigned &OpNum) {
3993   bool SeenV1 = false;
3994   bool SeenV2 = false;
3995
3996   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3997     int Idx = SVOp->getMaskElt(i);
3998     // Ignore undef indicies
3999     if (Idx < 0)
4000       continue;
4001
4002     if (Idx < NumElems)
4003       SeenV1 = true;
4004     else
4005       SeenV2 = true;
4006
4007     // Only accept consecutive elements from the same vector
4008     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4009       return false;
4010   }
4011
4012   OpNum = SeenV1 ? 0 : 1;
4013   return true;
4014 }
4015
4016 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4017 /// logical left shift of a vector.
4018 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4019                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4020   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4021   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4022               false /* check zeros from right */, DAG);
4023   unsigned OpSrc;
4024
4025   if (!NumZeros)
4026     return false;
4027
4028   // Considering the elements in the mask that are not consecutive zeros,
4029   // check if they consecutively come from only one of the source vectors.
4030   //
4031   //               V1 = {X, A, B, C}     0
4032   //                         \  \  \    /
4033   //   vector_shuffle V1, V2 <1, 2, 3, X>
4034   //
4035   if (!isShuffleMaskConsecutive(SVOp,
4036             0,                   // Mask Start Index
4037             NumElems-NumZeros-1, // Mask End Index
4038             NumZeros,            // Where to start looking in the src vector
4039             NumElems,            // Number of elements in vector
4040             OpSrc))              // Which source operand ?
4041     return false;
4042
4043   isLeft = false;
4044   ShAmt = NumZeros;
4045   ShVal = SVOp->getOperand(OpSrc);
4046   return true;
4047 }
4048
4049 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4050 /// logical left shift of a vector.
4051 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4052                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4053   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4054   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4055               true /* check zeros from left */, DAG);
4056   unsigned OpSrc;
4057
4058   if (!NumZeros)
4059     return false;
4060
4061   // Considering the elements in the mask that are not consecutive zeros,
4062   // check if they consecutively come from only one of the source vectors.
4063   //
4064   //                           0    { A, B, X, X } = V2
4065   //                          / \    /  /
4066   //   vector_shuffle V1, V2 <X, X, 4, 5>
4067   //
4068   if (!isShuffleMaskConsecutive(SVOp,
4069             NumZeros,     // Mask Start Index
4070             NumElems-1,   // Mask End Index
4071             0,            // Where to start looking in the src vector
4072             NumElems,     // Number of elements in vector
4073             OpSrc))       // Which source operand ?
4074     return false;
4075
4076   isLeft = true;
4077   ShAmt = NumZeros;
4078   ShVal = SVOp->getOperand(OpSrc);
4079   return true;
4080 }
4081
4082 /// isVectorShift - Returns true if the shuffle can be implemented as a
4083 /// logical left or right shift of a vector.
4084 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4085                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4086   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4087       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4088     return true;
4089
4090   return false;
4091 }
4092
4093 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4094 ///
4095 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4096                                        unsigned NumNonZero, unsigned NumZero,
4097                                        SelectionDAG &DAG,
4098                                        const TargetLowering &TLI) {
4099   if (NumNonZero > 8)
4100     return SDValue();
4101
4102   DebugLoc dl = Op.getDebugLoc();
4103   SDValue V(0, 0);
4104   bool First = true;
4105   for (unsigned i = 0; i < 16; ++i) {
4106     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4107     if (ThisIsNonZero && First) {
4108       if (NumZero)
4109         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4110       else
4111         V = DAG.getUNDEF(MVT::v8i16);
4112       First = false;
4113     }
4114
4115     if ((i & 1) != 0) {
4116       SDValue ThisElt(0, 0), LastElt(0, 0);
4117       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4118       if (LastIsNonZero) {
4119         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4120                               MVT::i16, Op.getOperand(i-1));
4121       }
4122       if (ThisIsNonZero) {
4123         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4124         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4125                               ThisElt, DAG.getConstant(8, MVT::i8));
4126         if (LastIsNonZero)
4127           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4128       } else
4129         ThisElt = LastElt;
4130
4131       if (ThisElt.getNode())
4132         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4133                         DAG.getIntPtrConstant(i/2));
4134     }
4135   }
4136
4137   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4138 }
4139
4140 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4141 ///
4142 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4143                                      unsigned NumNonZero, unsigned NumZero,
4144                                      SelectionDAG &DAG,
4145                                      const TargetLowering &TLI) {
4146   if (NumNonZero > 4)
4147     return SDValue();
4148
4149   DebugLoc dl = Op.getDebugLoc();
4150   SDValue V(0, 0);
4151   bool First = true;
4152   for (unsigned i = 0; i < 8; ++i) {
4153     bool isNonZero = (NonZeros & (1 << i)) != 0;
4154     if (isNonZero) {
4155       if (First) {
4156         if (NumZero)
4157           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4158         else
4159           V = DAG.getUNDEF(MVT::v8i16);
4160         First = false;
4161       }
4162       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4163                       MVT::v8i16, V, Op.getOperand(i),
4164                       DAG.getIntPtrConstant(i));
4165     }
4166   }
4167
4168   return V;
4169 }
4170
4171 /// getVShift - Return a vector logical shift node.
4172 ///
4173 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4174                          unsigned NumBits, SelectionDAG &DAG,
4175                          const TargetLowering &TLI, DebugLoc dl) {
4176   EVT ShVT = MVT::v2i64;
4177   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4178   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4179   return DAG.getNode(ISD::BITCAST, dl, VT,
4180                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4181                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4182 }
4183
4184 SDValue
4185 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4186                                           SelectionDAG &DAG) const {
4187
4188   // Check if the scalar load can be widened into a vector load. And if
4189   // the address is "base + cst" see if the cst can be "absorbed" into
4190   // the shuffle mask.
4191   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4192     SDValue Ptr = LD->getBasePtr();
4193     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4194       return SDValue();
4195     EVT PVT = LD->getValueType(0);
4196     if (PVT != MVT::i32 && PVT != MVT::f32)
4197       return SDValue();
4198
4199     int FI = -1;
4200     int64_t Offset = 0;
4201     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4202       FI = FINode->getIndex();
4203       Offset = 0;
4204     } else if (Ptr.getOpcode() == ISD::ADD &&
4205                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4206                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4207       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4208       Offset = Ptr.getConstantOperandVal(1);
4209       Ptr = Ptr.getOperand(0);
4210     } else {
4211       return SDValue();
4212     }
4213
4214     SDValue Chain = LD->getChain();
4215     // Make sure the stack object alignment is at least 16.
4216     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4217     if (DAG.InferPtrAlignment(Ptr) < 16) {
4218       if (MFI->isFixedObjectIndex(FI)) {
4219         // Can't change the alignment. FIXME: It's possible to compute
4220         // the exact stack offset and reference FI + adjust offset instead.
4221         // If someone *really* cares about this. That's the way to implement it.
4222         return SDValue();
4223       } else {
4224         MFI->setObjectAlignment(FI, 16);
4225       }
4226     }
4227
4228     // (Offset % 16) must be multiple of 4. Then address is then
4229     // Ptr + (Offset & ~15).
4230     if (Offset < 0)
4231       return SDValue();
4232     if ((Offset % 16) & 3)
4233       return SDValue();
4234     int64_t StartOffset = Offset & ~15;
4235     if (StartOffset)
4236       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4237                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4238
4239     int EltNo = (Offset - StartOffset) >> 2;
4240     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4241     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4242     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4243                              LD->getPointerInfo().getWithOffset(StartOffset),
4244                              false, false, 0);
4245     // Canonicalize it to a v4i32 shuffle.
4246     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4247     return DAG.getNode(ISD::BITCAST, dl, VT,
4248                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4249                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4250   }
4251
4252   return SDValue();
4253 }
4254
4255 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4256 /// vector of type 'VT', see if the elements can be replaced by a single large
4257 /// load which has the same value as a build_vector whose operands are 'elts'.
4258 ///
4259 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4260 ///
4261 /// FIXME: we'd also like to handle the case where the last elements are zero
4262 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4263 /// There's even a handy isZeroNode for that purpose.
4264 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4265                                         DebugLoc &DL, SelectionDAG &DAG) {
4266   EVT EltVT = VT.getVectorElementType();
4267   unsigned NumElems = Elts.size();
4268
4269   LoadSDNode *LDBase = NULL;
4270   unsigned LastLoadedElt = -1U;
4271
4272   // For each element in the initializer, see if we've found a load or an undef.
4273   // If we don't find an initial load element, or later load elements are
4274   // non-consecutive, bail out.
4275   for (unsigned i = 0; i < NumElems; ++i) {
4276     SDValue Elt = Elts[i];
4277
4278     if (!Elt.getNode() ||
4279         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4280       return SDValue();
4281     if (!LDBase) {
4282       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4283         return SDValue();
4284       LDBase = cast<LoadSDNode>(Elt.getNode());
4285       LastLoadedElt = i;
4286       continue;
4287     }
4288     if (Elt.getOpcode() == ISD::UNDEF)
4289       continue;
4290
4291     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4292     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4293       return SDValue();
4294     LastLoadedElt = i;
4295   }
4296
4297   // If we have found an entire vector of loads and undefs, then return a large
4298   // load of the entire vector width starting at the base pointer.  If we found
4299   // consecutive loads for the low half, generate a vzext_load node.
4300   if (LastLoadedElt == NumElems - 1) {
4301     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4302       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4303                          LDBase->getPointerInfo(),
4304                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4305     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4306                        LDBase->getPointerInfo(),
4307                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4308                        LDBase->getAlignment());
4309   } else if (NumElems == 4 && LastLoadedElt == 1) {
4310     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4311     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4312     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4313                                               Ops, 2, MVT::i32,
4314                                               LDBase->getMemOperand());
4315     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4316   }
4317   return SDValue();
4318 }
4319
4320 SDValue
4321 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4322   DebugLoc dl = Op.getDebugLoc();
4323
4324   EVT VT = Op.getValueType();
4325   EVT ExtVT = VT.getVectorElementType();
4326
4327   unsigned NumElems = Op.getNumOperands();
4328
4329   // For AVX-length vectors, build the individual 128-bit pieces and
4330   // use shuffles to put them in place.
4331   if (VT.getSizeInBits() > 256 && 
4332       Subtarget->hasAVX() && 
4333       !Disable256Bit &&
4334       !ISD::isBuildVectorAllZeros(Op.getNode())) {
4335     SmallVector<SDValue, 8> V;
4336     V.resize(NumElems);
4337     for (unsigned i = 0; i < NumElems; ++i) {
4338       V[i] = Op.getOperand(i);
4339     }
4340  
4341     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4342
4343     // Build the lower subvector.
4344     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4345     // Build the upper subvector.
4346     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4347                                 NumElems/2);
4348
4349     return ConcatVectors(Lower, Upper, DAG);
4350   }
4351
4352   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4353   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4354   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4355   // is present, so AllOnes is ignored.
4356   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4357       (Op.getValueType().getSizeInBits() != 256 &&
4358        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4359     // Canonicalize this to <4 x i32> (SSE) to
4360     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4361     // eliminated on x86-32 hosts.
4362     if (Op.getValueType() == MVT::v4i32)
4363       return Op;
4364
4365     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4366       return getOnesVector(Op.getValueType(), DAG, dl);
4367     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4368   }
4369
4370   unsigned EVTBits = ExtVT.getSizeInBits();
4371
4372   unsigned NumZero  = 0;
4373   unsigned NumNonZero = 0;
4374   unsigned NonZeros = 0;
4375   bool IsAllConstants = true;
4376   SmallSet<SDValue, 8> Values;
4377   for (unsigned i = 0; i < NumElems; ++i) {
4378     SDValue Elt = Op.getOperand(i);
4379     if (Elt.getOpcode() == ISD::UNDEF)
4380       continue;
4381     Values.insert(Elt);
4382     if (Elt.getOpcode() != ISD::Constant &&
4383         Elt.getOpcode() != ISD::ConstantFP)
4384       IsAllConstants = false;
4385     if (X86::isZeroNode(Elt))
4386       NumZero++;
4387     else {
4388       NonZeros |= (1 << i);
4389       NumNonZero++;
4390     }
4391   }
4392
4393   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4394   if (NumNonZero == 0)
4395     return DAG.getUNDEF(VT);
4396
4397   // Special case for single non-zero, non-undef, element.
4398   if (NumNonZero == 1) {
4399     unsigned Idx = CountTrailingZeros_32(NonZeros);
4400     SDValue Item = Op.getOperand(Idx);
4401
4402     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4403     // the value are obviously zero, truncate the value to i32 and do the
4404     // insertion that way.  Only do this if the value is non-constant or if the
4405     // value is a constant being inserted into element 0.  It is cheaper to do
4406     // a constant pool load than it is to do a movd + shuffle.
4407     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4408         (!IsAllConstants || Idx == 0)) {
4409       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4410         // Handle SSE only.
4411         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4412         EVT VecVT = MVT::v4i32;
4413         unsigned VecElts = 4;
4414
4415         // Truncate the value (which may itself be a constant) to i32, and
4416         // convert it to a vector with movd (S2V+shuffle to zero extend).
4417         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4418         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4419         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4420                                            Subtarget->hasSSE2(), DAG);
4421
4422         // Now we have our 32-bit value zero extended in the low element of
4423         // a vector.  If Idx != 0, swizzle it into place.
4424         if (Idx != 0) {
4425           SmallVector<int, 4> Mask;
4426           Mask.push_back(Idx);
4427           for (unsigned i = 1; i != VecElts; ++i)
4428             Mask.push_back(i);
4429           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4430                                       DAG.getUNDEF(Item.getValueType()),
4431                                       &Mask[0]);
4432         }
4433         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4434       }
4435     }
4436
4437     // If we have a constant or non-constant insertion into the low element of
4438     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4439     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4440     // depending on what the source datatype is.
4441     if (Idx == 0) {
4442       if (NumZero == 0) {
4443         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4444       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4445           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4446         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4447         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4448         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4449                                            DAG);
4450       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4451         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4452         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4453         EVT MiddleVT = MVT::v4i32;
4454         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4455         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4456                                            Subtarget->hasSSE2(), DAG);
4457         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4458       }
4459     }
4460
4461     // Is it a vector logical left shift?
4462     if (NumElems == 2 && Idx == 1 &&
4463         X86::isZeroNode(Op.getOperand(0)) &&
4464         !X86::isZeroNode(Op.getOperand(1))) {
4465       unsigned NumBits = VT.getSizeInBits();
4466       return getVShift(true, VT,
4467                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4468                                    VT, Op.getOperand(1)),
4469                        NumBits/2, DAG, *this, dl);
4470     }
4471
4472     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4473       return SDValue();
4474
4475     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4476     // is a non-constant being inserted into an element other than the low one,
4477     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4478     // movd/movss) to move this into the low element, then shuffle it into
4479     // place.
4480     if (EVTBits == 32) {
4481       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4482
4483       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4484       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4485                                          Subtarget->hasSSE2(), DAG);
4486       SmallVector<int, 8> MaskVec;
4487       for (unsigned i = 0; i < NumElems; i++)
4488         MaskVec.push_back(i == Idx ? 0 : 1);
4489       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4490     }
4491   }
4492
4493   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4494   if (Values.size() == 1) {
4495     if (EVTBits == 32) {
4496       // Instead of a shuffle like this:
4497       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4498       // Check if it's possible to issue this instead.
4499       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4500       unsigned Idx = CountTrailingZeros_32(NonZeros);
4501       SDValue Item = Op.getOperand(Idx);
4502       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4503         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4504     }
4505     return SDValue();
4506   }
4507
4508   // A vector full of immediates; various special cases are already
4509   // handled, so this is best done with a single constant-pool load.
4510   if (IsAllConstants)
4511     return SDValue();
4512
4513   // Let legalizer expand 2-wide build_vectors.
4514   if (EVTBits == 64) {
4515     if (NumNonZero == 1) {
4516       // One half is zero or undef.
4517       unsigned Idx = CountTrailingZeros_32(NonZeros);
4518       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4519                                  Op.getOperand(Idx));
4520       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4521                                          Subtarget->hasSSE2(), DAG);
4522     }
4523     return SDValue();
4524   }
4525
4526   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4527   if (EVTBits == 8 && NumElems == 16) {
4528     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4529                                         *this);
4530     if (V.getNode()) return V;
4531   }
4532
4533   if (EVTBits == 16 && NumElems == 8) {
4534     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4535                                       *this);
4536     if (V.getNode()) return V;
4537   }
4538
4539   // If element VT is == 32 bits, turn it into a number of shuffles.
4540   SmallVector<SDValue, 8> V;
4541   V.resize(NumElems);
4542   if (NumElems == 4 && NumZero > 0) {
4543     for (unsigned i = 0; i < 4; ++i) {
4544       bool isZero = !(NonZeros & (1 << i));
4545       if (isZero)
4546         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4547       else
4548         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4549     }
4550
4551     for (unsigned i = 0; i < 2; ++i) {
4552       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4553         default: break;
4554         case 0:
4555           V[i] = V[i*2];  // Must be a zero vector.
4556           break;
4557         case 1:
4558           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4559           break;
4560         case 2:
4561           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4562           break;
4563         case 3:
4564           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4565           break;
4566       }
4567     }
4568
4569     SmallVector<int, 8> MaskVec;
4570     bool Reverse = (NonZeros & 0x3) == 2;
4571     for (unsigned i = 0; i < 2; ++i)
4572       MaskVec.push_back(Reverse ? 1-i : i);
4573     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4574     for (unsigned i = 0; i < 2; ++i)
4575       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4576     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4577   }
4578
4579   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4580     // Check for a build vector of consecutive loads.
4581     for (unsigned i = 0; i < NumElems; ++i)
4582       V[i] = Op.getOperand(i);
4583
4584     // Check for elements which are consecutive loads.
4585     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4586     if (LD.getNode())
4587       return LD;
4588
4589     // For SSE 4.1, use insertps to put the high elements into the low element.
4590     if (getSubtarget()->hasSSE41()) {
4591       SDValue Result;
4592       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4593         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4594       else
4595         Result = DAG.getUNDEF(VT);
4596
4597       for (unsigned i = 1; i < NumElems; ++i) {
4598         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4599         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4600                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4601       }
4602       return Result;
4603     }
4604
4605     // Otherwise, expand into a number of unpckl*, start by extending each of
4606     // our (non-undef) elements to the full vector width with the element in the
4607     // bottom slot of the vector (which generates no code for SSE).
4608     for (unsigned i = 0; i < NumElems; ++i) {
4609       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4610         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4611       else
4612         V[i] = DAG.getUNDEF(VT);
4613     }
4614
4615     // Next, we iteratively mix elements, e.g. for v4f32:
4616     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4617     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4618     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4619     unsigned EltStride = NumElems >> 1;
4620     while (EltStride != 0) {
4621       for (unsigned i = 0; i < EltStride; ++i) {
4622         // If V[i+EltStride] is undef and this is the first round of mixing,
4623         // then it is safe to just drop this shuffle: V[i] is already in the
4624         // right place, the one element (since it's the first round) being
4625         // inserted as undef can be dropped.  This isn't safe for successive
4626         // rounds because they will permute elements within both vectors.
4627         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4628             EltStride == NumElems/2)
4629           continue;
4630
4631         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4632       }
4633       EltStride >>= 1;
4634     }
4635     return V[0];
4636   }
4637   return SDValue();
4638 }
4639
4640 SDValue
4641 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4642   // We support concatenate two MMX registers and place them in a MMX
4643   // register.  This is better than doing a stack convert.
4644   DebugLoc dl = Op.getDebugLoc();
4645   EVT ResVT = Op.getValueType();
4646   assert(Op.getNumOperands() == 2);
4647   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4648          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4649   int Mask[2];
4650   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4651   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4652   InVec = Op.getOperand(1);
4653   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4654     unsigned NumElts = ResVT.getVectorNumElements();
4655     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4656     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4657                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4658   } else {
4659     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4660     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4661     Mask[0] = 0; Mask[1] = 2;
4662     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4663   }
4664   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4665 }
4666
4667 // v8i16 shuffles - Prefer shuffles in the following order:
4668 // 1. [all]   pshuflw, pshufhw, optional move
4669 // 2. [ssse3] 1 x pshufb
4670 // 3. [ssse3] 2 x pshufb + 1 x por
4671 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4672 SDValue
4673 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4674                                             SelectionDAG &DAG) const {
4675   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4676   SDValue V1 = SVOp->getOperand(0);
4677   SDValue V2 = SVOp->getOperand(1);
4678   DebugLoc dl = SVOp->getDebugLoc();
4679   SmallVector<int, 8> MaskVals;
4680
4681   // Determine if more than 1 of the words in each of the low and high quadwords
4682   // of the result come from the same quadword of one of the two inputs.  Undef
4683   // mask values count as coming from any quadword, for better codegen.
4684   SmallVector<unsigned, 4> LoQuad(4);
4685   SmallVector<unsigned, 4> HiQuad(4);
4686   BitVector InputQuads(4);
4687   for (unsigned i = 0; i < 8; ++i) {
4688     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4689     int EltIdx = SVOp->getMaskElt(i);
4690     MaskVals.push_back(EltIdx);
4691     if (EltIdx < 0) {
4692       ++Quad[0];
4693       ++Quad[1];
4694       ++Quad[2];
4695       ++Quad[3];
4696       continue;
4697     }
4698     ++Quad[EltIdx / 4];
4699     InputQuads.set(EltIdx / 4);
4700   }
4701
4702   int BestLoQuad = -1;
4703   unsigned MaxQuad = 1;
4704   for (unsigned i = 0; i < 4; ++i) {
4705     if (LoQuad[i] > MaxQuad) {
4706       BestLoQuad = i;
4707       MaxQuad = LoQuad[i];
4708     }
4709   }
4710
4711   int BestHiQuad = -1;
4712   MaxQuad = 1;
4713   for (unsigned i = 0; i < 4; ++i) {
4714     if (HiQuad[i] > MaxQuad) {
4715       BestHiQuad = i;
4716       MaxQuad = HiQuad[i];
4717     }
4718   }
4719
4720   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4721   // of the two input vectors, shuffle them into one input vector so only a
4722   // single pshufb instruction is necessary. If There are more than 2 input
4723   // quads, disable the next transformation since it does not help SSSE3.
4724   bool V1Used = InputQuads[0] || InputQuads[1];
4725   bool V2Used = InputQuads[2] || InputQuads[3];
4726   if (Subtarget->hasSSSE3()) {
4727     if (InputQuads.count() == 2 && V1Used && V2Used) {
4728       BestLoQuad = InputQuads.find_first();
4729       BestHiQuad = InputQuads.find_next(BestLoQuad);
4730     }
4731     if (InputQuads.count() > 2) {
4732       BestLoQuad = -1;
4733       BestHiQuad = -1;
4734     }
4735   }
4736
4737   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4738   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4739   // words from all 4 input quadwords.
4740   SDValue NewV;
4741   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4742     SmallVector<int, 8> MaskV;
4743     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4744     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4745     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4746                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4747                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4748     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4749
4750     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4751     // source words for the shuffle, to aid later transformations.
4752     bool AllWordsInNewV = true;
4753     bool InOrder[2] = { true, true };
4754     for (unsigned i = 0; i != 8; ++i) {
4755       int idx = MaskVals[i];
4756       if (idx != (int)i)
4757         InOrder[i/4] = false;
4758       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4759         continue;
4760       AllWordsInNewV = false;
4761       break;
4762     }
4763
4764     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4765     if (AllWordsInNewV) {
4766       for (int i = 0; i != 8; ++i) {
4767         int idx = MaskVals[i];
4768         if (idx < 0)
4769           continue;
4770         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4771         if ((idx != i) && idx < 4)
4772           pshufhw = false;
4773         if ((idx != i) && idx > 3)
4774           pshuflw = false;
4775       }
4776       V1 = NewV;
4777       V2Used = false;
4778       BestLoQuad = 0;
4779       BestHiQuad = 1;
4780     }
4781
4782     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4783     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4784     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4785       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4786       unsigned TargetMask = 0;
4787       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4788                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4789       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4790                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4791       V1 = NewV.getOperand(0);
4792       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4793     }
4794   }
4795
4796   // If we have SSSE3, and all words of the result are from 1 input vector,
4797   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4798   // is present, fall back to case 4.
4799   if (Subtarget->hasSSSE3()) {
4800     SmallVector<SDValue,16> pshufbMask;
4801
4802     // If we have elements from both input vectors, set the high bit of the
4803     // shuffle mask element to zero out elements that come from V2 in the V1
4804     // mask, and elements that come from V1 in the V2 mask, so that the two
4805     // results can be OR'd together.
4806     bool TwoInputs = V1Used && V2Used;
4807     for (unsigned i = 0; i != 8; ++i) {
4808       int EltIdx = MaskVals[i] * 2;
4809       if (TwoInputs && (EltIdx >= 16)) {
4810         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4811         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4812         continue;
4813       }
4814       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4815       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4816     }
4817     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4818     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4819                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4820                                  MVT::v16i8, &pshufbMask[0], 16));
4821     if (!TwoInputs)
4822       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4823
4824     // Calculate the shuffle mask for the second input, shuffle it, and
4825     // OR it with the first shuffled input.
4826     pshufbMask.clear();
4827     for (unsigned i = 0; i != 8; ++i) {
4828       int EltIdx = MaskVals[i] * 2;
4829       if (EltIdx < 16) {
4830         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4831         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4832         continue;
4833       }
4834       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4835       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4836     }
4837     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4838     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4839                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4840                                  MVT::v16i8, &pshufbMask[0], 16));
4841     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4842     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4843   }
4844
4845   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4846   // and update MaskVals with new element order.
4847   BitVector InOrder(8);
4848   if (BestLoQuad >= 0) {
4849     SmallVector<int, 8> MaskV;
4850     for (int i = 0; i != 4; ++i) {
4851       int idx = MaskVals[i];
4852       if (idx < 0) {
4853         MaskV.push_back(-1);
4854         InOrder.set(i);
4855       } else if ((idx / 4) == BestLoQuad) {
4856         MaskV.push_back(idx & 3);
4857         InOrder.set(i);
4858       } else {
4859         MaskV.push_back(-1);
4860       }
4861     }
4862     for (unsigned i = 4; i != 8; ++i)
4863       MaskV.push_back(i);
4864     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4865                                 &MaskV[0]);
4866
4867     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4868       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4869                                NewV.getOperand(0),
4870                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4871                                DAG);
4872   }
4873
4874   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4875   // and update MaskVals with the new element order.
4876   if (BestHiQuad >= 0) {
4877     SmallVector<int, 8> MaskV;
4878     for (unsigned i = 0; i != 4; ++i)
4879       MaskV.push_back(i);
4880     for (unsigned i = 4; i != 8; ++i) {
4881       int idx = MaskVals[i];
4882       if (idx < 0) {
4883         MaskV.push_back(-1);
4884         InOrder.set(i);
4885       } else if ((idx / 4) == BestHiQuad) {
4886         MaskV.push_back((idx & 3) + 4);
4887         InOrder.set(i);
4888       } else {
4889         MaskV.push_back(-1);
4890       }
4891     }
4892     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4893                                 &MaskV[0]);
4894
4895     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4896       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4897                               NewV.getOperand(0),
4898                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4899                               DAG);
4900   }
4901
4902   // In case BestHi & BestLo were both -1, which means each quadword has a word
4903   // from each of the four input quadwords, calculate the InOrder bitvector now
4904   // before falling through to the insert/extract cleanup.
4905   if (BestLoQuad == -1 && BestHiQuad == -1) {
4906     NewV = V1;
4907     for (int i = 0; i != 8; ++i)
4908       if (MaskVals[i] < 0 || MaskVals[i] == i)
4909         InOrder.set(i);
4910   }
4911
4912   // The other elements are put in the right place using pextrw and pinsrw.
4913   for (unsigned i = 0; i != 8; ++i) {
4914     if (InOrder[i])
4915       continue;
4916     int EltIdx = MaskVals[i];
4917     if (EltIdx < 0)
4918       continue;
4919     SDValue ExtOp = (EltIdx < 8)
4920     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4921                   DAG.getIntPtrConstant(EltIdx))
4922     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4923                   DAG.getIntPtrConstant(EltIdx - 8));
4924     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4925                        DAG.getIntPtrConstant(i));
4926   }
4927   return NewV;
4928 }
4929
4930 // v16i8 shuffles - Prefer shuffles in the following order:
4931 // 1. [ssse3] 1 x pshufb
4932 // 2. [ssse3] 2 x pshufb + 1 x por
4933 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4934 static
4935 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4936                                  SelectionDAG &DAG,
4937                                  const X86TargetLowering &TLI) {
4938   SDValue V1 = SVOp->getOperand(0);
4939   SDValue V2 = SVOp->getOperand(1);
4940   DebugLoc dl = SVOp->getDebugLoc();
4941   SmallVector<int, 16> MaskVals;
4942   SVOp->getMask(MaskVals);
4943
4944   // If we have SSSE3, case 1 is generated when all result bytes come from
4945   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4946   // present, fall back to case 3.
4947   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4948   bool V1Only = true;
4949   bool V2Only = true;
4950   for (unsigned i = 0; i < 16; ++i) {
4951     int EltIdx = MaskVals[i];
4952     if (EltIdx < 0)
4953       continue;
4954     if (EltIdx < 16)
4955       V2Only = false;
4956     else
4957       V1Only = false;
4958   }
4959
4960   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4961   if (TLI.getSubtarget()->hasSSSE3()) {
4962     SmallVector<SDValue,16> pshufbMask;
4963
4964     // If all result elements are from one input vector, then only translate
4965     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4966     //
4967     // Otherwise, we have elements from both input vectors, and must zero out
4968     // elements that come from V2 in the first mask, and V1 in the second mask
4969     // so that we can OR them together.
4970     bool TwoInputs = !(V1Only || V2Only);
4971     for (unsigned i = 0; i != 16; ++i) {
4972       int EltIdx = MaskVals[i];
4973       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4974         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4975         continue;
4976       }
4977       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4978     }
4979     // If all the elements are from V2, assign it to V1 and return after
4980     // building the first pshufb.
4981     if (V2Only)
4982       V1 = V2;
4983     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4984                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4985                                  MVT::v16i8, &pshufbMask[0], 16));
4986     if (!TwoInputs)
4987       return V1;
4988
4989     // Calculate the shuffle mask for the second input, shuffle it, and
4990     // OR it with the first shuffled input.
4991     pshufbMask.clear();
4992     for (unsigned i = 0; i != 16; ++i) {
4993       int EltIdx = MaskVals[i];
4994       if (EltIdx < 16) {
4995         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4996         continue;
4997       }
4998       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4999     }
5000     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5001                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5002                                  MVT::v16i8, &pshufbMask[0], 16));
5003     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5004   }
5005
5006   // No SSSE3 - Calculate in place words and then fix all out of place words
5007   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5008   // the 16 different words that comprise the two doublequadword input vectors.
5009   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5010   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5011   SDValue NewV = V2Only ? V2 : V1;
5012   for (int i = 0; i != 8; ++i) {
5013     int Elt0 = MaskVals[i*2];
5014     int Elt1 = MaskVals[i*2+1];
5015
5016     // This word of the result is all undef, skip it.
5017     if (Elt0 < 0 && Elt1 < 0)
5018       continue;
5019
5020     // This word of the result is already in the correct place, skip it.
5021     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5022       continue;
5023     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5024       continue;
5025
5026     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5027     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5028     SDValue InsElt;
5029
5030     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5031     // using a single extract together, load it and store it.
5032     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5033       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5034                            DAG.getIntPtrConstant(Elt1 / 2));
5035       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5036                         DAG.getIntPtrConstant(i));
5037       continue;
5038     }
5039
5040     // If Elt1 is defined, extract it from the appropriate source.  If the
5041     // source byte is not also odd, shift the extracted word left 8 bits
5042     // otherwise clear the bottom 8 bits if we need to do an or.
5043     if (Elt1 >= 0) {
5044       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5045                            DAG.getIntPtrConstant(Elt1 / 2));
5046       if ((Elt1 & 1) == 0)
5047         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5048                              DAG.getConstant(8, TLI.getShiftAmountTy()));
5049       else if (Elt0 >= 0)
5050         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5051                              DAG.getConstant(0xFF00, MVT::i16));
5052     }
5053     // If Elt0 is defined, extract it from the appropriate source.  If the
5054     // source byte is not also even, shift the extracted word right 8 bits. If
5055     // Elt1 was also defined, OR the extracted values together before
5056     // inserting them in the result.
5057     if (Elt0 >= 0) {
5058       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5059                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5060       if ((Elt0 & 1) != 0)
5061         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5062                               DAG.getConstant(8, TLI.getShiftAmountTy()));
5063       else if (Elt1 >= 0)
5064         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5065                              DAG.getConstant(0x00FF, MVT::i16));
5066       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5067                          : InsElt0;
5068     }
5069     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5070                        DAG.getIntPtrConstant(i));
5071   }
5072   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5073 }
5074
5075 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5076 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5077 /// done when every pair / quad of shuffle mask elements point to elements in
5078 /// the right sequence. e.g.
5079 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5080 static
5081 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5082                                  SelectionDAG &DAG, DebugLoc dl) {
5083   EVT VT = SVOp->getValueType(0);
5084   SDValue V1 = SVOp->getOperand(0);
5085   SDValue V2 = SVOp->getOperand(1);
5086   unsigned NumElems = VT.getVectorNumElements();
5087   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5088   EVT NewVT;
5089   switch (VT.getSimpleVT().SimpleTy) {
5090   default: assert(false && "Unexpected!");
5091   case MVT::v4f32: NewVT = MVT::v2f64; break;
5092   case MVT::v4i32: NewVT = MVT::v2i64; break;
5093   case MVT::v8i16: NewVT = MVT::v4i32; break;
5094   case MVT::v16i8: NewVT = MVT::v4i32; break;
5095   }
5096
5097   int Scale = NumElems / NewWidth;
5098   SmallVector<int, 8> MaskVec;
5099   for (unsigned i = 0; i < NumElems; i += Scale) {
5100     int StartIdx = -1;
5101     for (int j = 0; j < Scale; ++j) {
5102       int EltIdx = SVOp->getMaskElt(i+j);
5103       if (EltIdx < 0)
5104         continue;
5105       if (StartIdx == -1)
5106         StartIdx = EltIdx - (EltIdx % Scale);
5107       if (EltIdx != StartIdx + j)
5108         return SDValue();
5109     }
5110     if (StartIdx == -1)
5111       MaskVec.push_back(-1);
5112     else
5113       MaskVec.push_back(StartIdx / Scale);
5114   }
5115
5116   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5117   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5118   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5119 }
5120
5121 /// getVZextMovL - Return a zero-extending vector move low node.
5122 ///
5123 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5124                             SDValue SrcOp, SelectionDAG &DAG,
5125                             const X86Subtarget *Subtarget, DebugLoc dl) {
5126   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5127     LoadSDNode *LD = NULL;
5128     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5129       LD = dyn_cast<LoadSDNode>(SrcOp);
5130     if (!LD) {
5131       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5132       // instead.
5133       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5134       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5135           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5136           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5137           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5138         // PR2108
5139         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5140         return DAG.getNode(ISD::BITCAST, dl, VT,
5141                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5142                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5143                                                    OpVT,
5144                                                    SrcOp.getOperand(0)
5145                                                           .getOperand(0))));
5146       }
5147     }
5148   }
5149
5150   return DAG.getNode(ISD::BITCAST, dl, VT,
5151                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5152                                  DAG.getNode(ISD::BITCAST, dl,
5153                                              OpVT, SrcOp)));
5154 }
5155
5156 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
5157 /// shuffles.
5158 static SDValue
5159 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5160   SDValue V1 = SVOp->getOperand(0);
5161   SDValue V2 = SVOp->getOperand(1);
5162   DebugLoc dl = SVOp->getDebugLoc();
5163   EVT VT = SVOp->getValueType(0);
5164
5165   SmallVector<std::pair<int, int>, 8> Locs;
5166   Locs.resize(4);
5167   SmallVector<int, 8> Mask1(4U, -1);
5168   SmallVector<int, 8> PermMask;
5169   SVOp->getMask(PermMask);
5170
5171   unsigned NumHi = 0;
5172   unsigned NumLo = 0;
5173   for (unsigned i = 0; i != 4; ++i) {
5174     int Idx = PermMask[i];
5175     if (Idx < 0) {
5176       Locs[i] = std::make_pair(-1, -1);
5177     } else {
5178       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5179       if (Idx < 4) {
5180         Locs[i] = std::make_pair(0, NumLo);
5181         Mask1[NumLo] = Idx;
5182         NumLo++;
5183       } else {
5184         Locs[i] = std::make_pair(1, NumHi);
5185         if (2+NumHi < 4)
5186           Mask1[2+NumHi] = Idx;
5187         NumHi++;
5188       }
5189     }
5190   }
5191
5192   if (NumLo <= 2 && NumHi <= 2) {
5193     // If no more than two elements come from either vector. This can be
5194     // implemented with two shuffles. First shuffle gather the elements.
5195     // The second shuffle, which takes the first shuffle as both of its
5196     // vector operands, put the elements into the right order.
5197     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5198
5199     SmallVector<int, 8> Mask2(4U, -1);
5200
5201     for (unsigned i = 0; i != 4; ++i) {
5202       if (Locs[i].first == -1)
5203         continue;
5204       else {
5205         unsigned Idx = (i < 2) ? 0 : 4;
5206         Idx += Locs[i].first * 2 + Locs[i].second;
5207         Mask2[i] = Idx;
5208       }
5209     }
5210
5211     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5212   } else if (NumLo == 3 || NumHi == 3) {
5213     // Otherwise, we must have three elements from one vector, call it X, and
5214     // one element from the other, call it Y.  First, use a shufps to build an
5215     // intermediate vector with the one element from Y and the element from X
5216     // that will be in the same half in the final destination (the indexes don't
5217     // matter). Then, use a shufps to build the final vector, taking the half
5218     // containing the element from Y from the intermediate, and the other half
5219     // from X.
5220     if (NumHi == 3) {
5221       // Normalize it so the 3 elements come from V1.
5222       CommuteVectorShuffleMask(PermMask, VT);
5223       std::swap(V1, V2);
5224     }
5225
5226     // Find the element from V2.
5227     unsigned HiIndex;
5228     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5229       int Val = PermMask[HiIndex];
5230       if (Val < 0)
5231         continue;
5232       if (Val >= 4)
5233         break;
5234     }
5235
5236     Mask1[0] = PermMask[HiIndex];
5237     Mask1[1] = -1;
5238     Mask1[2] = PermMask[HiIndex^1];
5239     Mask1[3] = -1;
5240     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5241
5242     if (HiIndex >= 2) {
5243       Mask1[0] = PermMask[0];
5244       Mask1[1] = PermMask[1];
5245       Mask1[2] = HiIndex & 1 ? 6 : 4;
5246       Mask1[3] = HiIndex & 1 ? 4 : 6;
5247       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5248     } else {
5249       Mask1[0] = HiIndex & 1 ? 2 : 0;
5250       Mask1[1] = HiIndex & 1 ? 0 : 2;
5251       Mask1[2] = PermMask[2];
5252       Mask1[3] = PermMask[3];
5253       if (Mask1[2] >= 0)
5254         Mask1[2] += 4;
5255       if (Mask1[3] >= 0)
5256         Mask1[3] += 4;
5257       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5258     }
5259   }
5260
5261   // Break it into (shuffle shuffle_hi, shuffle_lo).
5262   Locs.clear();
5263   SmallVector<int,8> LoMask(4U, -1);
5264   SmallVector<int,8> HiMask(4U, -1);
5265
5266   SmallVector<int,8> *MaskPtr = &LoMask;
5267   unsigned MaskIdx = 0;
5268   unsigned LoIdx = 0;
5269   unsigned HiIdx = 2;
5270   for (unsigned i = 0; i != 4; ++i) {
5271     if (i == 2) {
5272       MaskPtr = &HiMask;
5273       MaskIdx = 1;
5274       LoIdx = 0;
5275       HiIdx = 2;
5276     }
5277     int Idx = PermMask[i];
5278     if (Idx < 0) {
5279       Locs[i] = std::make_pair(-1, -1);
5280     } else if (Idx < 4) {
5281       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5282       (*MaskPtr)[LoIdx] = Idx;
5283       LoIdx++;
5284     } else {
5285       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5286       (*MaskPtr)[HiIdx] = Idx;
5287       HiIdx++;
5288     }
5289   }
5290
5291   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5292   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5293   SmallVector<int, 8> MaskOps;
5294   for (unsigned i = 0; i != 4; ++i) {
5295     if (Locs[i].first == -1) {
5296       MaskOps.push_back(-1);
5297     } else {
5298       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5299       MaskOps.push_back(Idx);
5300     }
5301   }
5302   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5303 }
5304
5305 static bool MayFoldVectorLoad(SDValue V) {
5306   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5307     V = V.getOperand(0);
5308   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5309     V = V.getOperand(0);
5310   if (MayFoldLoad(V))
5311     return true;
5312   return false;
5313 }
5314
5315 // FIXME: the version above should always be used. Since there's
5316 // a bug where several vector shuffles can't be folded because the
5317 // DAG is not updated during lowering and a node claims to have two
5318 // uses while it only has one, use this version, and let isel match
5319 // another instruction if the load really happens to have more than
5320 // one use. Remove this version after this bug get fixed.
5321 // rdar://8434668, PR8156
5322 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5323   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5324     V = V.getOperand(0);
5325   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5326     V = V.getOperand(0);
5327   if (ISD::isNormalLoad(V.getNode()))
5328     return true;
5329   return false;
5330 }
5331
5332 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5333 /// a vector extract, and if both can be later optimized into a single load.
5334 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5335 /// here because otherwise a target specific shuffle node is going to be
5336 /// emitted for this shuffle, and the optimization not done.
5337 /// FIXME: This is probably not the best approach, but fix the problem
5338 /// until the right path is decided.
5339 static
5340 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5341                                          const TargetLowering &TLI) {
5342   EVT VT = V.getValueType();
5343   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5344
5345   // Be sure that the vector shuffle is present in a pattern like this:
5346   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5347   if (!V.hasOneUse())
5348     return false;
5349
5350   SDNode *N = *V.getNode()->use_begin();
5351   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5352     return false;
5353
5354   SDValue EltNo = N->getOperand(1);
5355   if (!isa<ConstantSDNode>(EltNo))
5356     return false;
5357
5358   // If the bit convert changed the number of elements, it is unsafe
5359   // to examine the mask.
5360   bool HasShuffleIntoBitcast = false;
5361   if (V.getOpcode() == ISD::BITCAST) {
5362     EVT SrcVT = V.getOperand(0).getValueType();
5363     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5364       return false;
5365     V = V.getOperand(0);
5366     HasShuffleIntoBitcast = true;
5367   }
5368
5369   // Select the input vector, guarding against out of range extract vector.
5370   unsigned NumElems = VT.getVectorNumElements();
5371   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5372   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5373   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5374
5375   // Skip one more bit_convert if necessary
5376   if (V.getOpcode() == ISD::BITCAST)
5377     V = V.getOperand(0);
5378
5379   if (ISD::isNormalLoad(V.getNode())) {
5380     // Is the original load suitable?
5381     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5382
5383     // FIXME: avoid the multi-use bug that is preventing lots of
5384     // of foldings to be detected, this is still wrong of course, but
5385     // give the temporary desired behavior, and if it happens that
5386     // the load has real more uses, during isel it will not fold, and
5387     // will generate poor code.
5388     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5389       return false;
5390
5391     if (!HasShuffleIntoBitcast)
5392       return true;
5393
5394     // If there's a bitcast before the shuffle, check if the load type and
5395     // alignment is valid.
5396     unsigned Align = LN0->getAlignment();
5397     unsigned NewAlign =
5398       TLI.getTargetData()->getABITypeAlignment(
5399                                     VT.getTypeForEVT(*DAG.getContext()));
5400
5401     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5402       return false;
5403   }
5404
5405   return true;
5406 }
5407
5408 static
5409 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5410   EVT VT = Op.getValueType();
5411
5412   // Canonizalize to v2f64.
5413   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5414   return DAG.getNode(ISD::BITCAST, dl, VT,
5415                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5416                                           V1, DAG));
5417 }
5418
5419 static
5420 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5421                         bool HasSSE2) {
5422   SDValue V1 = Op.getOperand(0);
5423   SDValue V2 = Op.getOperand(1);
5424   EVT VT = Op.getValueType();
5425
5426   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5427
5428   if (HasSSE2 && VT == MVT::v2f64)
5429     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5430
5431   // v4f32 or v4i32
5432   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5433 }
5434
5435 static
5436 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5437   SDValue V1 = Op.getOperand(0);
5438   SDValue V2 = Op.getOperand(1);
5439   EVT VT = Op.getValueType();
5440
5441   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5442          "unsupported shuffle type");
5443
5444   if (V2.getOpcode() == ISD::UNDEF)
5445     V2 = V1;
5446
5447   // v4i32 or v4f32
5448   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5449 }
5450
5451 static
5452 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5453   SDValue V1 = Op.getOperand(0);
5454   SDValue V2 = Op.getOperand(1);
5455   EVT VT = Op.getValueType();
5456   unsigned NumElems = VT.getVectorNumElements();
5457
5458   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5459   // operand of these instructions is only memory, so check if there's a
5460   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5461   // same masks.
5462   bool CanFoldLoad = false;
5463
5464   // Trivial case, when V2 comes from a load.
5465   if (MayFoldVectorLoad(V2))
5466     CanFoldLoad = true;
5467
5468   // When V1 is a load, it can be folded later into a store in isel, example:
5469   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5470   //    turns into:
5471   //  (MOVLPSmr addr:$src1, VR128:$src2)
5472   // So, recognize this potential and also use MOVLPS or MOVLPD
5473   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5474     CanFoldLoad = true;
5475
5476   if (CanFoldLoad) {
5477     if (HasSSE2 && NumElems == 2)
5478       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5479
5480     if (NumElems == 4)
5481       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5482   }
5483
5484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5485   // movl and movlp will both match v2i64, but v2i64 is never matched by
5486   // movl earlier because we make it strict to avoid messing with the movlp load
5487   // folding logic (see the code above getMOVLP call). Match it here then,
5488   // this is horrible, but will stay like this until we move all shuffle
5489   // matching to x86 specific nodes. Note that for the 1st condition all
5490   // types are matched with movsd.
5491   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5492     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5493   else if (HasSSE2)
5494     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5495
5496
5497   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5498
5499   // Invert the operand order and use SHUFPS to match it.
5500   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5501                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5502 }
5503
5504 static inline unsigned getUNPCKLOpcode(EVT VT) {
5505   switch(VT.getSimpleVT().SimpleTy) {
5506   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5507   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5508   case MVT::v4f32: return X86ISD::UNPCKLPS;
5509   case MVT::v2f64: return X86ISD::UNPCKLPD;
5510   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5511   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5512   default:
5513     llvm_unreachable("Unknow type for unpckl");
5514   }
5515   return 0;
5516 }
5517
5518 static inline unsigned getUNPCKHOpcode(EVT VT) {
5519   switch(VT.getSimpleVT().SimpleTy) {
5520   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5521   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5522   case MVT::v4f32: return X86ISD::UNPCKHPS;
5523   case MVT::v2f64: return X86ISD::UNPCKHPD;
5524   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5525   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5526   default:
5527     llvm_unreachable("Unknow type for unpckh");
5528   }
5529   return 0;
5530 }
5531
5532 static
5533 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5534                                const TargetLowering &TLI,
5535                                const X86Subtarget *Subtarget) {
5536   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5537   EVT VT = Op.getValueType();
5538   DebugLoc dl = Op.getDebugLoc();
5539   SDValue V1 = Op.getOperand(0);
5540   SDValue V2 = Op.getOperand(1);
5541
5542   if (isZeroShuffle(SVOp))
5543     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5544
5545   // Handle splat operations
5546   if (SVOp->isSplat()) {
5547     // Special case, this is the only place now where it's
5548     // allowed to return a vector_shuffle operation without
5549     // using a target specific node, because *hopefully* it
5550     // will be optimized away by the dag combiner.
5551     if (VT.getVectorNumElements() <= 4 &&
5552         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5553       return Op;
5554
5555     // Handle splats by matching through known masks
5556     if (VT.getVectorNumElements() <= 4)
5557       return SDValue();
5558
5559     // Canonicalize all of the remaining to v4f32.
5560     return PromoteSplat(SVOp, DAG);
5561   }
5562
5563   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5564   // do it!
5565   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5566     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5567     if (NewOp.getNode())
5568       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5569   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5570     // FIXME: Figure out a cleaner way to do this.
5571     // Try to make use of movq to zero out the top part.
5572     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5573       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5574       if (NewOp.getNode()) {
5575         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5576           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5577                               DAG, Subtarget, dl);
5578       }
5579     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5580       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5581       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5582         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5583                             DAG, Subtarget, dl);
5584     }
5585   }
5586   return SDValue();
5587 }
5588
5589 SDValue
5590 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5591   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5592   SDValue V1 = Op.getOperand(0);
5593   SDValue V2 = Op.getOperand(1);
5594   EVT VT = Op.getValueType();
5595   DebugLoc dl = Op.getDebugLoc();
5596   unsigned NumElems = VT.getVectorNumElements();
5597   bool isMMX = VT.getSizeInBits() == 64;
5598   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5599   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5600   bool V1IsSplat = false;
5601   bool V2IsSplat = false;
5602   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5603   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5604   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5605   MachineFunction &MF = DAG.getMachineFunction();
5606   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5607
5608   // Shuffle operations on MMX not supported.
5609   if (isMMX)
5610     return Op;
5611
5612   // Vector shuffle lowering takes 3 steps:
5613   //
5614   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5615   //    narrowing and commutation of operands should be handled.
5616   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5617   //    shuffle nodes.
5618   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5619   //    so the shuffle can be broken into other shuffles and the legalizer can
5620   //    try the lowering again.
5621   //
5622   // The general ideia is that no vector_shuffle operation should be left to
5623   // be matched during isel, all of them must be converted to a target specific
5624   // node here.
5625
5626   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5627   // narrowing and commutation of operands should be handled. The actual code
5628   // doesn't include all of those, work in progress...
5629   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5630   if (NewOp.getNode())
5631     return NewOp;
5632
5633   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5634   // unpckh_undef). Only use pshufd if speed is more important than size.
5635   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5636     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5637       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5638   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5639     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5640       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5641
5642   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5643       RelaxedMayFoldVectorLoad(V1))
5644     return getMOVDDup(Op, dl, V1, DAG);
5645
5646   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5647     return getMOVHighToLow(Op, dl, DAG);
5648
5649   // Use to match splats
5650   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5651       (VT == MVT::v2f64 || VT == MVT::v2i64))
5652     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5653
5654   if (X86::isPSHUFDMask(SVOp)) {
5655     // The actual implementation will match the mask in the if above and then
5656     // during isel it can match several different instructions, not only pshufd
5657     // as its name says, sad but true, emulate the behavior for now...
5658     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5659         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5660
5661     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5662
5663     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5664       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5665
5666     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5667       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5668                                   TargetMask, DAG);
5669
5670     if (VT == MVT::v4f32)
5671       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5672                                   TargetMask, DAG);
5673   }
5674
5675   // Check if this can be converted into a logical shift.
5676   bool isLeft = false;
5677   unsigned ShAmt = 0;
5678   SDValue ShVal;
5679   bool isShift = getSubtarget()->hasSSE2() &&
5680     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5681   if (isShift && ShVal.hasOneUse()) {
5682     // If the shifted value has multiple uses, it may be cheaper to use
5683     // v_set0 + movlhps or movhlps, etc.
5684     EVT EltVT = VT.getVectorElementType();
5685     ShAmt *= EltVT.getSizeInBits();
5686     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5687   }
5688
5689   if (X86::isMOVLMask(SVOp)) {
5690     if (V1IsUndef)
5691       return V2;
5692     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5693       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5694     if (!X86::isMOVLPMask(SVOp)) {
5695       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5696         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5697
5698       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5699         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5700     }
5701   }
5702
5703   // FIXME: fold these into legal mask.
5704   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5705     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5706
5707   if (X86::isMOVHLPSMask(SVOp))
5708     return getMOVHighToLow(Op, dl, DAG);
5709
5710   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5711     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5712
5713   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5714     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5715
5716   if (X86::isMOVLPMask(SVOp))
5717     return getMOVLP(Op, dl, DAG, HasSSE2);
5718
5719   if (ShouldXformToMOVHLPS(SVOp) ||
5720       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5721     return CommuteVectorShuffle(SVOp, DAG);
5722
5723   if (isShift) {
5724     // No better options. Use a vshl / vsrl.
5725     EVT EltVT = VT.getVectorElementType();
5726     ShAmt *= EltVT.getSizeInBits();
5727     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5728   }
5729
5730   bool Commuted = false;
5731   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5732   // 1,1,1,1 -> v8i16 though.
5733   V1IsSplat = isSplatVector(V1.getNode());
5734   V2IsSplat = isSplatVector(V2.getNode());
5735
5736   // Canonicalize the splat or undef, if present, to be on the RHS.
5737   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5738     Op = CommuteVectorShuffle(SVOp, DAG);
5739     SVOp = cast<ShuffleVectorSDNode>(Op);
5740     V1 = SVOp->getOperand(0);
5741     V2 = SVOp->getOperand(1);
5742     std::swap(V1IsSplat, V2IsSplat);
5743     std::swap(V1IsUndef, V2IsUndef);
5744     Commuted = true;
5745   }
5746
5747   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5748     // Shuffling low element of v1 into undef, just return v1.
5749     if (V2IsUndef)
5750       return V1;
5751     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5752     // the instruction selector will not match, so get a canonical MOVL with
5753     // swapped operands to undo the commute.
5754     return getMOVL(DAG, dl, VT, V2, V1);
5755   }
5756
5757   if (X86::isUNPCKLMask(SVOp))
5758     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5759
5760   if (X86::isUNPCKHMask(SVOp))
5761     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5762
5763   if (V2IsSplat) {
5764     // Normalize mask so all entries that point to V2 points to its first
5765     // element then try to match unpck{h|l} again. If match, return a
5766     // new vector_shuffle with the corrected mask.
5767     SDValue NewMask = NormalizeMask(SVOp, DAG);
5768     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5769     if (NSVOp != SVOp) {
5770       if (X86::isUNPCKLMask(NSVOp, true)) {
5771         return NewMask;
5772       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5773         return NewMask;
5774       }
5775     }
5776   }
5777
5778   if (Commuted) {
5779     // Commute is back and try unpck* again.
5780     // FIXME: this seems wrong.
5781     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5782     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5783
5784     if (X86::isUNPCKLMask(NewSVOp))
5785       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5786
5787     if (X86::isUNPCKHMask(NewSVOp))
5788       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5789   }
5790
5791   // Normalize the node to match x86 shuffle ops if needed
5792   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5793     return CommuteVectorShuffle(SVOp, DAG);
5794
5795   // The checks below are all present in isShuffleMaskLegal, but they are
5796   // inlined here right now to enable us to directly emit target specific
5797   // nodes, and remove one by one until they don't return Op anymore.
5798   SmallVector<int, 16> M;
5799   SVOp->getMask(M);
5800
5801   if (isPALIGNRMask(M, VT, HasSSSE3))
5802     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5803                                 X86::getShufflePALIGNRImmediate(SVOp),
5804                                 DAG);
5805
5806   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5807       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5808     if (VT == MVT::v2f64)
5809       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5810     if (VT == MVT::v2i64)
5811       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5812   }
5813
5814   if (isPSHUFHWMask(M, VT))
5815     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5816                                 X86::getShufflePSHUFHWImmediate(SVOp),
5817                                 DAG);
5818
5819   if (isPSHUFLWMask(M, VT))
5820     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5821                                 X86::getShufflePSHUFLWImmediate(SVOp),
5822                                 DAG);
5823
5824   if (isSHUFPMask(M, VT)) {
5825     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5826     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5827       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5828                                   TargetMask, DAG);
5829     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5830       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5831                                   TargetMask, DAG);
5832   }
5833
5834   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5835     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5836       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5837   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5838     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5839       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5840
5841   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5842   if (VT == MVT::v8i16) {
5843     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5844     if (NewOp.getNode())
5845       return NewOp;
5846   }
5847
5848   if (VT == MVT::v16i8) {
5849     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5850     if (NewOp.getNode())
5851       return NewOp;
5852   }
5853
5854   // Handle all 4 wide cases with a number of shuffles.
5855   if (NumElems == 4)
5856     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5857
5858   return SDValue();
5859 }
5860
5861 SDValue
5862 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5863                                                 SelectionDAG &DAG) const {
5864   EVT VT = Op.getValueType();
5865   DebugLoc dl = Op.getDebugLoc();
5866   if (VT.getSizeInBits() == 8) {
5867     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5868                                     Op.getOperand(0), Op.getOperand(1));
5869     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5870                                     DAG.getValueType(VT));
5871     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5872   } else if (VT.getSizeInBits() == 16) {
5873     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5874     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5875     if (Idx == 0)
5876       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5877                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5878                                      DAG.getNode(ISD::BITCAST, dl,
5879                                                  MVT::v4i32,
5880                                                  Op.getOperand(0)),
5881                                      Op.getOperand(1)));
5882     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5883                                     Op.getOperand(0), Op.getOperand(1));
5884     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5885                                     DAG.getValueType(VT));
5886     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5887   } else if (VT == MVT::f32) {
5888     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5889     // the result back to FR32 register. It's only worth matching if the
5890     // result has a single use which is a store or a bitcast to i32.  And in
5891     // the case of a store, it's not worth it if the index is a constant 0,
5892     // because a MOVSSmr can be used instead, which is smaller and faster.
5893     if (!Op.hasOneUse())
5894       return SDValue();
5895     SDNode *User = *Op.getNode()->use_begin();
5896     if ((User->getOpcode() != ISD::STORE ||
5897          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5898           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5899         (User->getOpcode() != ISD::BITCAST ||
5900          User->getValueType(0) != MVT::i32))
5901       return SDValue();
5902     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5903                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5904                                               Op.getOperand(0)),
5905                                               Op.getOperand(1));
5906     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5907   } else if (VT == MVT::i32) {
5908     // ExtractPS works with constant index.
5909     if (isa<ConstantSDNode>(Op.getOperand(1)))
5910       return Op;
5911   }
5912   return SDValue();
5913 }
5914
5915
5916 SDValue
5917 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5918                                            SelectionDAG &DAG) const {
5919   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5920     return SDValue();
5921
5922   SDValue Vec = Op.getOperand(0);
5923   EVT VecVT = Vec.getValueType();
5924
5925   // If this is a 256-bit vector result, first extract the 128-bit
5926   // vector and then extract from the 128-bit vector.
5927   if (VecVT.getSizeInBits() > 128) {
5928     DebugLoc dl = Op.getNode()->getDebugLoc();
5929     unsigned NumElems = VecVT.getVectorNumElements();
5930     SDValue Idx = Op.getOperand(1);
5931
5932     if (!isa<ConstantSDNode>(Idx))
5933       return SDValue();
5934
5935     unsigned ExtractNumElems = NumElems / (VecVT.getSizeInBits() / 128);
5936     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5937
5938     // Get the 128-bit vector.
5939     bool Upper = IdxVal >= ExtractNumElems;
5940     Vec = Extract128BitVector(Vec, Idx, DAG, dl);
5941
5942     // Extract from it.
5943     SDValue ScaledIdx = Idx;
5944     if (Upper)
5945       ScaledIdx = DAG.getNode(ISD::SUB, dl, Idx.getValueType(), Idx,
5946                               DAG.getConstant(ExtractNumElems,
5947                                               Idx.getValueType()));
5948     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
5949                        ScaledIdx);
5950   }
5951
5952   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
5953
5954   if (Subtarget->hasSSE41()) {
5955     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5956     if (Res.getNode())
5957       return Res;
5958   }
5959
5960   EVT VT = Op.getValueType();
5961   DebugLoc dl = Op.getDebugLoc();
5962   // TODO: handle v16i8.
5963   if (VT.getSizeInBits() == 16) {
5964     SDValue Vec = Op.getOperand(0);
5965     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5966     if (Idx == 0)
5967       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5968                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5969                                      DAG.getNode(ISD::BITCAST, dl,
5970                                                  MVT::v4i32, Vec),
5971                                      Op.getOperand(1)));
5972     // Transform it so it match pextrw which produces a 32-bit result.
5973     EVT EltVT = MVT::i32;
5974     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5975                                     Op.getOperand(0), Op.getOperand(1));
5976     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5977                                     DAG.getValueType(VT));
5978     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5979   } else if (VT.getSizeInBits() == 32) {
5980     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5981     if (Idx == 0)
5982       return Op;
5983
5984     // SHUFPS the element to the lowest double word, then movss.
5985     int Mask[4] = { Idx, -1, -1, -1 };
5986     EVT VVT = Op.getOperand(0).getValueType();
5987     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5988                                        DAG.getUNDEF(VVT), Mask);
5989     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5990                        DAG.getIntPtrConstant(0));
5991   } else if (VT.getSizeInBits() == 64) {
5992     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5993     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5994     //        to match extract_elt for f64.
5995     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5996     if (Idx == 0)
5997       return Op;
5998
5999     // UNPCKHPD the element to the lowest double word, then movsd.
6000     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6001     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6002     int Mask[2] = { 1, -1 };
6003     EVT VVT = Op.getOperand(0).getValueType();
6004     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6005                                        DAG.getUNDEF(VVT), Mask);
6006     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6007                        DAG.getIntPtrConstant(0));
6008   }
6009
6010   return SDValue();
6011 }
6012
6013 SDValue
6014 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6015                                                SelectionDAG &DAG) const {
6016   EVT VT = Op.getValueType();
6017   EVT EltVT = VT.getVectorElementType();
6018   DebugLoc dl = Op.getDebugLoc();
6019
6020   SDValue N0 = Op.getOperand(0);
6021   SDValue N1 = Op.getOperand(1);
6022   SDValue N2 = Op.getOperand(2);
6023
6024   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6025       isa<ConstantSDNode>(N2)) {
6026     unsigned Opc;
6027     if (VT == MVT::v8i16)
6028       Opc = X86ISD::PINSRW;
6029     else if (VT == MVT::v16i8)
6030       Opc = X86ISD::PINSRB;
6031     else
6032       Opc = X86ISD::PINSRB;
6033
6034     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6035     // argument.
6036     if (N1.getValueType() != MVT::i32)
6037       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6038     if (N2.getValueType() != MVT::i32)
6039       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6040     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6041   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6042     // Bits [7:6] of the constant are the source select.  This will always be
6043     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6044     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6045     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6046     // Bits [5:4] of the constant are the destination select.  This is the
6047     //  value of the incoming immediate.
6048     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6049     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6050     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6051     // Create this as a scalar to vector..
6052     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6053     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6054   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6055     // PINSR* works with constant index.
6056     return Op;
6057   }
6058   return SDValue();
6059 }
6060
6061 SDValue
6062 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6063   EVT VT = Op.getValueType();
6064   EVT EltVT = VT.getVectorElementType();
6065
6066   DebugLoc dl = Op.getDebugLoc();
6067   SDValue N0 = Op.getOperand(0);
6068   SDValue N1 = Op.getOperand(1);
6069   SDValue N2 = Op.getOperand(2);
6070
6071   // If this is a 256-bit vector result, first insert into a 128-bit
6072   // vector and then insert into the 256-bit vector.
6073   if (VT.getSizeInBits() > 128) {
6074     if (!isa<ConstantSDNode>(N2))
6075       return SDValue();
6076
6077     // Get the 128-bit vector.
6078     unsigned NumElems = VT.getVectorNumElements();
6079     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6080     bool Upper = IdxVal >= NumElems / 2;
6081
6082     SDValue SubN0 = Extract128BitVector(N0, N2, DAG, dl);
6083
6084     // Insert into it.
6085     SDValue ScaledN2 = N2;
6086     if (Upper)
6087       ScaledN2 = DAG.getNode(ISD::SUB, dl, N2.getValueType(), N2,
6088                              DAG.getConstant(NumElems / 
6089                                              (VT.getSizeInBits() / 128),
6090                                              N2.getValueType()));
6091     Op = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubN0.getValueType(), SubN0,
6092                      N1, ScaledN2);
6093
6094     // Insert the 128-bit vector
6095     // FIXME: Why UNDEF?
6096     return Insert128BitVector(N0, Op, N2, DAG, dl);
6097   }
6098
6099   if (Subtarget->hasSSE41())
6100     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6101
6102   if (EltVT == MVT::i8)
6103     return SDValue();
6104
6105   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6106     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6107     // as its second argument.
6108     if (N1.getValueType() != MVT::i32)
6109       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6110     if (N2.getValueType() != MVT::i32)
6111       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6112     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6113   }
6114   return SDValue();
6115 }
6116
6117 SDValue
6118 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6119   DebugLoc dl = Op.getDebugLoc();
6120
6121   if (Op.getValueType() == MVT::v1i64 &&
6122       Op.getOperand(0).getValueType() == MVT::i64)
6123     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6124
6125   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6126   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6127          "Expected an SSE type!");
6128   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6129                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6130 }
6131
6132 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6133 // a simple subregister reference or explicit instructions to grab
6134 // upper bits of a vector.
6135 SDValue
6136 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6137   if (Subtarget->hasAVX()) {
6138     DebugLoc dl = Op.getNode()->getDebugLoc();
6139     SDValue Vec = Op.getNode()->getOperand(0);
6140     SDValue Idx = Op.getNode()->getOperand(1);
6141
6142     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6143         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6144         return Extract128BitVector(Vec, Idx, DAG, dl);
6145     }
6146   }
6147   return SDValue();
6148 }
6149
6150 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6151 // simple superregister reference or explicit instructions to insert
6152 // the upper bits of a vector.
6153 SDValue
6154 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6155   if (Subtarget->hasAVX()) {
6156     DebugLoc dl = Op.getNode()->getDebugLoc();
6157     SDValue Vec = Op.getNode()->getOperand(0);
6158     SDValue SubVec = Op.getNode()->getOperand(1);
6159     SDValue Idx = Op.getNode()->getOperand(2);
6160
6161     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6162         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6163       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6164     }
6165   }
6166   return SDValue();
6167 }
6168
6169 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6170 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6171 // one of the above mentioned nodes. It has to be wrapped because otherwise
6172 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6173 // be used to form addressing mode. These wrapped nodes will be selected
6174 // into MOV32ri.
6175 SDValue
6176 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6177   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6178
6179   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6180   // global base reg.
6181   unsigned char OpFlag = 0;
6182   unsigned WrapperKind = X86ISD::Wrapper;
6183   CodeModel::Model M = getTargetMachine().getCodeModel();
6184
6185   if (Subtarget->isPICStyleRIPRel() &&
6186       (M == CodeModel::Small || M == CodeModel::Kernel))
6187     WrapperKind = X86ISD::WrapperRIP;
6188   else if (Subtarget->isPICStyleGOT())
6189     OpFlag = X86II::MO_GOTOFF;
6190   else if (Subtarget->isPICStyleStubPIC())
6191     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6192
6193   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6194                                              CP->getAlignment(),
6195                                              CP->getOffset(), OpFlag);
6196   DebugLoc DL = CP->getDebugLoc();
6197   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6198   // With PIC, the address is actually $g + Offset.
6199   if (OpFlag) {
6200     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6201                          DAG.getNode(X86ISD::GlobalBaseReg,
6202                                      DebugLoc(), getPointerTy()),
6203                          Result);
6204   }
6205
6206   return Result;
6207 }
6208
6209 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6210   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6211
6212   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6213   // global base reg.
6214   unsigned char OpFlag = 0;
6215   unsigned WrapperKind = X86ISD::Wrapper;
6216   CodeModel::Model M = getTargetMachine().getCodeModel();
6217
6218   if (Subtarget->isPICStyleRIPRel() &&
6219       (M == CodeModel::Small || M == CodeModel::Kernel))
6220     WrapperKind = X86ISD::WrapperRIP;
6221   else if (Subtarget->isPICStyleGOT())
6222     OpFlag = X86II::MO_GOTOFF;
6223   else if (Subtarget->isPICStyleStubPIC())
6224     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6225
6226   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6227                                           OpFlag);
6228   DebugLoc DL = JT->getDebugLoc();
6229   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6230
6231   // With PIC, the address is actually $g + Offset.
6232   if (OpFlag)
6233     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6234                          DAG.getNode(X86ISD::GlobalBaseReg,
6235                                      DebugLoc(), getPointerTy()),
6236                          Result);
6237
6238   return Result;
6239 }
6240
6241 SDValue
6242 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6243   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6244
6245   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6246   // global base reg.
6247   unsigned char OpFlag = 0;
6248   unsigned WrapperKind = X86ISD::Wrapper;
6249   CodeModel::Model M = getTargetMachine().getCodeModel();
6250
6251   if (Subtarget->isPICStyleRIPRel() &&
6252       (M == CodeModel::Small || M == CodeModel::Kernel))
6253     WrapperKind = X86ISD::WrapperRIP;
6254   else if (Subtarget->isPICStyleGOT())
6255     OpFlag = X86II::MO_GOTOFF;
6256   else if (Subtarget->isPICStyleStubPIC())
6257     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6258
6259   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6260
6261   DebugLoc DL = Op.getDebugLoc();
6262   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6263
6264
6265   // With PIC, the address is actually $g + Offset.
6266   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6267       !Subtarget->is64Bit()) {
6268     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6269                          DAG.getNode(X86ISD::GlobalBaseReg,
6270                                      DebugLoc(), getPointerTy()),
6271                          Result);
6272   }
6273
6274   return Result;
6275 }
6276
6277 SDValue
6278 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6279   // Create the TargetBlockAddressAddress node.
6280   unsigned char OpFlags =
6281     Subtarget->ClassifyBlockAddressReference();
6282   CodeModel::Model M = getTargetMachine().getCodeModel();
6283   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6284   DebugLoc dl = Op.getDebugLoc();
6285   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6286                                        /*isTarget=*/true, OpFlags);
6287
6288   if (Subtarget->isPICStyleRIPRel() &&
6289       (M == CodeModel::Small || M == CodeModel::Kernel))
6290     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6291   else
6292     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6293
6294   // With PIC, the address is actually $g + Offset.
6295   if (isGlobalRelativeToPICBase(OpFlags)) {
6296     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6297                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6298                          Result);
6299   }
6300
6301   return Result;
6302 }
6303
6304 SDValue
6305 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6306                                       int64_t Offset,
6307                                       SelectionDAG &DAG) const {
6308   // Create the TargetGlobalAddress node, folding in the constant
6309   // offset if it is legal.
6310   unsigned char OpFlags =
6311     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6312   CodeModel::Model M = getTargetMachine().getCodeModel();
6313   SDValue Result;
6314   if (OpFlags == X86II::MO_NO_FLAG &&
6315       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6316     // A direct static reference to a global.
6317     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6318     Offset = 0;
6319   } else {
6320     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6321   }
6322
6323   if (Subtarget->isPICStyleRIPRel() &&
6324       (M == CodeModel::Small || M == CodeModel::Kernel))
6325     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6326   else
6327     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6328
6329   // With PIC, the address is actually $g + Offset.
6330   if (isGlobalRelativeToPICBase(OpFlags)) {
6331     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6332                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6333                          Result);
6334   }
6335
6336   // For globals that require a load from a stub to get the address, emit the
6337   // load.
6338   if (isGlobalStubReference(OpFlags))
6339     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6340                          MachinePointerInfo::getGOT(), false, false, 0);
6341
6342   // If there was a non-zero offset that we didn't fold, create an explicit
6343   // addition for it.
6344   if (Offset != 0)
6345     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6346                          DAG.getConstant(Offset, getPointerTy()));
6347
6348   return Result;
6349 }
6350
6351 SDValue
6352 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6353   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6354   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6355   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6356 }
6357
6358 static SDValue
6359 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6360            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6361            unsigned char OperandFlags) {
6362   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6363   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6364   DebugLoc dl = GA->getDebugLoc();
6365   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6366                                            GA->getValueType(0),
6367                                            GA->getOffset(),
6368                                            OperandFlags);
6369   if (InFlag) {
6370     SDValue Ops[] = { Chain,  TGA, *InFlag };
6371     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6372   } else {
6373     SDValue Ops[]  = { Chain, TGA };
6374     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6375   }
6376
6377   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6378   MFI->setAdjustsStack(true);
6379
6380   SDValue Flag = Chain.getValue(1);
6381   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6382 }
6383
6384 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6385 static SDValue
6386 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6387                                 const EVT PtrVT) {
6388   SDValue InFlag;
6389   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6390   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6391                                      DAG.getNode(X86ISD::GlobalBaseReg,
6392                                                  DebugLoc(), PtrVT), InFlag);
6393   InFlag = Chain.getValue(1);
6394
6395   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6396 }
6397
6398 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6399 static SDValue
6400 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6401                                 const EVT PtrVT) {
6402   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6403                     X86::RAX, X86II::MO_TLSGD);
6404 }
6405
6406 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6407 // "local exec" model.
6408 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6409                                    const EVT PtrVT, TLSModel::Model model,
6410                                    bool is64Bit) {
6411   DebugLoc dl = GA->getDebugLoc();
6412
6413   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6414   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6415                                                          is64Bit ? 257 : 256));
6416
6417   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6418                                       DAG.getIntPtrConstant(0),
6419                                       MachinePointerInfo(Ptr), false, false, 0);
6420
6421   unsigned char OperandFlags = 0;
6422   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6423   // initialexec.
6424   unsigned WrapperKind = X86ISD::Wrapper;
6425   if (model == TLSModel::LocalExec) {
6426     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6427   } else if (is64Bit) {
6428     assert(model == TLSModel::InitialExec);
6429     OperandFlags = X86II::MO_GOTTPOFF;
6430     WrapperKind = X86ISD::WrapperRIP;
6431   } else {
6432     assert(model == TLSModel::InitialExec);
6433     OperandFlags = X86II::MO_INDNTPOFF;
6434   }
6435
6436   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6437   // exec)
6438   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6439                                            GA->getValueType(0),
6440                                            GA->getOffset(), OperandFlags);
6441   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6442
6443   if (model == TLSModel::InitialExec)
6444     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6445                          MachinePointerInfo::getGOT(), false, false, 0);
6446
6447   // The address of the thread local variable is the add of the thread
6448   // pointer with the offset of the variable.
6449   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6450 }
6451
6452 SDValue
6453 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6454
6455   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6456   const GlobalValue *GV = GA->getGlobal();
6457
6458   if (Subtarget->isTargetELF()) {
6459     // TODO: implement the "local dynamic" model
6460     // TODO: implement the "initial exec"model for pic executables
6461
6462     // If GV is an alias then use the aliasee for determining
6463     // thread-localness.
6464     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6465       GV = GA->resolveAliasedGlobal(false);
6466
6467     TLSModel::Model model
6468       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6469
6470     switch (model) {
6471       case TLSModel::GeneralDynamic:
6472       case TLSModel::LocalDynamic: // not implemented
6473         if (Subtarget->is64Bit())
6474           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6475         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6476
6477       case TLSModel::InitialExec:
6478       case TLSModel::LocalExec:
6479         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6480                                    Subtarget->is64Bit());
6481     }
6482   } else if (Subtarget->isTargetDarwin()) {
6483     // Darwin only has one model of TLS.  Lower to that.
6484     unsigned char OpFlag = 0;
6485     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6486                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6487
6488     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6489     // global base reg.
6490     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6491                   !Subtarget->is64Bit();
6492     if (PIC32)
6493       OpFlag = X86II::MO_TLVP_PIC_BASE;
6494     else
6495       OpFlag = X86II::MO_TLVP;
6496     DebugLoc DL = Op.getDebugLoc();
6497     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6498                                                 GA->getValueType(0),
6499                                                 GA->getOffset(), OpFlag);
6500     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6501
6502     // With PIC32, the address is actually $g + Offset.
6503     if (PIC32)
6504       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6505                            DAG.getNode(X86ISD::GlobalBaseReg,
6506                                        DebugLoc(), getPointerTy()),
6507                            Offset);
6508
6509     // Lowering the machine isd will make sure everything is in the right
6510     // location.
6511     SDValue Chain = DAG.getEntryNode();
6512     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6513     SDValue Args[] = { Chain, Offset };
6514     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6515
6516     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6517     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6518     MFI->setAdjustsStack(true);
6519
6520     // And our return value (tls address) is in the standard call return value
6521     // location.
6522     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6523     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6524   }
6525
6526   assert(false &&
6527          "TLS not implemented for this target.");
6528
6529   llvm_unreachable("Unreachable");
6530   return SDValue();
6531 }
6532
6533
6534 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6535 /// take a 2 x i32 value to shift plus a shift amount.
6536 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6537   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6538   EVT VT = Op.getValueType();
6539   unsigned VTBits = VT.getSizeInBits();
6540   DebugLoc dl = Op.getDebugLoc();
6541   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6542   SDValue ShOpLo = Op.getOperand(0);
6543   SDValue ShOpHi = Op.getOperand(1);
6544   SDValue ShAmt  = Op.getOperand(2);
6545   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6546                                      DAG.getConstant(VTBits - 1, MVT::i8))
6547                        : DAG.getConstant(0, VT);
6548
6549   SDValue Tmp2, Tmp3;
6550   if (Op.getOpcode() == ISD::SHL_PARTS) {
6551     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6552     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6553   } else {
6554     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6555     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6556   }
6557
6558   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6559                                 DAG.getConstant(VTBits, MVT::i8));
6560   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6561                              AndNode, DAG.getConstant(0, MVT::i8));
6562
6563   SDValue Hi, Lo;
6564   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6565   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6566   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6567
6568   if (Op.getOpcode() == ISD::SHL_PARTS) {
6569     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6570     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6571   } else {
6572     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6573     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6574   }
6575
6576   SDValue Ops[2] = { Lo, Hi };
6577   return DAG.getMergeValues(Ops, 2, dl);
6578 }
6579
6580 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6581                                            SelectionDAG &DAG) const {
6582   EVT SrcVT = Op.getOperand(0).getValueType();
6583
6584   if (SrcVT.isVector())
6585     return SDValue();
6586
6587   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6588          "Unknown SINT_TO_FP to lower!");
6589
6590   // These are really Legal; return the operand so the caller accepts it as
6591   // Legal.
6592   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6593     return Op;
6594   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6595       Subtarget->is64Bit()) {
6596     return Op;
6597   }
6598
6599   DebugLoc dl = Op.getDebugLoc();
6600   unsigned Size = SrcVT.getSizeInBits()/8;
6601   MachineFunction &MF = DAG.getMachineFunction();
6602   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6603   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6604   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6605                                StackSlot,
6606                                MachinePointerInfo::getFixedStack(SSFI),
6607                                false, false, 0);
6608   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6609 }
6610
6611 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6612                                      SDValue StackSlot,
6613                                      SelectionDAG &DAG) const {
6614   // Build the FILD
6615   DebugLoc DL = Op.getDebugLoc();
6616   SDVTList Tys;
6617   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6618   if (useSSE)
6619     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6620   else
6621     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6622
6623   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6624
6625   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6626   MachineMemOperand *MMO =
6627     DAG.getMachineFunction()
6628     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6629                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6630
6631   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6632   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6633                                            X86ISD::FILD, DL,
6634                                            Tys, Ops, array_lengthof(Ops),
6635                                            SrcVT, MMO);
6636
6637   if (useSSE) {
6638     Chain = Result.getValue(1);
6639     SDValue InFlag = Result.getValue(2);
6640
6641     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6642     // shouldn't be necessary except that RFP cannot be live across
6643     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6644     MachineFunction &MF = DAG.getMachineFunction();
6645     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6646     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6647     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6648     Tys = DAG.getVTList(MVT::Other);
6649     SDValue Ops[] = {
6650       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6651     };
6652     MachineMemOperand *MMO =
6653       DAG.getMachineFunction()
6654       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6655                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6656
6657     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6658                                     Ops, array_lengthof(Ops),
6659                                     Op.getValueType(), MMO);
6660     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6661                          MachinePointerInfo::getFixedStack(SSFI),
6662                          false, false, 0);
6663   }
6664
6665   return Result;
6666 }
6667
6668 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6669 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6670                                                SelectionDAG &DAG) const {
6671   // This algorithm is not obvious. Here it is in C code, more or less:
6672   /*
6673     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6674       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6675       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6676
6677       // Copy ints to xmm registers.
6678       __m128i xh = _mm_cvtsi32_si128( hi );
6679       __m128i xl = _mm_cvtsi32_si128( lo );
6680
6681       // Combine into low half of a single xmm register.
6682       __m128i x = _mm_unpacklo_epi32( xh, xl );
6683       __m128d d;
6684       double sd;
6685
6686       // Merge in appropriate exponents to give the integer bits the right
6687       // magnitude.
6688       x = _mm_unpacklo_epi32( x, exp );
6689
6690       // Subtract away the biases to deal with the IEEE-754 double precision
6691       // implicit 1.
6692       d = _mm_sub_pd( (__m128d) x, bias );
6693
6694       // All conversions up to here are exact. The correctly rounded result is
6695       // calculated using the current rounding mode using the following
6696       // horizontal add.
6697       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6698       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6699                                 // store doesn't really need to be here (except
6700                                 // maybe to zero the other double)
6701       return sd;
6702     }
6703   */
6704
6705   DebugLoc dl = Op.getDebugLoc();
6706   LLVMContext *Context = DAG.getContext();
6707
6708   // Build some magic constants.
6709   std::vector<Constant*> CV0;
6710   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6711   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6712   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6713   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6714   Constant *C0 = ConstantVector::get(CV0);
6715   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6716
6717   std::vector<Constant*> CV1;
6718   CV1.push_back(
6719     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6720   CV1.push_back(
6721     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6722   Constant *C1 = ConstantVector::get(CV1);
6723   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6724
6725   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6726                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6727                                         Op.getOperand(0),
6728                                         DAG.getIntPtrConstant(1)));
6729   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6730                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6731                                         Op.getOperand(0),
6732                                         DAG.getIntPtrConstant(0)));
6733   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6734   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6735                               MachinePointerInfo::getConstantPool(),
6736                               false, false, 16);
6737   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6738   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6739   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6740                               MachinePointerInfo::getConstantPool(),
6741                               false, false, 16);
6742   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6743
6744   // Add the halves; easiest way is to swap them into another reg first.
6745   int ShufMask[2] = { 1, -1 };
6746   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6747                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6748   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6749   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6750                      DAG.getIntPtrConstant(0));
6751 }
6752
6753 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6754 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6755                                                SelectionDAG &DAG) const {
6756   DebugLoc dl = Op.getDebugLoc();
6757   // FP constant to bias correct the final result.
6758   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6759                                    MVT::f64);
6760
6761   // Load the 32-bit value into an XMM register.
6762   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6763                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6764                                          Op.getOperand(0),
6765                                          DAG.getIntPtrConstant(0)));
6766
6767   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6768                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6769                      DAG.getIntPtrConstant(0));
6770
6771   // Or the load with the bias.
6772   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6773                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6774                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6775                                                    MVT::v2f64, Load)),
6776                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6777                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6778                                                    MVT::v2f64, Bias)));
6779   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6780                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6781                    DAG.getIntPtrConstant(0));
6782
6783   // Subtract the bias.
6784   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6785
6786   // Handle final rounding.
6787   EVT DestVT = Op.getValueType();
6788
6789   if (DestVT.bitsLT(MVT::f64)) {
6790     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6791                        DAG.getIntPtrConstant(0));
6792   } else if (DestVT.bitsGT(MVT::f64)) {
6793     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6794   }
6795
6796   // Handle final rounding.
6797   return Sub;
6798 }
6799
6800 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6801                                            SelectionDAG &DAG) const {
6802   SDValue N0 = Op.getOperand(0);
6803   DebugLoc dl = Op.getDebugLoc();
6804
6805   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6806   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6807   // the optimization here.
6808   if (DAG.SignBitIsZero(N0))
6809     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6810
6811   EVT SrcVT = N0.getValueType();
6812   EVT DstVT = Op.getValueType();
6813   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6814     return LowerUINT_TO_FP_i64(Op, DAG);
6815   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6816     return LowerUINT_TO_FP_i32(Op, DAG);
6817
6818   // Make a 64-bit buffer, and use it to build an FILD.
6819   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6820   if (SrcVT == MVT::i32) {
6821     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6822     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6823                                      getPointerTy(), StackSlot, WordOff);
6824     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6825                                   StackSlot, MachinePointerInfo(),
6826                                   false, false, 0);
6827     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6828                                   OffsetSlot, MachinePointerInfo(),
6829                                   false, false, 0);
6830     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6831     return Fild;
6832   }
6833
6834   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6835   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6836                                 StackSlot, MachinePointerInfo(),
6837                                false, false, 0);
6838   // For i64 source, we need to add the appropriate power of 2 if the input
6839   // was negative.  This is the same as the optimization in
6840   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6841   // we must be careful to do the computation in x87 extended precision, not
6842   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6843   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6844   MachineMemOperand *MMO =
6845     DAG.getMachineFunction()
6846     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6847                           MachineMemOperand::MOLoad, 8, 8);
6848
6849   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6850   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6851   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6852                                          MVT::i64, MMO);
6853
6854   APInt FF(32, 0x5F800000ULL);
6855
6856   // Check whether the sign bit is set.
6857   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6858                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6859                                  ISD::SETLT);
6860
6861   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6862   SDValue FudgePtr = DAG.getConstantPool(
6863                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6864                                          getPointerTy());
6865
6866   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6867   SDValue Zero = DAG.getIntPtrConstant(0);
6868   SDValue Four = DAG.getIntPtrConstant(4);
6869   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6870                                Zero, Four);
6871   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6872
6873   // Load the value out, extending it from f32 to f80.
6874   // FIXME: Avoid the extend by constructing the right constant pool?
6875   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6876                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6877                                  MVT::f32, false, false, 4);
6878   // Extend everything to 80 bits to force it to be done on x87.
6879   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6880   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6881 }
6882
6883 std::pair<SDValue,SDValue> X86TargetLowering::
6884 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6885   DebugLoc DL = Op.getDebugLoc();
6886
6887   EVT DstTy = Op.getValueType();
6888
6889   if (!IsSigned) {
6890     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6891     DstTy = MVT::i64;
6892   }
6893
6894   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6895          DstTy.getSimpleVT() >= MVT::i16 &&
6896          "Unknown FP_TO_SINT to lower!");
6897
6898   // These are really Legal.
6899   if (DstTy == MVT::i32 &&
6900       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6901     return std::make_pair(SDValue(), SDValue());
6902   if (Subtarget->is64Bit() &&
6903       DstTy == MVT::i64 &&
6904       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6905     return std::make_pair(SDValue(), SDValue());
6906
6907   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6908   // stack slot.
6909   MachineFunction &MF = DAG.getMachineFunction();
6910   unsigned MemSize = DstTy.getSizeInBits()/8;
6911   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6912   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6913
6914
6915
6916   unsigned Opc;
6917   switch (DstTy.getSimpleVT().SimpleTy) {
6918   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6919   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6920   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6921   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6922   }
6923
6924   SDValue Chain = DAG.getEntryNode();
6925   SDValue Value = Op.getOperand(0);
6926   EVT TheVT = Op.getOperand(0).getValueType();
6927   if (isScalarFPTypeInSSEReg(TheVT)) {
6928     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6929     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6930                          MachinePointerInfo::getFixedStack(SSFI),
6931                          false, false, 0);
6932     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6933     SDValue Ops[] = {
6934       Chain, StackSlot, DAG.getValueType(TheVT)
6935     };
6936
6937     MachineMemOperand *MMO =
6938       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6939                               MachineMemOperand::MOLoad, MemSize, MemSize);
6940     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6941                                     DstTy, MMO);
6942     Chain = Value.getValue(1);
6943     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6944     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6945   }
6946
6947   MachineMemOperand *MMO =
6948     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6949                             MachineMemOperand::MOStore, MemSize, MemSize);
6950
6951   // Build the FP_TO_INT*_IN_MEM
6952   SDValue Ops[] = { Chain, Value, StackSlot };
6953   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6954                                          Ops, 3, DstTy, MMO);
6955
6956   return std::make_pair(FIST, StackSlot);
6957 }
6958
6959 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6960                                            SelectionDAG &DAG) const {
6961   if (Op.getValueType().isVector())
6962     return SDValue();
6963
6964   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6965   SDValue FIST = Vals.first, StackSlot = Vals.second;
6966   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6967   if (FIST.getNode() == 0) return Op;
6968
6969   // Load the result.
6970   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6971                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6972 }
6973
6974 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6975                                            SelectionDAG &DAG) const {
6976   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6977   SDValue FIST = Vals.first, StackSlot = Vals.second;
6978   assert(FIST.getNode() && "Unexpected failure");
6979
6980   // Load the result.
6981   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6982                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6983 }
6984
6985 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6986                                      SelectionDAG &DAG) const {
6987   LLVMContext *Context = DAG.getContext();
6988   DebugLoc dl = Op.getDebugLoc();
6989   EVT VT = Op.getValueType();
6990   EVT EltVT = VT;
6991   if (VT.isVector())
6992     EltVT = VT.getVectorElementType();
6993   std::vector<Constant*> CV;
6994   if (EltVT == MVT::f64) {
6995     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6996     CV.push_back(C);
6997     CV.push_back(C);
6998   } else {
6999     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7000     CV.push_back(C);
7001     CV.push_back(C);
7002     CV.push_back(C);
7003     CV.push_back(C);
7004   }
7005   Constant *C = ConstantVector::get(CV);
7006   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7007   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7008                              MachinePointerInfo::getConstantPool(),
7009                              false, false, 16);
7010   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7011 }
7012
7013 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7014   LLVMContext *Context = DAG.getContext();
7015   DebugLoc dl = Op.getDebugLoc();
7016   EVT VT = Op.getValueType();
7017   EVT EltVT = VT;
7018   if (VT.isVector())
7019     EltVT = VT.getVectorElementType();
7020   std::vector<Constant*> CV;
7021   if (EltVT == MVT::f64) {
7022     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7023     CV.push_back(C);
7024     CV.push_back(C);
7025   } else {
7026     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7027     CV.push_back(C);
7028     CV.push_back(C);
7029     CV.push_back(C);
7030     CV.push_back(C);
7031   }
7032   Constant *C = ConstantVector::get(CV);
7033   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7034   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7035                              MachinePointerInfo::getConstantPool(),
7036                              false, false, 16);
7037   if (VT.isVector()) {
7038     return DAG.getNode(ISD::BITCAST, dl, VT,
7039                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7040                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7041                                 Op.getOperand(0)),
7042                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7043   } else {
7044     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7045   }
7046 }
7047
7048 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7049   LLVMContext *Context = DAG.getContext();
7050   SDValue Op0 = Op.getOperand(0);
7051   SDValue Op1 = Op.getOperand(1);
7052   DebugLoc dl = Op.getDebugLoc();
7053   EVT VT = Op.getValueType();
7054   EVT SrcVT = Op1.getValueType();
7055
7056   // If second operand is smaller, extend it first.
7057   if (SrcVT.bitsLT(VT)) {
7058     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7059     SrcVT = VT;
7060   }
7061   // And if it is bigger, shrink it first.
7062   if (SrcVT.bitsGT(VT)) {
7063     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7064     SrcVT = VT;
7065   }
7066
7067   // At this point the operands and the result should have the same
7068   // type, and that won't be f80 since that is not custom lowered.
7069
7070   // First get the sign bit of second operand.
7071   std::vector<Constant*> CV;
7072   if (SrcVT == MVT::f64) {
7073     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7074     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7075   } else {
7076     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7077     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7078     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7079     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7080   }
7081   Constant *C = ConstantVector::get(CV);
7082   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7083   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7084                               MachinePointerInfo::getConstantPool(),
7085                               false, false, 16);
7086   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7087
7088   // Shift sign bit right or left if the two operands have different types.
7089   if (SrcVT.bitsGT(VT)) {
7090     // Op0 is MVT::f32, Op1 is MVT::f64.
7091     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7092     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7093                           DAG.getConstant(32, MVT::i32));
7094     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7095     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7096                           DAG.getIntPtrConstant(0));
7097   }
7098
7099   // Clear first operand sign bit.
7100   CV.clear();
7101   if (VT == MVT::f64) {
7102     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7103     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7104   } else {
7105     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7106     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7107     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7108     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7109   }
7110   C = ConstantVector::get(CV);
7111   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7112   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7113                               MachinePointerInfo::getConstantPool(),
7114                               false, false, 16);
7115   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7116
7117   // Or the value with the sign bit.
7118   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7119 }
7120
7121 /// Emit nodes that will be selected as "test Op0,Op0", or something
7122 /// equivalent.
7123 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7124                                     SelectionDAG &DAG) const {
7125   DebugLoc dl = Op.getDebugLoc();
7126
7127   // CF and OF aren't always set the way we want. Determine which
7128   // of these we need.
7129   bool NeedCF = false;
7130   bool NeedOF = false;
7131   switch (X86CC) {
7132   default: break;
7133   case X86::COND_A: case X86::COND_AE:
7134   case X86::COND_B: case X86::COND_BE:
7135     NeedCF = true;
7136     break;
7137   case X86::COND_G: case X86::COND_GE:
7138   case X86::COND_L: case X86::COND_LE:
7139   case X86::COND_O: case X86::COND_NO:
7140     NeedOF = true;
7141     break;
7142   }
7143
7144   // See if we can use the EFLAGS value from the operand instead of
7145   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7146   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7147   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7148     // Emit a CMP with 0, which is the TEST pattern.
7149     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7150                        DAG.getConstant(0, Op.getValueType()));
7151
7152   unsigned Opcode = 0;
7153   unsigned NumOperands = 0;
7154   switch (Op.getNode()->getOpcode()) {
7155   case ISD::ADD:
7156     // Due to an isel shortcoming, be conservative if this add is likely to be
7157     // selected as part of a load-modify-store instruction. When the root node
7158     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7159     // uses of other nodes in the match, such as the ADD in this case. This
7160     // leads to the ADD being left around and reselected, with the result being
7161     // two adds in the output.  Alas, even if none our users are stores, that
7162     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7163     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7164     // climbing the DAG back to the root, and it doesn't seem to be worth the
7165     // effort.
7166     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7167            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7168       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7169         goto default_case;
7170
7171     if (ConstantSDNode *C =
7172         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7173       // An add of one will be selected as an INC.
7174       if (C->getAPIntValue() == 1) {
7175         Opcode = X86ISD::INC;
7176         NumOperands = 1;
7177         break;
7178       }
7179
7180       // An add of negative one (subtract of one) will be selected as a DEC.
7181       if (C->getAPIntValue().isAllOnesValue()) {
7182         Opcode = X86ISD::DEC;
7183         NumOperands = 1;
7184         break;
7185       }
7186     }
7187
7188     // Otherwise use a regular EFLAGS-setting add.
7189     Opcode = X86ISD::ADD;
7190     NumOperands = 2;
7191     break;
7192   case ISD::AND: {
7193     // If the primary and result isn't used, don't bother using X86ISD::AND,
7194     // because a TEST instruction will be better.
7195     bool NonFlagUse = false;
7196     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7197            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7198       SDNode *User = *UI;
7199       unsigned UOpNo = UI.getOperandNo();
7200       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7201         // Look pass truncate.
7202         UOpNo = User->use_begin().getOperandNo();
7203         User = *User->use_begin();
7204       }
7205
7206       if (User->getOpcode() != ISD::BRCOND &&
7207           User->getOpcode() != ISD::SETCC &&
7208           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7209         NonFlagUse = true;
7210         break;
7211       }
7212     }
7213
7214     if (!NonFlagUse)
7215       break;
7216   }
7217     // FALL THROUGH
7218   case ISD::SUB:
7219   case ISD::OR:
7220   case ISD::XOR:
7221     // Due to the ISEL shortcoming noted above, be conservative if this op is
7222     // likely to be selected as part of a load-modify-store instruction.
7223     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7224            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7225       if (UI->getOpcode() == ISD::STORE)
7226         goto default_case;
7227
7228     // Otherwise use a regular EFLAGS-setting instruction.
7229     switch (Op.getNode()->getOpcode()) {
7230     default: llvm_unreachable("unexpected operator!");
7231     case ISD::SUB: Opcode = X86ISD::SUB; break;
7232     case ISD::OR:  Opcode = X86ISD::OR;  break;
7233     case ISD::XOR: Opcode = X86ISD::XOR; break;
7234     case ISD::AND: Opcode = X86ISD::AND; break;
7235     }
7236
7237     NumOperands = 2;
7238     break;
7239   case X86ISD::ADD:
7240   case X86ISD::SUB:
7241   case X86ISD::INC:
7242   case X86ISD::DEC:
7243   case X86ISD::OR:
7244   case X86ISD::XOR:
7245   case X86ISD::AND:
7246     return SDValue(Op.getNode(), 1);
7247   default:
7248   default_case:
7249     break;
7250   }
7251
7252   if (Opcode == 0)
7253     // Emit a CMP with 0, which is the TEST pattern.
7254     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7255                        DAG.getConstant(0, Op.getValueType()));
7256
7257   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7258   SmallVector<SDValue, 4> Ops;
7259   for (unsigned i = 0; i != NumOperands; ++i)
7260     Ops.push_back(Op.getOperand(i));
7261
7262   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7263   DAG.ReplaceAllUsesWith(Op, New);
7264   return SDValue(New.getNode(), 1);
7265 }
7266
7267 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7268 /// equivalent.
7269 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7270                                    SelectionDAG &DAG) const {
7271   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7272     if (C->getAPIntValue() == 0)
7273       return EmitTest(Op0, X86CC, DAG);
7274
7275   DebugLoc dl = Op0.getDebugLoc();
7276   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7277 }
7278
7279 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7280 /// if it's possible.
7281 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7282                                      DebugLoc dl, SelectionDAG &DAG) const {
7283   SDValue Op0 = And.getOperand(0);
7284   SDValue Op1 = And.getOperand(1);
7285   if (Op0.getOpcode() == ISD::TRUNCATE)
7286     Op0 = Op0.getOperand(0);
7287   if (Op1.getOpcode() == ISD::TRUNCATE)
7288     Op1 = Op1.getOperand(0);
7289
7290   SDValue LHS, RHS;
7291   if (Op1.getOpcode() == ISD::SHL)
7292     std::swap(Op0, Op1);
7293   if (Op0.getOpcode() == ISD::SHL) {
7294     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7295       if (And00C->getZExtValue() == 1) {
7296         // If we looked past a truncate, check that it's only truncating away
7297         // known zeros.
7298         unsigned BitWidth = Op0.getValueSizeInBits();
7299         unsigned AndBitWidth = And.getValueSizeInBits();
7300         if (BitWidth > AndBitWidth) {
7301           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7302           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7303           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7304             return SDValue();
7305         }
7306         LHS = Op1;
7307         RHS = Op0.getOperand(1);
7308       }
7309   } else if (Op1.getOpcode() == ISD::Constant) {
7310     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7311     SDValue AndLHS = Op0;
7312     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7313       LHS = AndLHS.getOperand(0);
7314       RHS = AndLHS.getOperand(1);
7315     }
7316   }
7317
7318   if (LHS.getNode()) {
7319     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7320     // instruction.  Since the shift amount is in-range-or-undefined, we know
7321     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7322     // the encoding for the i16 version is larger than the i32 version.
7323     // Also promote i16 to i32 for performance / code size reason.
7324     if (LHS.getValueType() == MVT::i8 ||
7325         LHS.getValueType() == MVT::i16)
7326       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7327
7328     // If the operand types disagree, extend the shift amount to match.  Since
7329     // BT ignores high bits (like shifts) we can use anyextend.
7330     if (LHS.getValueType() != RHS.getValueType())
7331       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7332
7333     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7334     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7335     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7336                        DAG.getConstant(Cond, MVT::i8), BT);
7337   }
7338
7339   return SDValue();
7340 }
7341
7342 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7343   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7344   SDValue Op0 = Op.getOperand(0);
7345   SDValue Op1 = Op.getOperand(1);
7346   DebugLoc dl = Op.getDebugLoc();
7347   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7348
7349   // Optimize to BT if possible.
7350   // Lower (X & (1 << N)) == 0 to BT(X, N).
7351   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7352   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7353   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7354       Op1.getOpcode() == ISD::Constant &&
7355       cast<ConstantSDNode>(Op1)->isNullValue() &&
7356       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7357     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7358     if (NewSetCC.getNode())
7359       return NewSetCC;
7360   }
7361
7362   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7363   // these.
7364   if (Op1.getOpcode() == ISD::Constant &&
7365       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7366        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7367       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7368
7369     // If the input is a setcc, then reuse the input setcc or use a new one with
7370     // the inverted condition.
7371     if (Op0.getOpcode() == X86ISD::SETCC) {
7372       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7373       bool Invert = (CC == ISD::SETNE) ^
7374         cast<ConstantSDNode>(Op1)->isNullValue();
7375       if (!Invert) return Op0;
7376
7377       CCode = X86::GetOppositeBranchCondition(CCode);
7378       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7379                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7380     }
7381   }
7382
7383   bool isFP = Op1.getValueType().isFloatingPoint();
7384   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7385   if (X86CC == X86::COND_INVALID)
7386     return SDValue();
7387
7388   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7389   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7390                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7391 }
7392
7393 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7394   SDValue Cond;
7395   SDValue Op0 = Op.getOperand(0);
7396   SDValue Op1 = Op.getOperand(1);
7397   SDValue CC = Op.getOperand(2);
7398   EVT VT = Op.getValueType();
7399   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7400   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7401   DebugLoc dl = Op.getDebugLoc();
7402
7403   if (isFP) {
7404     unsigned SSECC = 8;
7405     EVT VT0 = Op0.getValueType();
7406     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7407     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7408     bool Swap = false;
7409
7410     switch (SetCCOpcode) {
7411     default: break;
7412     case ISD::SETOEQ:
7413     case ISD::SETEQ:  SSECC = 0; break;
7414     case ISD::SETOGT:
7415     case ISD::SETGT: Swap = true; // Fallthrough
7416     case ISD::SETLT:
7417     case ISD::SETOLT: SSECC = 1; break;
7418     case ISD::SETOGE:
7419     case ISD::SETGE: Swap = true; // Fallthrough
7420     case ISD::SETLE:
7421     case ISD::SETOLE: SSECC = 2; break;
7422     case ISD::SETUO:  SSECC = 3; break;
7423     case ISD::SETUNE:
7424     case ISD::SETNE:  SSECC = 4; break;
7425     case ISD::SETULE: Swap = true;
7426     case ISD::SETUGE: SSECC = 5; break;
7427     case ISD::SETULT: Swap = true;
7428     case ISD::SETUGT: SSECC = 6; break;
7429     case ISD::SETO:   SSECC = 7; break;
7430     }
7431     if (Swap)
7432       std::swap(Op0, Op1);
7433
7434     // In the two special cases we can't handle, emit two comparisons.
7435     if (SSECC == 8) {
7436       if (SetCCOpcode == ISD::SETUEQ) {
7437         SDValue UNORD, EQ;
7438         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7439         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7440         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7441       }
7442       else if (SetCCOpcode == ISD::SETONE) {
7443         SDValue ORD, NEQ;
7444         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7445         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7446         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7447       }
7448       llvm_unreachable("Illegal FP comparison");
7449     }
7450     // Handle all other FP comparisons here.
7451     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7452   }
7453
7454   // We are handling one of the integer comparisons here.  Since SSE only has
7455   // GT and EQ comparisons for integer, swapping operands and multiple
7456   // operations may be required for some comparisons.
7457   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7458   bool Swap = false, Invert = false, FlipSigns = false;
7459
7460   switch (VT.getSimpleVT().SimpleTy) {
7461   default: break;
7462   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7463   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7464   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7465   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7466   }
7467
7468   switch (SetCCOpcode) {
7469   default: break;
7470   case ISD::SETNE:  Invert = true;
7471   case ISD::SETEQ:  Opc = EQOpc; break;
7472   case ISD::SETLT:  Swap = true;
7473   case ISD::SETGT:  Opc = GTOpc; break;
7474   case ISD::SETGE:  Swap = true;
7475   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7476   case ISD::SETULT: Swap = true;
7477   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7478   case ISD::SETUGE: Swap = true;
7479   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7480   }
7481   if (Swap)
7482     std::swap(Op0, Op1);
7483
7484   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7485   // bits of the inputs before performing those operations.
7486   if (FlipSigns) {
7487     EVT EltVT = VT.getVectorElementType();
7488     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7489                                       EltVT);
7490     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7491     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7492                                     SignBits.size());
7493     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7494     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7495   }
7496
7497   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7498
7499   // If the logical-not of the result is required, perform that now.
7500   if (Invert)
7501     Result = DAG.getNOT(dl, Result, VT);
7502
7503   return Result;
7504 }
7505
7506 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7507 static bool isX86LogicalCmp(SDValue Op) {
7508   unsigned Opc = Op.getNode()->getOpcode();
7509   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7510     return true;
7511   if (Op.getResNo() == 1 &&
7512       (Opc == X86ISD::ADD ||
7513        Opc == X86ISD::SUB ||
7514        Opc == X86ISD::ADC ||
7515        Opc == X86ISD::SBB ||
7516        Opc == X86ISD::SMUL ||
7517        Opc == X86ISD::UMUL ||
7518        Opc == X86ISD::INC ||
7519        Opc == X86ISD::DEC ||
7520        Opc == X86ISD::OR ||
7521        Opc == X86ISD::XOR ||
7522        Opc == X86ISD::AND))
7523     return true;
7524
7525   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7526     return true;
7527
7528   return false;
7529 }
7530
7531 static bool isZero(SDValue V) {
7532   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7533   return C && C->isNullValue();
7534 }
7535
7536 static bool isAllOnes(SDValue V) {
7537   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7538   return C && C->isAllOnesValue();
7539 }
7540
7541 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7542   bool addTest = true;
7543   SDValue Cond  = Op.getOperand(0);
7544   SDValue Op1 = Op.getOperand(1);
7545   SDValue Op2 = Op.getOperand(2);
7546   DebugLoc DL = Op.getDebugLoc();
7547   SDValue CC;
7548
7549   if (Cond.getOpcode() == ISD::SETCC) {
7550     SDValue NewCond = LowerSETCC(Cond, DAG);
7551     if (NewCond.getNode())
7552       Cond = NewCond;
7553   }
7554
7555   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7556   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7557   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7558   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7559   if (Cond.getOpcode() == X86ISD::SETCC &&
7560       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7561       isZero(Cond.getOperand(1).getOperand(1))) {
7562     SDValue Cmp = Cond.getOperand(1);
7563
7564     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7565
7566     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7567         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7568       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7569
7570       SDValue CmpOp0 = Cmp.getOperand(0);
7571       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7572                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7573
7574       SDValue Res =   // Res = 0 or -1.
7575         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7576                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7577
7578       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7579         Res = DAG.getNOT(DL, Res, Res.getValueType());
7580
7581       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7582       if (N2C == 0 || !N2C->isNullValue())
7583         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7584       return Res;
7585     }
7586   }
7587
7588   // Look past (and (setcc_carry (cmp ...)), 1).
7589   if (Cond.getOpcode() == ISD::AND &&
7590       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7591     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7592     if (C && C->getAPIntValue() == 1)
7593       Cond = Cond.getOperand(0);
7594   }
7595
7596   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7597   // setting operand in place of the X86ISD::SETCC.
7598   if (Cond.getOpcode() == X86ISD::SETCC ||
7599       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7600     CC = Cond.getOperand(0);
7601
7602     SDValue Cmp = Cond.getOperand(1);
7603     unsigned Opc = Cmp.getOpcode();
7604     EVT VT = Op.getValueType();
7605
7606     bool IllegalFPCMov = false;
7607     if (VT.isFloatingPoint() && !VT.isVector() &&
7608         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7609       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7610
7611     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7612         Opc == X86ISD::BT) { // FIXME
7613       Cond = Cmp;
7614       addTest = false;
7615     }
7616   }
7617
7618   if (addTest) {
7619     // Look pass the truncate.
7620     if (Cond.getOpcode() == ISD::TRUNCATE)
7621       Cond = Cond.getOperand(0);
7622
7623     // We know the result of AND is compared against zero. Try to match
7624     // it to BT.
7625     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7626       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7627       if (NewSetCC.getNode()) {
7628         CC = NewSetCC.getOperand(0);
7629         Cond = NewSetCC.getOperand(1);
7630         addTest = false;
7631       }
7632     }
7633   }
7634
7635   if (addTest) {
7636     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7637     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7638   }
7639
7640   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7641   // a <  b ?  0 : -1 -> RES = setcc_carry
7642   // a >= b ? -1 :  0 -> RES = setcc_carry
7643   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7644   if (Cond.getOpcode() == X86ISD::CMP) {
7645     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7646
7647     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7648         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7649       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7650                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7651       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7652         return DAG.getNOT(DL, Res, Res.getValueType());
7653       return Res;
7654     }
7655   }
7656
7657   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7658   // condition is true.
7659   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7660   SDValue Ops[] = { Op2, Op1, CC, Cond };
7661   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7662 }
7663
7664 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7665 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7666 // from the AND / OR.
7667 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7668   Opc = Op.getOpcode();
7669   if (Opc != ISD::OR && Opc != ISD::AND)
7670     return false;
7671   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7672           Op.getOperand(0).hasOneUse() &&
7673           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7674           Op.getOperand(1).hasOneUse());
7675 }
7676
7677 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7678 // 1 and that the SETCC node has a single use.
7679 static bool isXor1OfSetCC(SDValue Op) {
7680   if (Op.getOpcode() != ISD::XOR)
7681     return false;
7682   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7683   if (N1C && N1C->getAPIntValue() == 1) {
7684     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7685       Op.getOperand(0).hasOneUse();
7686   }
7687   return false;
7688 }
7689
7690 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7691   bool addTest = true;
7692   SDValue Chain = Op.getOperand(0);
7693   SDValue Cond  = Op.getOperand(1);
7694   SDValue Dest  = Op.getOperand(2);
7695   DebugLoc dl = Op.getDebugLoc();
7696   SDValue CC;
7697
7698   if (Cond.getOpcode() == ISD::SETCC) {
7699     SDValue NewCond = LowerSETCC(Cond, DAG);
7700     if (NewCond.getNode())
7701       Cond = NewCond;
7702   }
7703 #if 0
7704   // FIXME: LowerXALUO doesn't handle these!!
7705   else if (Cond.getOpcode() == X86ISD::ADD  ||
7706            Cond.getOpcode() == X86ISD::SUB  ||
7707            Cond.getOpcode() == X86ISD::SMUL ||
7708            Cond.getOpcode() == X86ISD::UMUL)
7709     Cond = LowerXALUO(Cond, DAG);
7710 #endif
7711
7712   // Look pass (and (setcc_carry (cmp ...)), 1).
7713   if (Cond.getOpcode() == ISD::AND &&
7714       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7715     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7716     if (C && C->getAPIntValue() == 1)
7717       Cond = Cond.getOperand(0);
7718   }
7719
7720   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7721   // setting operand in place of the X86ISD::SETCC.
7722   if (Cond.getOpcode() == X86ISD::SETCC ||
7723       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7724     CC = Cond.getOperand(0);
7725
7726     SDValue Cmp = Cond.getOperand(1);
7727     unsigned Opc = Cmp.getOpcode();
7728     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7729     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7730       Cond = Cmp;
7731       addTest = false;
7732     } else {
7733       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7734       default: break;
7735       case X86::COND_O:
7736       case X86::COND_B:
7737         // These can only come from an arithmetic instruction with overflow,
7738         // e.g. SADDO, UADDO.
7739         Cond = Cond.getNode()->getOperand(1);
7740         addTest = false;
7741         break;
7742       }
7743     }
7744   } else {
7745     unsigned CondOpc;
7746     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7747       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7748       if (CondOpc == ISD::OR) {
7749         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7750         // two branches instead of an explicit OR instruction with a
7751         // separate test.
7752         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7753             isX86LogicalCmp(Cmp)) {
7754           CC = Cond.getOperand(0).getOperand(0);
7755           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7756                               Chain, Dest, CC, Cmp);
7757           CC = Cond.getOperand(1).getOperand(0);
7758           Cond = Cmp;
7759           addTest = false;
7760         }
7761       } else { // ISD::AND
7762         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7763         // two branches instead of an explicit AND instruction with a
7764         // separate test. However, we only do this if this block doesn't
7765         // have a fall-through edge, because this requires an explicit
7766         // jmp when the condition is false.
7767         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7768             isX86LogicalCmp(Cmp) &&
7769             Op.getNode()->hasOneUse()) {
7770           X86::CondCode CCode =
7771             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7772           CCode = X86::GetOppositeBranchCondition(CCode);
7773           CC = DAG.getConstant(CCode, MVT::i8);
7774           SDNode *User = *Op.getNode()->use_begin();
7775           // Look for an unconditional branch following this conditional branch.
7776           // We need this because we need to reverse the successors in order
7777           // to implement FCMP_OEQ.
7778           if (User->getOpcode() == ISD::BR) {
7779             SDValue FalseBB = User->getOperand(1);
7780             SDNode *NewBR =
7781               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7782             assert(NewBR == User);
7783             (void)NewBR;
7784             Dest = FalseBB;
7785
7786             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7787                                 Chain, Dest, CC, Cmp);
7788             X86::CondCode CCode =
7789               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7790             CCode = X86::GetOppositeBranchCondition(CCode);
7791             CC = DAG.getConstant(CCode, MVT::i8);
7792             Cond = Cmp;
7793             addTest = false;
7794           }
7795         }
7796       }
7797     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7798       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7799       // It should be transformed during dag combiner except when the condition
7800       // is set by a arithmetics with overflow node.
7801       X86::CondCode CCode =
7802         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7803       CCode = X86::GetOppositeBranchCondition(CCode);
7804       CC = DAG.getConstant(CCode, MVT::i8);
7805       Cond = Cond.getOperand(0).getOperand(1);
7806       addTest = false;
7807     }
7808   }
7809
7810   if (addTest) {
7811     // Look pass the truncate.
7812     if (Cond.getOpcode() == ISD::TRUNCATE)
7813       Cond = Cond.getOperand(0);
7814
7815     // We know the result of AND is compared against zero. Try to match
7816     // it to BT.
7817     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7818       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7819       if (NewSetCC.getNode()) {
7820         CC = NewSetCC.getOperand(0);
7821         Cond = NewSetCC.getOperand(1);
7822         addTest = false;
7823       }
7824     }
7825   }
7826
7827   if (addTest) {
7828     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7829     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7830   }
7831   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7832                      Chain, Dest, CC, Cond);
7833 }
7834
7835
7836 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7837 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7838 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7839 // that the guard pages used by the OS virtual memory manager are allocated in
7840 // correct sequence.
7841 SDValue
7842 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7843                                            SelectionDAG &DAG) const {
7844   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7845          "This should be used only on Windows targets");
7846   DebugLoc dl = Op.getDebugLoc();
7847
7848   // Get the inputs.
7849   SDValue Chain = Op.getOperand(0);
7850   SDValue Size  = Op.getOperand(1);
7851   // FIXME: Ensure alignment here
7852
7853   SDValue Flag;
7854
7855   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7856
7857   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7858   Flag = Chain.getValue(1);
7859
7860   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7861
7862   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7863   Flag = Chain.getValue(1);
7864
7865   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7866
7867   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7868   return DAG.getMergeValues(Ops1, 2, dl);
7869 }
7870
7871 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7872   MachineFunction &MF = DAG.getMachineFunction();
7873   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7874
7875   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7876   DebugLoc DL = Op.getDebugLoc();
7877
7878   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7879     // vastart just stores the address of the VarArgsFrameIndex slot into the
7880     // memory location argument.
7881     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7882                                    getPointerTy());
7883     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7884                         MachinePointerInfo(SV), false, false, 0);
7885   }
7886
7887   // __va_list_tag:
7888   //   gp_offset         (0 - 6 * 8)
7889   //   fp_offset         (48 - 48 + 8 * 16)
7890   //   overflow_arg_area (point to parameters coming in memory).
7891   //   reg_save_area
7892   SmallVector<SDValue, 8> MemOps;
7893   SDValue FIN = Op.getOperand(1);
7894   // Store gp_offset
7895   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7896                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7897                                                MVT::i32),
7898                                FIN, MachinePointerInfo(SV), false, false, 0);
7899   MemOps.push_back(Store);
7900
7901   // Store fp_offset
7902   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7903                     FIN, DAG.getIntPtrConstant(4));
7904   Store = DAG.getStore(Op.getOperand(0), DL,
7905                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7906                                        MVT::i32),
7907                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7908   MemOps.push_back(Store);
7909
7910   // Store ptr to overflow_arg_area
7911   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7912                     FIN, DAG.getIntPtrConstant(4));
7913   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7914                                     getPointerTy());
7915   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7916                        MachinePointerInfo(SV, 8),
7917                        false, false, 0);
7918   MemOps.push_back(Store);
7919
7920   // Store ptr to reg_save_area.
7921   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7922                     FIN, DAG.getIntPtrConstant(8));
7923   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7924                                     getPointerTy());
7925   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7926                        MachinePointerInfo(SV, 16), false, false, 0);
7927   MemOps.push_back(Store);
7928   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7929                      &MemOps[0], MemOps.size());
7930 }
7931
7932 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7933   assert(Subtarget->is64Bit() &&
7934          "LowerVAARG only handles 64-bit va_arg!");
7935   assert((Subtarget->isTargetLinux() ||
7936           Subtarget->isTargetDarwin()) &&
7937           "Unhandled target in LowerVAARG");
7938   assert(Op.getNode()->getNumOperands() == 4);
7939   SDValue Chain = Op.getOperand(0);
7940   SDValue SrcPtr = Op.getOperand(1);
7941   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7942   unsigned Align = Op.getConstantOperandVal(3);
7943   DebugLoc dl = Op.getDebugLoc();
7944
7945   EVT ArgVT = Op.getNode()->getValueType(0);
7946   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7947   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7948   uint8_t ArgMode;
7949
7950   // Decide which area this value should be read from.
7951   // TODO: Implement the AMD64 ABI in its entirety. This simple
7952   // selection mechanism works only for the basic types.
7953   if (ArgVT == MVT::f80) {
7954     llvm_unreachable("va_arg for f80 not yet implemented");
7955   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7956     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7957   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7958     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7959   } else {
7960     llvm_unreachable("Unhandled argument type in LowerVAARG");
7961   }
7962
7963   if (ArgMode == 2) {
7964     // Sanity Check: Make sure using fp_offset makes sense.
7965     assert(!UseSoftFloat &&
7966            !(DAG.getMachineFunction()
7967                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7968            Subtarget->hasXMM());
7969   }
7970
7971   // Insert VAARG_64 node into the DAG
7972   // VAARG_64 returns two values: Variable Argument Address, Chain
7973   SmallVector<SDValue, 11> InstOps;
7974   InstOps.push_back(Chain);
7975   InstOps.push_back(SrcPtr);
7976   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7977   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7978   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7979   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7980   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7981                                           VTs, &InstOps[0], InstOps.size(),
7982                                           MVT::i64,
7983                                           MachinePointerInfo(SV),
7984                                           /*Align=*/0,
7985                                           /*Volatile=*/false,
7986                                           /*ReadMem=*/true,
7987                                           /*WriteMem=*/true);
7988   Chain = VAARG.getValue(1);
7989
7990   // Load the next argument and return it
7991   return DAG.getLoad(ArgVT, dl,
7992                      Chain,
7993                      VAARG,
7994                      MachinePointerInfo(),
7995                      false, false, 0);
7996 }
7997
7998 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7999   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8000   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8001   SDValue Chain = Op.getOperand(0);
8002   SDValue DstPtr = Op.getOperand(1);
8003   SDValue SrcPtr = Op.getOperand(2);
8004   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8005   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8006   DebugLoc DL = Op.getDebugLoc();
8007
8008   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8009                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8010                        false,
8011                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8012 }
8013
8014 SDValue
8015 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8016   DebugLoc dl = Op.getDebugLoc();
8017   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8018   switch (IntNo) {
8019   default: return SDValue();    // Don't custom lower most intrinsics.
8020   // Comparison intrinsics.
8021   case Intrinsic::x86_sse_comieq_ss:
8022   case Intrinsic::x86_sse_comilt_ss:
8023   case Intrinsic::x86_sse_comile_ss:
8024   case Intrinsic::x86_sse_comigt_ss:
8025   case Intrinsic::x86_sse_comige_ss:
8026   case Intrinsic::x86_sse_comineq_ss:
8027   case Intrinsic::x86_sse_ucomieq_ss:
8028   case Intrinsic::x86_sse_ucomilt_ss:
8029   case Intrinsic::x86_sse_ucomile_ss:
8030   case Intrinsic::x86_sse_ucomigt_ss:
8031   case Intrinsic::x86_sse_ucomige_ss:
8032   case Intrinsic::x86_sse_ucomineq_ss:
8033   case Intrinsic::x86_sse2_comieq_sd:
8034   case Intrinsic::x86_sse2_comilt_sd:
8035   case Intrinsic::x86_sse2_comile_sd:
8036   case Intrinsic::x86_sse2_comigt_sd:
8037   case Intrinsic::x86_sse2_comige_sd:
8038   case Intrinsic::x86_sse2_comineq_sd:
8039   case Intrinsic::x86_sse2_ucomieq_sd:
8040   case Intrinsic::x86_sse2_ucomilt_sd:
8041   case Intrinsic::x86_sse2_ucomile_sd:
8042   case Intrinsic::x86_sse2_ucomigt_sd:
8043   case Intrinsic::x86_sse2_ucomige_sd:
8044   case Intrinsic::x86_sse2_ucomineq_sd: {
8045     unsigned Opc = 0;
8046     ISD::CondCode CC = ISD::SETCC_INVALID;
8047     switch (IntNo) {
8048     default: break;
8049     case Intrinsic::x86_sse_comieq_ss:
8050     case Intrinsic::x86_sse2_comieq_sd:
8051       Opc = X86ISD::COMI;
8052       CC = ISD::SETEQ;
8053       break;
8054     case Intrinsic::x86_sse_comilt_ss:
8055     case Intrinsic::x86_sse2_comilt_sd:
8056       Opc = X86ISD::COMI;
8057       CC = ISD::SETLT;
8058       break;
8059     case Intrinsic::x86_sse_comile_ss:
8060     case Intrinsic::x86_sse2_comile_sd:
8061       Opc = X86ISD::COMI;
8062       CC = ISD::SETLE;
8063       break;
8064     case Intrinsic::x86_sse_comigt_ss:
8065     case Intrinsic::x86_sse2_comigt_sd:
8066       Opc = X86ISD::COMI;
8067       CC = ISD::SETGT;
8068       break;
8069     case Intrinsic::x86_sse_comige_ss:
8070     case Intrinsic::x86_sse2_comige_sd:
8071       Opc = X86ISD::COMI;
8072       CC = ISD::SETGE;
8073       break;
8074     case Intrinsic::x86_sse_comineq_ss:
8075     case Intrinsic::x86_sse2_comineq_sd:
8076       Opc = X86ISD::COMI;
8077       CC = ISD::SETNE;
8078       break;
8079     case Intrinsic::x86_sse_ucomieq_ss:
8080     case Intrinsic::x86_sse2_ucomieq_sd:
8081       Opc = X86ISD::UCOMI;
8082       CC = ISD::SETEQ;
8083       break;
8084     case Intrinsic::x86_sse_ucomilt_ss:
8085     case Intrinsic::x86_sse2_ucomilt_sd:
8086       Opc = X86ISD::UCOMI;
8087       CC = ISD::SETLT;
8088       break;
8089     case Intrinsic::x86_sse_ucomile_ss:
8090     case Intrinsic::x86_sse2_ucomile_sd:
8091       Opc = X86ISD::UCOMI;
8092       CC = ISD::SETLE;
8093       break;
8094     case Intrinsic::x86_sse_ucomigt_ss:
8095     case Intrinsic::x86_sse2_ucomigt_sd:
8096       Opc = X86ISD::UCOMI;
8097       CC = ISD::SETGT;
8098       break;
8099     case Intrinsic::x86_sse_ucomige_ss:
8100     case Intrinsic::x86_sse2_ucomige_sd:
8101       Opc = X86ISD::UCOMI;
8102       CC = ISD::SETGE;
8103       break;
8104     case Intrinsic::x86_sse_ucomineq_ss:
8105     case Intrinsic::x86_sse2_ucomineq_sd:
8106       Opc = X86ISD::UCOMI;
8107       CC = ISD::SETNE;
8108       break;
8109     }
8110
8111     SDValue LHS = Op.getOperand(1);
8112     SDValue RHS = Op.getOperand(2);
8113     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8114     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8115     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8116     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8117                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8118     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8119   }
8120   // ptest and testp intrinsics. The intrinsic these come from are designed to
8121   // return an integer value, not just an instruction so lower it to the ptest
8122   // or testp pattern and a setcc for the result.
8123   case Intrinsic::x86_sse41_ptestz:
8124   case Intrinsic::x86_sse41_ptestc:
8125   case Intrinsic::x86_sse41_ptestnzc:
8126   case Intrinsic::x86_avx_ptestz_256:
8127   case Intrinsic::x86_avx_ptestc_256:
8128   case Intrinsic::x86_avx_ptestnzc_256:
8129   case Intrinsic::x86_avx_vtestz_ps:
8130   case Intrinsic::x86_avx_vtestc_ps:
8131   case Intrinsic::x86_avx_vtestnzc_ps:
8132   case Intrinsic::x86_avx_vtestz_pd:
8133   case Intrinsic::x86_avx_vtestc_pd:
8134   case Intrinsic::x86_avx_vtestnzc_pd:
8135   case Intrinsic::x86_avx_vtestz_ps_256:
8136   case Intrinsic::x86_avx_vtestc_ps_256:
8137   case Intrinsic::x86_avx_vtestnzc_ps_256:
8138   case Intrinsic::x86_avx_vtestz_pd_256:
8139   case Intrinsic::x86_avx_vtestc_pd_256:
8140   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8141     bool IsTestPacked = false;
8142     unsigned X86CC = 0;
8143     switch (IntNo) {
8144     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8145     case Intrinsic::x86_avx_vtestz_ps:
8146     case Intrinsic::x86_avx_vtestz_pd:
8147     case Intrinsic::x86_avx_vtestz_ps_256:
8148     case Intrinsic::x86_avx_vtestz_pd_256:
8149       IsTestPacked = true; // Fallthrough
8150     case Intrinsic::x86_sse41_ptestz:
8151     case Intrinsic::x86_avx_ptestz_256:
8152       // ZF = 1
8153       X86CC = X86::COND_E;
8154       break;
8155     case Intrinsic::x86_avx_vtestc_ps:
8156     case Intrinsic::x86_avx_vtestc_pd:
8157     case Intrinsic::x86_avx_vtestc_ps_256:
8158     case Intrinsic::x86_avx_vtestc_pd_256:
8159       IsTestPacked = true; // Fallthrough
8160     case Intrinsic::x86_sse41_ptestc:
8161     case Intrinsic::x86_avx_ptestc_256:
8162       // CF = 1
8163       X86CC = X86::COND_B;
8164       break;
8165     case Intrinsic::x86_avx_vtestnzc_ps:
8166     case Intrinsic::x86_avx_vtestnzc_pd:
8167     case Intrinsic::x86_avx_vtestnzc_ps_256:
8168     case Intrinsic::x86_avx_vtestnzc_pd_256:
8169       IsTestPacked = true; // Fallthrough
8170     case Intrinsic::x86_sse41_ptestnzc:
8171     case Intrinsic::x86_avx_ptestnzc_256:
8172       // ZF and CF = 0
8173       X86CC = X86::COND_A;
8174       break;
8175     }
8176
8177     SDValue LHS = Op.getOperand(1);
8178     SDValue RHS = Op.getOperand(2);
8179     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8180     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8181     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8182     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8183     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8184   }
8185
8186   // Fix vector shift instructions where the last operand is a non-immediate
8187   // i32 value.
8188   case Intrinsic::x86_sse2_pslli_w:
8189   case Intrinsic::x86_sse2_pslli_d:
8190   case Intrinsic::x86_sse2_pslli_q:
8191   case Intrinsic::x86_sse2_psrli_w:
8192   case Intrinsic::x86_sse2_psrli_d:
8193   case Intrinsic::x86_sse2_psrli_q:
8194   case Intrinsic::x86_sse2_psrai_w:
8195   case Intrinsic::x86_sse2_psrai_d:
8196   case Intrinsic::x86_mmx_pslli_w:
8197   case Intrinsic::x86_mmx_pslli_d:
8198   case Intrinsic::x86_mmx_pslli_q:
8199   case Intrinsic::x86_mmx_psrli_w:
8200   case Intrinsic::x86_mmx_psrli_d:
8201   case Intrinsic::x86_mmx_psrli_q:
8202   case Intrinsic::x86_mmx_psrai_w:
8203   case Intrinsic::x86_mmx_psrai_d: {
8204     SDValue ShAmt = Op.getOperand(2);
8205     if (isa<ConstantSDNode>(ShAmt))
8206       return SDValue();
8207
8208     unsigned NewIntNo = 0;
8209     EVT ShAmtVT = MVT::v4i32;
8210     switch (IntNo) {
8211     case Intrinsic::x86_sse2_pslli_w:
8212       NewIntNo = Intrinsic::x86_sse2_psll_w;
8213       break;
8214     case Intrinsic::x86_sse2_pslli_d:
8215       NewIntNo = Intrinsic::x86_sse2_psll_d;
8216       break;
8217     case Intrinsic::x86_sse2_pslli_q:
8218       NewIntNo = Intrinsic::x86_sse2_psll_q;
8219       break;
8220     case Intrinsic::x86_sse2_psrli_w:
8221       NewIntNo = Intrinsic::x86_sse2_psrl_w;
8222       break;
8223     case Intrinsic::x86_sse2_psrli_d:
8224       NewIntNo = Intrinsic::x86_sse2_psrl_d;
8225       break;
8226     case Intrinsic::x86_sse2_psrli_q:
8227       NewIntNo = Intrinsic::x86_sse2_psrl_q;
8228       break;
8229     case Intrinsic::x86_sse2_psrai_w:
8230       NewIntNo = Intrinsic::x86_sse2_psra_w;
8231       break;
8232     case Intrinsic::x86_sse2_psrai_d:
8233       NewIntNo = Intrinsic::x86_sse2_psra_d;
8234       break;
8235     default: {
8236       ShAmtVT = MVT::v2i32;
8237       switch (IntNo) {
8238       case Intrinsic::x86_mmx_pslli_w:
8239         NewIntNo = Intrinsic::x86_mmx_psll_w;
8240         break;
8241       case Intrinsic::x86_mmx_pslli_d:
8242         NewIntNo = Intrinsic::x86_mmx_psll_d;
8243         break;
8244       case Intrinsic::x86_mmx_pslli_q:
8245         NewIntNo = Intrinsic::x86_mmx_psll_q;
8246         break;
8247       case Intrinsic::x86_mmx_psrli_w:
8248         NewIntNo = Intrinsic::x86_mmx_psrl_w;
8249         break;
8250       case Intrinsic::x86_mmx_psrli_d:
8251         NewIntNo = Intrinsic::x86_mmx_psrl_d;
8252         break;
8253       case Intrinsic::x86_mmx_psrli_q:
8254         NewIntNo = Intrinsic::x86_mmx_psrl_q;
8255         break;
8256       case Intrinsic::x86_mmx_psrai_w:
8257         NewIntNo = Intrinsic::x86_mmx_psra_w;
8258         break;
8259       case Intrinsic::x86_mmx_psrai_d:
8260         NewIntNo = Intrinsic::x86_mmx_psra_d;
8261         break;
8262       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8263       }
8264       break;
8265     }
8266     }
8267
8268     // The vector shift intrinsics with scalars uses 32b shift amounts but
8269     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
8270     // to be zero.
8271     SDValue ShOps[4];
8272     ShOps[0] = ShAmt;
8273     ShOps[1] = DAG.getConstant(0, MVT::i32);
8274     if (ShAmtVT == MVT::v4i32) {
8275       ShOps[2] = DAG.getUNDEF(MVT::i32);
8276       ShOps[3] = DAG.getUNDEF(MVT::i32);
8277       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
8278     } else {
8279       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
8280 // FIXME this must be lowered to get rid of the invalid type.
8281     }
8282
8283     EVT VT = Op.getValueType();
8284     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
8285     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8286                        DAG.getConstant(NewIntNo, MVT::i32),
8287                        Op.getOperand(1), ShAmt);
8288   }
8289   }
8290 }
8291
8292 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
8293                                            SelectionDAG &DAG) const {
8294   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8295   MFI->setReturnAddressIsTaken(true);
8296
8297   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8298   DebugLoc dl = Op.getDebugLoc();
8299
8300   if (Depth > 0) {
8301     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8302     SDValue Offset =
8303       DAG.getConstant(TD->getPointerSize(),
8304                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8305     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8306                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8307                                    FrameAddr, Offset),
8308                        MachinePointerInfo(), false, false, 0);
8309   }
8310
8311   // Just load the return address.
8312   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
8313   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8314                      RetAddrFI, MachinePointerInfo(), false, false, 0);
8315 }
8316
8317 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
8318   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8319   MFI->setFrameAddressIsTaken(true);
8320
8321   EVT VT = Op.getValueType();
8322   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
8323   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8324   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8325   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8326   while (Depth--)
8327     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8328                             MachinePointerInfo(),
8329                             false, false, 0);
8330   return FrameAddr;
8331 }
8332
8333 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8334                                                      SelectionDAG &DAG) const {
8335   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8336 }
8337
8338 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8339   MachineFunction &MF = DAG.getMachineFunction();
8340   SDValue Chain     = Op.getOperand(0);
8341   SDValue Offset    = Op.getOperand(1);
8342   SDValue Handler   = Op.getOperand(2);
8343   DebugLoc dl       = Op.getDebugLoc();
8344
8345   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8346                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8347                                      getPointerTy());
8348   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8349
8350   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8351                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8352   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8353   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8354                        false, false, 0);
8355   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8356   MF.getRegInfo().addLiveOut(StoreAddrReg);
8357
8358   return DAG.getNode(X86ISD::EH_RETURN, dl,
8359                      MVT::Other,
8360                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8361 }
8362
8363 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8364                                              SelectionDAG &DAG) const {
8365   SDValue Root = Op.getOperand(0);
8366   SDValue Trmp = Op.getOperand(1); // trampoline
8367   SDValue FPtr = Op.getOperand(2); // nested function
8368   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8369   DebugLoc dl  = Op.getDebugLoc();
8370
8371   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8372
8373   if (Subtarget->is64Bit()) {
8374     SDValue OutChains[6];
8375
8376     // Large code-model.
8377     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8378     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8379
8380     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8381     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8382
8383     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8384
8385     // Load the pointer to the nested function into R11.
8386     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8387     SDValue Addr = Trmp;
8388     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8389                                 Addr, MachinePointerInfo(TrmpAddr),
8390                                 false, false, 0);
8391
8392     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8393                        DAG.getConstant(2, MVT::i64));
8394     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8395                                 MachinePointerInfo(TrmpAddr, 2),
8396                                 false, false, 2);
8397
8398     // Load the 'nest' parameter value into R10.
8399     // R10 is specified in X86CallingConv.td
8400     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8401     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8402                        DAG.getConstant(10, MVT::i64));
8403     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8404                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8405                                 false, false, 0);
8406
8407     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8408                        DAG.getConstant(12, MVT::i64));
8409     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8410                                 MachinePointerInfo(TrmpAddr, 12),
8411                                 false, false, 2);
8412
8413     // Jump to the nested function.
8414     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8415     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8416                        DAG.getConstant(20, MVT::i64));
8417     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8418                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8419                                 false, false, 0);
8420
8421     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8422     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8423                        DAG.getConstant(22, MVT::i64));
8424     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8425                                 MachinePointerInfo(TrmpAddr, 22),
8426                                 false, false, 0);
8427
8428     SDValue Ops[] =
8429       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8430     return DAG.getMergeValues(Ops, 2, dl);
8431   } else {
8432     const Function *Func =
8433       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8434     CallingConv::ID CC = Func->getCallingConv();
8435     unsigned NestReg;
8436
8437     switch (CC) {
8438     default:
8439       llvm_unreachable("Unsupported calling convention");
8440     case CallingConv::C:
8441     case CallingConv::X86_StdCall: {
8442       // Pass 'nest' parameter in ECX.
8443       // Must be kept in sync with X86CallingConv.td
8444       NestReg = X86::ECX;
8445
8446       // Check that ECX wasn't needed by an 'inreg' parameter.
8447       const FunctionType *FTy = Func->getFunctionType();
8448       const AttrListPtr &Attrs = Func->getAttributes();
8449
8450       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8451         unsigned InRegCount = 0;
8452         unsigned Idx = 1;
8453
8454         for (FunctionType::param_iterator I = FTy->param_begin(),
8455              E = FTy->param_end(); I != E; ++I, ++Idx)
8456           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8457             // FIXME: should only count parameters that are lowered to integers.
8458             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8459
8460         if (InRegCount > 2) {
8461           report_fatal_error("Nest register in use - reduce number of inreg"
8462                              " parameters!");
8463         }
8464       }
8465       break;
8466     }
8467     case CallingConv::X86_FastCall:
8468     case CallingConv::X86_ThisCall:
8469     case CallingConv::Fast:
8470       // Pass 'nest' parameter in EAX.
8471       // Must be kept in sync with X86CallingConv.td
8472       NestReg = X86::EAX;
8473       break;
8474     }
8475
8476     SDValue OutChains[4];
8477     SDValue Addr, Disp;
8478
8479     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8480                        DAG.getConstant(10, MVT::i32));
8481     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8482
8483     // This is storing the opcode for MOV32ri.
8484     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8485     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8486     OutChains[0] = DAG.getStore(Root, dl,
8487                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8488                                 Trmp, MachinePointerInfo(TrmpAddr),
8489                                 false, false, 0);
8490
8491     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8492                        DAG.getConstant(1, MVT::i32));
8493     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8494                                 MachinePointerInfo(TrmpAddr, 1),
8495                                 false, false, 1);
8496
8497     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8498     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8499                        DAG.getConstant(5, MVT::i32));
8500     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8501                                 MachinePointerInfo(TrmpAddr, 5),
8502                                 false, false, 1);
8503
8504     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8505                        DAG.getConstant(6, MVT::i32));
8506     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8507                                 MachinePointerInfo(TrmpAddr, 6),
8508                                 false, false, 1);
8509
8510     SDValue Ops[] =
8511       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8512     return DAG.getMergeValues(Ops, 2, dl);
8513   }
8514 }
8515
8516 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8517                                             SelectionDAG &DAG) const {
8518   /*
8519    The rounding mode is in bits 11:10 of FPSR, and has the following
8520    settings:
8521      00 Round to nearest
8522      01 Round to -inf
8523      10 Round to +inf
8524      11 Round to 0
8525
8526   FLT_ROUNDS, on the other hand, expects the following:
8527     -1 Undefined
8528      0 Round to 0
8529      1 Round to nearest
8530      2 Round to +inf
8531      3 Round to -inf
8532
8533   To perform the conversion, we do:
8534     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8535   */
8536
8537   MachineFunction &MF = DAG.getMachineFunction();
8538   const TargetMachine &TM = MF.getTarget();
8539   const TargetFrameLowering &TFI = *TM.getFrameLowering();
8540   unsigned StackAlignment = TFI.getStackAlignment();
8541   EVT VT = Op.getValueType();
8542   DebugLoc DL = Op.getDebugLoc();
8543
8544   // Save FP Control Word to stack slot
8545   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8546   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8547
8548
8549   MachineMemOperand *MMO =
8550    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8551                            MachineMemOperand::MOStore, 2, 2);
8552
8553   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8554   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8555                                           DAG.getVTList(MVT::Other),
8556                                           Ops, 2, MVT::i16, MMO);
8557
8558   // Load FP Control Word from stack slot
8559   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8560                             MachinePointerInfo(), false, false, 0);
8561
8562   // Transform as necessary
8563   SDValue CWD1 =
8564     DAG.getNode(ISD::SRL, DL, MVT::i16,
8565                 DAG.getNode(ISD::AND, DL, MVT::i16,
8566                             CWD, DAG.getConstant(0x800, MVT::i16)),
8567                 DAG.getConstant(11, MVT::i8));
8568   SDValue CWD2 =
8569     DAG.getNode(ISD::SRL, DL, MVT::i16,
8570                 DAG.getNode(ISD::AND, DL, MVT::i16,
8571                             CWD, DAG.getConstant(0x400, MVT::i16)),
8572                 DAG.getConstant(9, MVT::i8));
8573
8574   SDValue RetVal =
8575     DAG.getNode(ISD::AND, DL, MVT::i16,
8576                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8577                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8578                             DAG.getConstant(1, MVT::i16)),
8579                 DAG.getConstant(3, MVT::i16));
8580
8581
8582   return DAG.getNode((VT.getSizeInBits() < 16 ?
8583                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8584 }
8585
8586 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8587   EVT VT = Op.getValueType();
8588   EVT OpVT = VT;
8589   unsigned NumBits = VT.getSizeInBits();
8590   DebugLoc dl = Op.getDebugLoc();
8591
8592   Op = Op.getOperand(0);
8593   if (VT == MVT::i8) {
8594     // Zero extend to i32 since there is not an i8 bsr.
8595     OpVT = MVT::i32;
8596     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8597   }
8598
8599   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8600   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8601   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8602
8603   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8604   SDValue Ops[] = {
8605     Op,
8606     DAG.getConstant(NumBits+NumBits-1, OpVT),
8607     DAG.getConstant(X86::COND_E, MVT::i8),
8608     Op.getValue(1)
8609   };
8610   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8611
8612   // Finally xor with NumBits-1.
8613   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8614
8615   if (VT == MVT::i8)
8616     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8617   return Op;
8618 }
8619
8620 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8621   EVT VT = Op.getValueType();
8622   EVT OpVT = VT;
8623   unsigned NumBits = VT.getSizeInBits();
8624   DebugLoc dl = Op.getDebugLoc();
8625
8626   Op = Op.getOperand(0);
8627   if (VT == MVT::i8) {
8628     OpVT = MVT::i32;
8629     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8630   }
8631
8632   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8633   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8634   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8635
8636   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8637   SDValue Ops[] = {
8638     Op,
8639     DAG.getConstant(NumBits, OpVT),
8640     DAG.getConstant(X86::COND_E, MVT::i8),
8641     Op.getValue(1)
8642   };
8643   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8644
8645   if (VT == MVT::i8)
8646     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8647   return Op;
8648 }
8649
8650 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8651   EVT VT = Op.getValueType();
8652   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8653   DebugLoc dl = Op.getDebugLoc();
8654
8655   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8656   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8657   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8658   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8659   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8660   //
8661   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8662   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8663   //  return AloBlo + AloBhi + AhiBlo;
8664
8665   SDValue A = Op.getOperand(0);
8666   SDValue B = Op.getOperand(1);
8667
8668   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8669                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8670                        A, DAG.getConstant(32, MVT::i32));
8671   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8672                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8673                        B, DAG.getConstant(32, MVT::i32));
8674   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8675                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8676                        A, B);
8677   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8678                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8679                        A, Bhi);
8680   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8681                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8682                        Ahi, B);
8683   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8684                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8685                        AloBhi, DAG.getConstant(32, MVT::i32));
8686   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8687                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8688                        AhiBlo, DAG.getConstant(32, MVT::i32));
8689   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8690   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8691   return Res;
8692 }
8693
8694 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8695   EVT VT = Op.getValueType();
8696   DebugLoc dl = Op.getDebugLoc();
8697   SDValue R = Op.getOperand(0);
8698
8699   LLVMContext *Context = DAG.getContext();
8700
8701   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8702
8703   if (VT == MVT::v4i32) {
8704     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8705                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8706                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8707
8708     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8709
8710     std::vector<Constant*> CV(4, CI);
8711     Constant *C = ConstantVector::get(CV);
8712     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8713     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8714                                  MachinePointerInfo::getConstantPool(),
8715                                  false, false, 16);
8716
8717     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8718     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8719     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8720     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8721   }
8722   if (VT == MVT::v16i8) {
8723     // a = a << 5;
8724     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8725                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8726                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8727
8728     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8729     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8730
8731     std::vector<Constant*> CVM1(16, CM1);
8732     std::vector<Constant*> CVM2(16, CM2);
8733     Constant *C = ConstantVector::get(CVM1);
8734     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8735     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8736                             MachinePointerInfo::getConstantPool(),
8737                             false, false, 16);
8738
8739     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8740     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8741     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8742                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8743                     DAG.getConstant(4, MVT::i32));
8744     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8745     // a += a
8746     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8747
8748     C = ConstantVector::get(CVM2);
8749     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8750     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8751                     MachinePointerInfo::getConstantPool(),
8752                     false, false, 16);
8753
8754     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8755     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8756     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8757                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8758                     DAG.getConstant(2, MVT::i32));
8759     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8760     // a += a
8761     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8762
8763     // return pblendv(r, r+r, a);
8764     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
8765                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8766     return R;
8767   }
8768   return SDValue();
8769 }
8770
8771 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8772   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8773   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8774   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8775   // has only one use.
8776   SDNode *N = Op.getNode();
8777   SDValue LHS = N->getOperand(0);
8778   SDValue RHS = N->getOperand(1);
8779   unsigned BaseOp = 0;
8780   unsigned Cond = 0;
8781   DebugLoc DL = Op.getDebugLoc();
8782   switch (Op.getOpcode()) {
8783   default: llvm_unreachable("Unknown ovf instruction!");
8784   case ISD::SADDO:
8785     // A subtract of one will be selected as a INC. Note that INC doesn't
8786     // set CF, so we can't do this for UADDO.
8787     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8788       if (C->getAPIntValue() == 1) {
8789         BaseOp = X86ISD::INC;
8790         Cond = X86::COND_O;
8791         break;
8792       }
8793     BaseOp = X86ISD::ADD;
8794     Cond = X86::COND_O;
8795     break;
8796   case ISD::UADDO:
8797     BaseOp = X86ISD::ADD;
8798     Cond = X86::COND_B;
8799     break;
8800   case ISD::SSUBO:
8801     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8802     // set CF, so we can't do this for USUBO.
8803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8804       if (C->getAPIntValue() == 1) {
8805         BaseOp = X86ISD::DEC;
8806         Cond = X86::COND_O;
8807         break;
8808       }
8809     BaseOp = X86ISD::SUB;
8810     Cond = X86::COND_O;
8811     break;
8812   case ISD::USUBO:
8813     BaseOp = X86ISD::SUB;
8814     Cond = X86::COND_B;
8815     break;
8816   case ISD::SMULO:
8817     BaseOp = X86ISD::SMUL;
8818     Cond = X86::COND_O;
8819     break;
8820   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8821     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8822                                  MVT::i32);
8823     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8824
8825     SDValue SetCC =
8826       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8827                   DAG.getConstant(X86::COND_O, MVT::i32),
8828                   SDValue(Sum.getNode(), 2));
8829
8830     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8831     return Sum;
8832   }
8833   }
8834
8835   // Also sets EFLAGS.
8836   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8837   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8838
8839   SDValue SetCC =
8840     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8841                 DAG.getConstant(Cond, MVT::i32),
8842                 SDValue(Sum.getNode(), 1));
8843
8844   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8845   return Sum;
8846 }
8847
8848 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8849   DebugLoc dl = Op.getDebugLoc();
8850
8851   if (!Subtarget->hasSSE2()) {
8852     SDValue Chain = Op.getOperand(0);
8853     SDValue Zero = DAG.getConstant(0,
8854                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8855     SDValue Ops[] = {
8856       DAG.getRegister(X86::ESP, MVT::i32), // Base
8857       DAG.getTargetConstant(1, MVT::i8),   // Scale
8858       DAG.getRegister(0, MVT::i32),        // Index
8859       DAG.getTargetConstant(0, MVT::i32),  // Disp
8860       DAG.getRegister(0, MVT::i32),        // Segment.
8861       Zero,
8862       Chain
8863     };
8864     SDNode *Res =
8865       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8866                           array_lengthof(Ops));
8867     return SDValue(Res, 0);
8868   }
8869
8870   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8871   if (!isDev)
8872     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8873
8874   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8875   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8876   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8877   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8878
8879   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8880   if (!Op1 && !Op2 && !Op3 && Op4)
8881     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8882
8883   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8884   if (Op1 && !Op2 && !Op3 && !Op4)
8885     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8886
8887   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8888   //           (MFENCE)>;
8889   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8890 }
8891
8892 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8893   EVT T = Op.getValueType();
8894   DebugLoc DL = Op.getDebugLoc();
8895   unsigned Reg = 0;
8896   unsigned size = 0;
8897   switch(T.getSimpleVT().SimpleTy) {
8898   default:
8899     assert(false && "Invalid value type!");
8900   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8901   case MVT::i16: Reg = X86::AX;  size = 2; break;
8902   case MVT::i32: Reg = X86::EAX; size = 4; break;
8903   case MVT::i64:
8904     assert(Subtarget->is64Bit() && "Node not type legal!");
8905     Reg = X86::RAX; size = 8;
8906     break;
8907   }
8908   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8909                                     Op.getOperand(2), SDValue());
8910   SDValue Ops[] = { cpIn.getValue(0),
8911                     Op.getOperand(1),
8912                     Op.getOperand(3),
8913                     DAG.getTargetConstant(size, MVT::i8),
8914                     cpIn.getValue(1) };
8915   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8916   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8917   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8918                                            Ops, 5, T, MMO);
8919   SDValue cpOut =
8920     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8921   return cpOut;
8922 }
8923
8924 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8925                                                  SelectionDAG &DAG) const {
8926   assert(Subtarget->is64Bit() && "Result not type legalized?");
8927   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8928   SDValue TheChain = Op.getOperand(0);
8929   DebugLoc dl = Op.getDebugLoc();
8930   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8931   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8932   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8933                                    rax.getValue(2));
8934   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8935                             DAG.getConstant(32, MVT::i8));
8936   SDValue Ops[] = {
8937     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8938     rdx.getValue(1)
8939   };
8940   return DAG.getMergeValues(Ops, 2, dl);
8941 }
8942
8943 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8944                                             SelectionDAG &DAG) const {
8945   EVT SrcVT = Op.getOperand(0).getValueType();
8946   EVT DstVT = Op.getValueType();
8947   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8948          Subtarget->hasMMX() && "Unexpected custom BITCAST");
8949   assert((DstVT == MVT::i64 ||
8950           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8951          "Unexpected custom BITCAST");
8952   // i64 <=> MMX conversions are Legal.
8953   if (SrcVT==MVT::i64 && DstVT.isVector())
8954     return Op;
8955   if (DstVT==MVT::i64 && SrcVT.isVector())
8956     return Op;
8957   // MMX <=> MMX conversions are Legal.
8958   if (SrcVT.isVector() && DstVT.isVector())
8959     return Op;
8960   // All other conversions need to be expanded.
8961   return SDValue();
8962 }
8963
8964 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8965   SDNode *Node = Op.getNode();
8966   DebugLoc dl = Node->getDebugLoc();
8967   EVT T = Node->getValueType(0);
8968   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8969                               DAG.getConstant(0, T), Node->getOperand(2));
8970   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8971                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8972                        Node->getOperand(0),
8973                        Node->getOperand(1), negOp,
8974                        cast<AtomicSDNode>(Node)->getSrcValue(),
8975                        cast<AtomicSDNode>(Node)->getAlignment());
8976 }
8977
8978 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8979   EVT VT = Op.getNode()->getValueType(0);
8980
8981   // Let legalize expand this if it isn't a legal type yet.
8982   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8983     return SDValue();
8984
8985   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8986
8987   unsigned Opc;
8988   bool ExtraOp = false;
8989   switch (Op.getOpcode()) {
8990   default: assert(0 && "Invalid code");
8991   case ISD::ADDC: Opc = X86ISD::ADD; break;
8992   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8993   case ISD::SUBC: Opc = X86ISD::SUB; break;
8994   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8995   }
8996
8997   if (!ExtraOp)
8998     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8999                        Op.getOperand(1));
9000   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
9001                      Op.getOperand(1), Op.getOperand(2));
9002 }
9003
9004 /// LowerOperation - Provide custom lowering hooks for some operations.
9005 ///
9006 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9007   switch (Op.getOpcode()) {
9008   default: llvm_unreachable("Should not custom lower this!");
9009   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
9010   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
9011   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
9012   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9013   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
9014   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9015   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9016   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9017   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
9018   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
9019   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9020   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9021   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9022   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9023   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
9024   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9025   case ISD::SHL_PARTS:
9026   case ISD::SRA_PARTS:
9027   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
9028   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
9029   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
9030   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
9031   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
9032   case ISD::FABS:               return LowerFABS(Op, DAG);
9033   case ISD::FNEG:               return LowerFNEG(Op, DAG);
9034   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
9035   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9036   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
9037   case ISD::SELECT:             return LowerSELECT(Op, DAG);
9038   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
9039   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9040   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9041   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9042   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9043   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9044   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9045   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9046   case ISD::FRAME_TO_ARGS_OFFSET:
9047                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
9048   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9049   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
9050   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
9051   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9052   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
9053   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
9054   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
9055   case ISD::SHL:                return LowerSHL(Op, DAG);
9056   case ISD::SADDO:
9057   case ISD::UADDO:
9058   case ISD::SSUBO:
9059   case ISD::USUBO:
9060   case ISD::SMULO:
9061   case ISD::UMULO:              return LowerXALUO(Op, DAG);
9062   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
9063   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
9064   case ISD::ADDC:
9065   case ISD::ADDE:
9066   case ISD::SUBC:
9067   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
9068   }
9069 }
9070
9071 void X86TargetLowering::
9072 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
9073                         SelectionDAG &DAG, unsigned NewOp) const {
9074   EVT T = Node->getValueType(0);
9075   DebugLoc dl = Node->getDebugLoc();
9076   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
9077
9078   SDValue Chain = Node->getOperand(0);
9079   SDValue In1 = Node->getOperand(1);
9080   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9081                              Node->getOperand(2), DAG.getIntPtrConstant(0));
9082   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9083                              Node->getOperand(2), DAG.getIntPtrConstant(1));
9084   SDValue Ops[] = { Chain, In1, In2L, In2H };
9085   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9086   SDValue Result =
9087     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
9088                             cast<MemSDNode>(Node)->getMemOperand());
9089   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
9090   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9091   Results.push_back(Result.getValue(2));
9092 }
9093
9094 /// ReplaceNodeResults - Replace a node with an illegal result type
9095 /// with a new node built out of custom code.
9096 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
9097                                            SmallVectorImpl<SDValue>&Results,
9098                                            SelectionDAG &DAG) const {
9099   DebugLoc dl = N->getDebugLoc();
9100   switch (N->getOpcode()) {
9101   default:
9102     assert(false && "Do not know how to custom type legalize this operation!");
9103     return;
9104   case ISD::ADDC:
9105   case ISD::ADDE:
9106   case ISD::SUBC:
9107   case ISD::SUBE:
9108     // We don't want to expand or promote these.
9109     return;
9110   case ISD::FP_TO_SINT: {
9111     std::pair<SDValue,SDValue> Vals =
9112         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
9113     SDValue FIST = Vals.first, StackSlot = Vals.second;
9114     if (FIST.getNode() != 0) {
9115       EVT VT = N->getValueType(0);
9116       // Return a load from the stack slot.
9117       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
9118                                     MachinePointerInfo(), false, false, 0));
9119     }
9120     return;
9121   }
9122   case ISD::READCYCLECOUNTER: {
9123     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9124     SDValue TheChain = N->getOperand(0);
9125     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9126     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
9127                                      rd.getValue(1));
9128     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
9129                                      eax.getValue(2));
9130     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
9131     SDValue Ops[] = { eax, edx };
9132     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
9133     Results.push_back(edx.getValue(1));
9134     return;
9135   }
9136   case ISD::ATOMIC_CMP_SWAP: {
9137     EVT T = N->getValueType(0);
9138     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
9139     SDValue cpInL, cpInH;
9140     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9141                         DAG.getConstant(0, MVT::i32));
9142     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
9143                         DAG.getConstant(1, MVT::i32));
9144     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
9145     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
9146                              cpInL.getValue(1));
9147     SDValue swapInL, swapInH;
9148     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9149                           DAG.getConstant(0, MVT::i32));
9150     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
9151                           DAG.getConstant(1, MVT::i32));
9152     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
9153                                cpInH.getValue(1));
9154     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
9155                                swapInL.getValue(1));
9156     SDValue Ops[] = { swapInH.getValue(0),
9157                       N->getOperand(1),
9158                       swapInH.getValue(1) };
9159     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9160     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
9161     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
9162                                              Ops, 3, T, MMO);
9163     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
9164                                         MVT::i32, Result.getValue(1));
9165     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
9166                                         MVT::i32, cpOutL.getValue(2));
9167     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
9168     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
9169     Results.push_back(cpOutH.getValue(1));
9170     return;
9171   }
9172   case ISD::ATOMIC_LOAD_ADD:
9173     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
9174     return;
9175   case ISD::ATOMIC_LOAD_AND:
9176     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
9177     return;
9178   case ISD::ATOMIC_LOAD_NAND:
9179     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
9180     return;
9181   case ISD::ATOMIC_LOAD_OR:
9182     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
9183     return;
9184   case ISD::ATOMIC_LOAD_SUB:
9185     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
9186     return;
9187   case ISD::ATOMIC_LOAD_XOR:
9188     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
9189     return;
9190   case ISD::ATOMIC_SWAP:
9191     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
9192     return;
9193   }
9194 }
9195
9196 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
9197   switch (Opcode) {
9198   default: return NULL;
9199   case X86ISD::BSF:                return "X86ISD::BSF";
9200   case X86ISD::BSR:                return "X86ISD::BSR";
9201   case X86ISD::SHLD:               return "X86ISD::SHLD";
9202   case X86ISD::SHRD:               return "X86ISD::SHRD";
9203   case X86ISD::FAND:               return "X86ISD::FAND";
9204   case X86ISD::FOR:                return "X86ISD::FOR";
9205   case X86ISD::FXOR:               return "X86ISD::FXOR";
9206   case X86ISD::FSRL:               return "X86ISD::FSRL";
9207   case X86ISD::FILD:               return "X86ISD::FILD";
9208   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
9209   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
9210   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
9211   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
9212   case X86ISD::FLD:                return "X86ISD::FLD";
9213   case X86ISD::FST:                return "X86ISD::FST";
9214   case X86ISD::CALL:               return "X86ISD::CALL";
9215   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
9216   case X86ISD::BT:                 return "X86ISD::BT";
9217   case X86ISD::CMP:                return "X86ISD::CMP";
9218   case X86ISD::COMI:               return "X86ISD::COMI";
9219   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
9220   case X86ISD::SETCC:              return "X86ISD::SETCC";
9221   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
9222   case X86ISD::CMOV:               return "X86ISD::CMOV";
9223   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
9224   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
9225   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
9226   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
9227   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
9228   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
9229   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
9230   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
9231   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
9232   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
9233   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
9234   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
9235   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
9236   case X86ISD::PANDN:              return "X86ISD::PANDN";
9237   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
9238   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
9239   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
9240   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
9241   case X86ISD::FMAX:               return "X86ISD::FMAX";
9242   case X86ISD::FMIN:               return "X86ISD::FMIN";
9243   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
9244   case X86ISD::FRCP:               return "X86ISD::FRCP";
9245   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
9246   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
9247   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
9248   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
9249   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
9250   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
9251   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
9252   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
9253   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
9254   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
9255   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
9256   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
9257   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
9258   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
9259   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
9260   case X86ISD::VSHL:               return "X86ISD::VSHL";
9261   case X86ISD::VSRL:               return "X86ISD::VSRL";
9262   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
9263   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
9264   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
9265   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
9266   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
9267   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
9268   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
9269   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
9270   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
9271   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
9272   case X86ISD::ADD:                return "X86ISD::ADD";
9273   case X86ISD::SUB:                return "X86ISD::SUB";
9274   case X86ISD::ADC:                return "X86ISD::ADC";
9275   case X86ISD::SBB:                return "X86ISD::SBB";
9276   case X86ISD::SMUL:               return "X86ISD::SMUL";
9277   case X86ISD::UMUL:               return "X86ISD::UMUL";
9278   case X86ISD::INC:                return "X86ISD::INC";
9279   case X86ISD::DEC:                return "X86ISD::DEC";
9280   case X86ISD::OR:                 return "X86ISD::OR";
9281   case X86ISD::XOR:                return "X86ISD::XOR";
9282   case X86ISD::AND:                return "X86ISD::AND";
9283   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
9284   case X86ISD::PTEST:              return "X86ISD::PTEST";
9285   case X86ISD::TESTP:              return "X86ISD::TESTP";
9286   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
9287   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
9288   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
9289   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
9290   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
9291   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
9292   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
9293   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
9294   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
9295   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
9296   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
9297   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
9298   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
9299   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
9300   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
9301   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
9302   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
9303   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
9304   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
9305   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
9306   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
9307   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
9308   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
9309   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
9310   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
9311   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
9312   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
9313   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
9314   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
9315   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
9316   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
9317   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
9318   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
9319   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
9320   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
9321   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
9322   }
9323 }
9324
9325 // isLegalAddressingMode - Return true if the addressing mode represented
9326 // by AM is legal for this target, for a load/store of the specified type.
9327 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9328                                               const Type *Ty) const {
9329   // X86 supports extremely general addressing modes.
9330   CodeModel::Model M = getTargetMachine().getCodeModel();
9331   Reloc::Model R = getTargetMachine().getRelocationModel();
9332
9333   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9334   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9335     return false;
9336
9337   if (AM.BaseGV) {
9338     unsigned GVFlags =
9339       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9340
9341     // If a reference to this global requires an extra load, we can't fold it.
9342     if (isGlobalStubReference(GVFlags))
9343       return false;
9344
9345     // If BaseGV requires a register for the PIC base, we cannot also have a
9346     // BaseReg specified.
9347     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9348       return false;
9349
9350     // If lower 4G is not available, then we must use rip-relative addressing.
9351     if ((M != CodeModel::Small || R != Reloc::Static) &&
9352         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9353       return false;
9354   }
9355
9356   switch (AM.Scale) {
9357   case 0:
9358   case 1:
9359   case 2:
9360   case 4:
9361   case 8:
9362     // These scales always work.
9363     break;
9364   case 3:
9365   case 5:
9366   case 9:
9367     // These scales are formed with basereg+scalereg.  Only accept if there is
9368     // no basereg yet.
9369     if (AM.HasBaseReg)
9370       return false;
9371     break;
9372   default:  // Other stuff never works.
9373     return false;
9374   }
9375
9376   return true;
9377 }
9378
9379
9380 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9381   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9382     return false;
9383   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9384   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9385   if (NumBits1 <= NumBits2)
9386     return false;
9387   return true;
9388 }
9389
9390 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9391   if (!VT1.isInteger() || !VT2.isInteger())
9392     return false;
9393   unsigned NumBits1 = VT1.getSizeInBits();
9394   unsigned NumBits2 = VT2.getSizeInBits();
9395   if (NumBits1 <= NumBits2)
9396     return false;
9397   return true;
9398 }
9399
9400 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9401   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9402   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9403 }
9404
9405 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9406   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9407   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9408 }
9409
9410 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9411   // i16 instructions are longer (0x66 prefix) and potentially slower.
9412   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9413 }
9414
9415 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9416 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9417 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9418 /// are assumed to be legal.
9419 bool
9420 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9421                                       EVT VT) const {
9422   // Very little shuffling can be done for 64-bit vectors right now.
9423   if (VT.getSizeInBits() == 64)
9424     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9425
9426   // FIXME: pshufb, blends, shifts.
9427   return (VT.getVectorNumElements() == 2 ||
9428           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9429           isMOVLMask(M, VT) ||
9430           isSHUFPMask(M, VT) ||
9431           isPSHUFDMask(M, VT) ||
9432           isPSHUFHWMask(M, VT) ||
9433           isPSHUFLWMask(M, VT) ||
9434           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9435           isUNPCKLMask(M, VT) ||
9436           isUNPCKHMask(M, VT) ||
9437           isUNPCKL_v_undef_Mask(M, VT) ||
9438           isUNPCKH_v_undef_Mask(M, VT));
9439 }
9440
9441 bool
9442 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9443                                           EVT VT) const {
9444   unsigned NumElts = VT.getVectorNumElements();
9445   // FIXME: This collection of masks seems suspect.
9446   if (NumElts == 2)
9447     return true;
9448   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9449     return (isMOVLMask(Mask, VT)  ||
9450             isCommutedMOVLMask(Mask, VT, true) ||
9451             isSHUFPMask(Mask, VT) ||
9452             isCommutedSHUFPMask(Mask, VT));
9453   }
9454   return false;
9455 }
9456
9457 //===----------------------------------------------------------------------===//
9458 //                           X86 Scheduler Hooks
9459 //===----------------------------------------------------------------------===//
9460
9461 // private utility function
9462 MachineBasicBlock *
9463 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9464                                                        MachineBasicBlock *MBB,
9465                                                        unsigned regOpc,
9466                                                        unsigned immOpc,
9467                                                        unsigned LoadOpc,
9468                                                        unsigned CXchgOpc,
9469                                                        unsigned notOpc,
9470                                                        unsigned EAXreg,
9471                                                        TargetRegisterClass *RC,
9472                                                        bool invSrc) const {
9473   // For the atomic bitwise operator, we generate
9474   //   thisMBB:
9475   //   newMBB:
9476   //     ld  t1 = [bitinstr.addr]
9477   //     op  t2 = t1, [bitinstr.val]
9478   //     mov EAX = t1
9479   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9480   //     bz  newMBB
9481   //     fallthrough -->nextMBB
9482   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9483   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9484   MachineFunction::iterator MBBIter = MBB;
9485   ++MBBIter;
9486
9487   /// First build the CFG
9488   MachineFunction *F = MBB->getParent();
9489   MachineBasicBlock *thisMBB = MBB;
9490   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9491   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9492   F->insert(MBBIter, newMBB);
9493   F->insert(MBBIter, nextMBB);
9494
9495   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9496   nextMBB->splice(nextMBB->begin(), thisMBB,
9497                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9498                   thisMBB->end());
9499   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9500
9501   // Update thisMBB to fall through to newMBB
9502   thisMBB->addSuccessor(newMBB);
9503
9504   // newMBB jumps to itself and fall through to nextMBB
9505   newMBB->addSuccessor(nextMBB);
9506   newMBB->addSuccessor(newMBB);
9507
9508   // Insert instructions into newMBB based on incoming instruction
9509   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9510          "unexpected number of operands");
9511   DebugLoc dl = bInstr->getDebugLoc();
9512   MachineOperand& destOper = bInstr->getOperand(0);
9513   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9514   int numArgs = bInstr->getNumOperands() - 1;
9515   for (int i=0; i < numArgs; ++i)
9516     argOpers[i] = &bInstr->getOperand(i+1);
9517
9518   // x86 address has 4 operands: base, index, scale, and displacement
9519   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9520   int valArgIndx = lastAddrIndx + 1;
9521
9522   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9523   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9524   for (int i=0; i <= lastAddrIndx; ++i)
9525     (*MIB).addOperand(*argOpers[i]);
9526
9527   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9528   if (invSrc) {
9529     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9530   }
9531   else
9532     tt = t1;
9533
9534   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9535   assert((argOpers[valArgIndx]->isReg() ||
9536           argOpers[valArgIndx]->isImm()) &&
9537          "invalid operand");
9538   if (argOpers[valArgIndx]->isReg())
9539     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9540   else
9541     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9542   MIB.addReg(tt);
9543   (*MIB).addOperand(*argOpers[valArgIndx]);
9544
9545   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9546   MIB.addReg(t1);
9547
9548   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9549   for (int i=0; i <= lastAddrIndx; ++i)
9550     (*MIB).addOperand(*argOpers[i]);
9551   MIB.addReg(t2);
9552   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9553   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9554                     bInstr->memoperands_end());
9555
9556   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9557   MIB.addReg(EAXreg);
9558
9559   // insert branch
9560   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9561
9562   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9563   return nextMBB;
9564 }
9565
9566 // private utility function:  64 bit atomics on 32 bit host.
9567 MachineBasicBlock *
9568 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9569                                                        MachineBasicBlock *MBB,
9570                                                        unsigned regOpcL,
9571                                                        unsigned regOpcH,
9572                                                        unsigned immOpcL,
9573                                                        unsigned immOpcH,
9574                                                        bool invSrc) const {
9575   // For the atomic bitwise operator, we generate
9576   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9577   //     ld t1,t2 = [bitinstr.addr]
9578   //   newMBB:
9579   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9580   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9581   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9582   //     mov ECX, EBX <- t5, t6
9583   //     mov EAX, EDX <- t1, t2
9584   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9585   //     mov t3, t4 <- EAX, EDX
9586   //     bz  newMBB
9587   //     result in out1, out2
9588   //     fallthrough -->nextMBB
9589
9590   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9591   const unsigned LoadOpc = X86::MOV32rm;
9592   const unsigned NotOpc = X86::NOT32r;
9593   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9594   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9595   MachineFunction::iterator MBBIter = MBB;
9596   ++MBBIter;
9597
9598   /// First build the CFG
9599   MachineFunction *F = MBB->getParent();
9600   MachineBasicBlock *thisMBB = MBB;
9601   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9602   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9603   F->insert(MBBIter, newMBB);
9604   F->insert(MBBIter, nextMBB);
9605
9606   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9607   nextMBB->splice(nextMBB->begin(), thisMBB,
9608                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9609                   thisMBB->end());
9610   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9611
9612   // Update thisMBB to fall through to newMBB
9613   thisMBB->addSuccessor(newMBB);
9614
9615   // newMBB jumps to itself and fall through to nextMBB
9616   newMBB->addSuccessor(nextMBB);
9617   newMBB->addSuccessor(newMBB);
9618
9619   DebugLoc dl = bInstr->getDebugLoc();
9620   // Insert instructions into newMBB based on incoming instruction
9621   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9622   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9623          "unexpected number of operands");
9624   MachineOperand& dest1Oper = bInstr->getOperand(0);
9625   MachineOperand& dest2Oper = bInstr->getOperand(1);
9626   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9627   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9628     argOpers[i] = &bInstr->getOperand(i+2);
9629
9630     // We use some of the operands multiple times, so conservatively just
9631     // clear any kill flags that might be present.
9632     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9633       argOpers[i]->setIsKill(false);
9634   }
9635
9636   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9637   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9638
9639   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9640   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9641   for (int i=0; i <= lastAddrIndx; ++i)
9642     (*MIB).addOperand(*argOpers[i]);
9643   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9644   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9645   // add 4 to displacement.
9646   for (int i=0; i <= lastAddrIndx-2; ++i)
9647     (*MIB).addOperand(*argOpers[i]);
9648   MachineOperand newOp3 = *(argOpers[3]);
9649   if (newOp3.isImm())
9650     newOp3.setImm(newOp3.getImm()+4);
9651   else
9652     newOp3.setOffset(newOp3.getOffset()+4);
9653   (*MIB).addOperand(newOp3);
9654   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9655
9656   // t3/4 are defined later, at the bottom of the loop
9657   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9658   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9659   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9660     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9661   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9662     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9663
9664   // The subsequent operations should be using the destination registers of
9665   //the PHI instructions.
9666   if (invSrc) {
9667     t1 = F->getRegInfo().createVirtualRegister(RC);
9668     t2 = F->getRegInfo().createVirtualRegister(RC);
9669     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9670     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9671   } else {
9672     t1 = dest1Oper.getReg();
9673     t2 = dest2Oper.getReg();
9674   }
9675
9676   int valArgIndx = lastAddrIndx + 1;
9677   assert((argOpers[valArgIndx]->isReg() ||
9678           argOpers[valArgIndx]->isImm()) &&
9679          "invalid operand");
9680   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9681   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9682   if (argOpers[valArgIndx]->isReg())
9683     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9684   else
9685     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9686   if (regOpcL != X86::MOV32rr)
9687     MIB.addReg(t1);
9688   (*MIB).addOperand(*argOpers[valArgIndx]);
9689   assert(argOpers[valArgIndx + 1]->isReg() ==
9690          argOpers[valArgIndx]->isReg());
9691   assert(argOpers[valArgIndx + 1]->isImm() ==
9692          argOpers[valArgIndx]->isImm());
9693   if (argOpers[valArgIndx + 1]->isReg())
9694     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9695   else
9696     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9697   if (regOpcH != X86::MOV32rr)
9698     MIB.addReg(t2);
9699   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9700
9701   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9702   MIB.addReg(t1);
9703   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9704   MIB.addReg(t2);
9705
9706   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9707   MIB.addReg(t5);
9708   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9709   MIB.addReg(t6);
9710
9711   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9712   for (int i=0; i <= lastAddrIndx; ++i)
9713     (*MIB).addOperand(*argOpers[i]);
9714
9715   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9716   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9717                     bInstr->memoperands_end());
9718
9719   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9720   MIB.addReg(X86::EAX);
9721   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9722   MIB.addReg(X86::EDX);
9723
9724   // insert branch
9725   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9726
9727   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9728   return nextMBB;
9729 }
9730
9731 // private utility function
9732 MachineBasicBlock *
9733 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9734                                                       MachineBasicBlock *MBB,
9735                                                       unsigned cmovOpc) const {
9736   // For the atomic min/max operator, we generate
9737   //   thisMBB:
9738   //   newMBB:
9739   //     ld t1 = [min/max.addr]
9740   //     mov t2 = [min/max.val]
9741   //     cmp  t1, t2
9742   //     cmov[cond] t2 = t1
9743   //     mov EAX = t1
9744   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9745   //     bz   newMBB
9746   //     fallthrough -->nextMBB
9747   //
9748   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9749   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9750   MachineFunction::iterator MBBIter = MBB;
9751   ++MBBIter;
9752
9753   /// First build the CFG
9754   MachineFunction *F = MBB->getParent();
9755   MachineBasicBlock *thisMBB = MBB;
9756   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9757   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9758   F->insert(MBBIter, newMBB);
9759   F->insert(MBBIter, nextMBB);
9760
9761   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9762   nextMBB->splice(nextMBB->begin(), thisMBB,
9763                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9764                   thisMBB->end());
9765   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9766
9767   // Update thisMBB to fall through to newMBB
9768   thisMBB->addSuccessor(newMBB);
9769
9770   // newMBB jumps to newMBB and fall through to nextMBB
9771   newMBB->addSuccessor(nextMBB);
9772   newMBB->addSuccessor(newMBB);
9773
9774   DebugLoc dl = mInstr->getDebugLoc();
9775   // Insert instructions into newMBB based on incoming instruction
9776   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9777          "unexpected number of operands");
9778   MachineOperand& destOper = mInstr->getOperand(0);
9779   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9780   int numArgs = mInstr->getNumOperands() - 1;
9781   for (int i=0; i < numArgs; ++i)
9782     argOpers[i] = &mInstr->getOperand(i+1);
9783
9784   // x86 address has 4 operands: base, index, scale, and displacement
9785   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9786   int valArgIndx = lastAddrIndx + 1;
9787
9788   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9789   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9790   for (int i=0; i <= lastAddrIndx; ++i)
9791     (*MIB).addOperand(*argOpers[i]);
9792
9793   // We only support register and immediate values
9794   assert((argOpers[valArgIndx]->isReg() ||
9795           argOpers[valArgIndx]->isImm()) &&
9796          "invalid operand");
9797
9798   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9799   if (argOpers[valArgIndx]->isReg())
9800     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9801   else
9802     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9803   (*MIB).addOperand(*argOpers[valArgIndx]);
9804
9805   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9806   MIB.addReg(t1);
9807
9808   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9809   MIB.addReg(t1);
9810   MIB.addReg(t2);
9811
9812   // Generate movc
9813   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9814   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9815   MIB.addReg(t2);
9816   MIB.addReg(t1);
9817
9818   // Cmp and exchange if none has modified the memory location
9819   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9820   for (int i=0; i <= lastAddrIndx; ++i)
9821     (*MIB).addOperand(*argOpers[i]);
9822   MIB.addReg(t3);
9823   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9824   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9825                     mInstr->memoperands_end());
9826
9827   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9828   MIB.addReg(X86::EAX);
9829
9830   // insert branch
9831   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9832
9833   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9834   return nextMBB;
9835 }
9836
9837 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9838 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9839 // in the .td file.
9840 MachineBasicBlock *
9841 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9842                             unsigned numArgs, bool memArg) const {
9843   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9844          "Target must have SSE4.2 or AVX features enabled");
9845
9846   DebugLoc dl = MI->getDebugLoc();
9847   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9848   unsigned Opc;
9849   if (!Subtarget->hasAVX()) {
9850     if (memArg)
9851       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9852     else
9853       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9854   } else {
9855     if (memArg)
9856       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9857     else
9858       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9859   }
9860
9861   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9862   for (unsigned i = 0; i < numArgs; ++i) {
9863     MachineOperand &Op = MI->getOperand(i+1);
9864     if (!(Op.isReg() && Op.isImplicit()))
9865       MIB.addOperand(Op);
9866   }
9867   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9868     .addReg(X86::XMM0);
9869
9870   MI->eraseFromParent();
9871   return BB;
9872 }
9873
9874 MachineBasicBlock *
9875 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9876   DebugLoc dl = MI->getDebugLoc();
9877   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9878
9879   // Address into RAX/EAX, other two args into ECX, EDX.
9880   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9881   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9882   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9883   for (int i = 0; i < X86::AddrNumOperands; ++i)
9884     MIB.addOperand(MI->getOperand(i));
9885
9886   unsigned ValOps = X86::AddrNumOperands;
9887   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9888     .addReg(MI->getOperand(ValOps).getReg());
9889   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9890     .addReg(MI->getOperand(ValOps+1).getReg());
9891
9892   // The instruction doesn't actually take any operands though.
9893   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9894
9895   MI->eraseFromParent(); // The pseudo is gone now.
9896   return BB;
9897 }
9898
9899 MachineBasicBlock *
9900 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9901   DebugLoc dl = MI->getDebugLoc();
9902   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9903
9904   // First arg in ECX, the second in EAX.
9905   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9906     .addReg(MI->getOperand(0).getReg());
9907   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9908     .addReg(MI->getOperand(1).getReg());
9909
9910   // The instruction doesn't actually take any operands though.
9911   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9912
9913   MI->eraseFromParent(); // The pseudo is gone now.
9914   return BB;
9915 }
9916
9917 MachineBasicBlock *
9918 X86TargetLowering::EmitVAARG64WithCustomInserter(
9919                    MachineInstr *MI,
9920                    MachineBasicBlock *MBB) const {
9921   // Emit va_arg instruction on X86-64.
9922
9923   // Operands to this pseudo-instruction:
9924   // 0  ) Output        : destination address (reg)
9925   // 1-5) Input         : va_list address (addr, i64mem)
9926   // 6  ) ArgSize       : Size (in bytes) of vararg type
9927   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9928   // 8  ) Align         : Alignment of type
9929   // 9  ) EFLAGS (implicit-def)
9930
9931   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9932   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9933
9934   unsigned DestReg = MI->getOperand(0).getReg();
9935   MachineOperand &Base = MI->getOperand(1);
9936   MachineOperand &Scale = MI->getOperand(2);
9937   MachineOperand &Index = MI->getOperand(3);
9938   MachineOperand &Disp = MI->getOperand(4);
9939   MachineOperand &Segment = MI->getOperand(5);
9940   unsigned ArgSize = MI->getOperand(6).getImm();
9941   unsigned ArgMode = MI->getOperand(7).getImm();
9942   unsigned Align = MI->getOperand(8).getImm();
9943
9944   // Memory Reference
9945   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9946   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9947   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9948
9949   // Machine Information
9950   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9951   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9952   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9953   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9954   DebugLoc DL = MI->getDebugLoc();
9955
9956   // struct va_list {
9957   //   i32   gp_offset
9958   //   i32   fp_offset
9959   //   i64   overflow_area (address)
9960   //   i64   reg_save_area (address)
9961   // }
9962   // sizeof(va_list) = 24
9963   // alignment(va_list) = 8
9964
9965   unsigned TotalNumIntRegs = 6;
9966   unsigned TotalNumXMMRegs = 8;
9967   bool UseGPOffset = (ArgMode == 1);
9968   bool UseFPOffset = (ArgMode == 2);
9969   unsigned MaxOffset = TotalNumIntRegs * 8 +
9970                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9971
9972   /* Align ArgSize to a multiple of 8 */
9973   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9974   bool NeedsAlign = (Align > 8);
9975
9976   MachineBasicBlock *thisMBB = MBB;
9977   MachineBasicBlock *overflowMBB;
9978   MachineBasicBlock *offsetMBB;
9979   MachineBasicBlock *endMBB;
9980
9981   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9982   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9983   unsigned OffsetReg = 0;
9984
9985   if (!UseGPOffset && !UseFPOffset) {
9986     // If we only pull from the overflow region, we don't create a branch.
9987     // We don't need to alter control flow.
9988     OffsetDestReg = 0; // unused
9989     OverflowDestReg = DestReg;
9990
9991     offsetMBB = NULL;
9992     overflowMBB = thisMBB;
9993     endMBB = thisMBB;
9994   } else {
9995     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9996     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9997     // If not, pull from overflow_area. (branch to overflowMBB)
9998     //
9999     //       thisMBB
10000     //         |     .
10001     //         |        .
10002     //     offsetMBB   overflowMBB
10003     //         |        .
10004     //         |     .
10005     //        endMBB
10006
10007     // Registers for the PHI in endMBB
10008     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
10009     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
10010
10011     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10012     MachineFunction *MF = MBB->getParent();
10013     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10014     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10015     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10016
10017     MachineFunction::iterator MBBIter = MBB;
10018     ++MBBIter;
10019
10020     // Insert the new basic blocks
10021     MF->insert(MBBIter, offsetMBB);
10022     MF->insert(MBBIter, overflowMBB);
10023     MF->insert(MBBIter, endMBB);
10024
10025     // Transfer the remainder of MBB and its successor edges to endMBB.
10026     endMBB->splice(endMBB->begin(), thisMBB,
10027                     llvm::next(MachineBasicBlock::iterator(MI)),
10028                     thisMBB->end());
10029     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10030
10031     // Make offsetMBB and overflowMBB successors of thisMBB
10032     thisMBB->addSuccessor(offsetMBB);
10033     thisMBB->addSuccessor(overflowMBB);
10034
10035     // endMBB is a successor of both offsetMBB and overflowMBB
10036     offsetMBB->addSuccessor(endMBB);
10037     overflowMBB->addSuccessor(endMBB);
10038
10039     // Load the offset value into a register
10040     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10041     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
10042       .addOperand(Base)
10043       .addOperand(Scale)
10044       .addOperand(Index)
10045       .addDisp(Disp, UseFPOffset ? 4 : 0)
10046       .addOperand(Segment)
10047       .setMemRefs(MMOBegin, MMOEnd);
10048
10049     // Check if there is enough room left to pull this argument.
10050     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
10051       .addReg(OffsetReg)
10052       .addImm(MaxOffset + 8 - ArgSizeA8);
10053
10054     // Branch to "overflowMBB" if offset >= max
10055     // Fall through to "offsetMBB" otherwise
10056     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
10057       .addMBB(overflowMBB);
10058   }
10059
10060   // In offsetMBB, emit code to use the reg_save_area.
10061   if (offsetMBB) {
10062     assert(OffsetReg != 0);
10063
10064     // Read the reg_save_area address.
10065     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
10066     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
10067       .addOperand(Base)
10068       .addOperand(Scale)
10069       .addOperand(Index)
10070       .addDisp(Disp, 16)
10071       .addOperand(Segment)
10072       .setMemRefs(MMOBegin, MMOEnd);
10073
10074     // Zero-extend the offset
10075     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
10076       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
10077         .addImm(0)
10078         .addReg(OffsetReg)
10079         .addImm(X86::sub_32bit);
10080
10081     // Add the offset to the reg_save_area to get the final address.
10082     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
10083       .addReg(OffsetReg64)
10084       .addReg(RegSaveReg);
10085
10086     // Compute the offset for the next argument
10087     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
10088     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
10089       .addReg(OffsetReg)
10090       .addImm(UseFPOffset ? 16 : 8);
10091
10092     // Store it back into the va_list.
10093     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
10094       .addOperand(Base)
10095       .addOperand(Scale)
10096       .addOperand(Index)
10097       .addDisp(Disp, UseFPOffset ? 4 : 0)
10098       .addOperand(Segment)
10099       .addReg(NextOffsetReg)
10100       .setMemRefs(MMOBegin, MMOEnd);
10101
10102     // Jump to endMBB
10103     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
10104       .addMBB(endMBB);
10105   }
10106
10107   //
10108   // Emit code to use overflow area
10109   //
10110
10111   // Load the overflow_area address into a register.
10112   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
10113   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
10114     .addOperand(Base)
10115     .addOperand(Scale)
10116     .addOperand(Index)
10117     .addDisp(Disp, 8)
10118     .addOperand(Segment)
10119     .setMemRefs(MMOBegin, MMOEnd);
10120
10121   // If we need to align it, do so. Otherwise, just copy the address
10122   // to OverflowDestReg.
10123   if (NeedsAlign) {
10124     // Align the overflow address
10125     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
10126     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
10127
10128     // aligned_addr = (addr + (align-1)) & ~(align-1)
10129     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
10130       .addReg(OverflowAddrReg)
10131       .addImm(Align-1);
10132
10133     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
10134       .addReg(TmpReg)
10135       .addImm(~(uint64_t)(Align-1));
10136   } else {
10137     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
10138       .addReg(OverflowAddrReg);
10139   }
10140
10141   // Compute the next overflow address after this argument.
10142   // (the overflow address should be kept 8-byte aligned)
10143   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
10144   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
10145     .addReg(OverflowDestReg)
10146     .addImm(ArgSizeA8);
10147
10148   // Store the new overflow address.
10149   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
10150     .addOperand(Base)
10151     .addOperand(Scale)
10152     .addOperand(Index)
10153     .addDisp(Disp, 8)
10154     .addOperand(Segment)
10155     .addReg(NextAddrReg)
10156     .setMemRefs(MMOBegin, MMOEnd);
10157
10158   // If we branched, emit the PHI to the front of endMBB.
10159   if (offsetMBB) {
10160     BuildMI(*endMBB, endMBB->begin(), DL,
10161             TII->get(X86::PHI), DestReg)
10162       .addReg(OffsetDestReg).addMBB(offsetMBB)
10163       .addReg(OverflowDestReg).addMBB(overflowMBB);
10164   }
10165
10166   // Erase the pseudo instruction
10167   MI->eraseFromParent();
10168
10169   return endMBB;
10170 }
10171
10172 MachineBasicBlock *
10173 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
10174                                                  MachineInstr *MI,
10175                                                  MachineBasicBlock *MBB) const {
10176   // Emit code to save XMM registers to the stack. The ABI says that the
10177   // number of registers to save is given in %al, so it's theoretically
10178   // possible to do an indirect jump trick to avoid saving all of them,
10179   // however this code takes a simpler approach and just executes all
10180   // of the stores if %al is non-zero. It's less code, and it's probably
10181   // easier on the hardware branch predictor, and stores aren't all that
10182   // expensive anyway.
10183
10184   // Create the new basic blocks. One block contains all the XMM stores,
10185   // and one block is the final destination regardless of whether any
10186   // stores were performed.
10187   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10188   MachineFunction *F = MBB->getParent();
10189   MachineFunction::iterator MBBIter = MBB;
10190   ++MBBIter;
10191   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
10192   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
10193   F->insert(MBBIter, XMMSaveMBB);
10194   F->insert(MBBIter, EndMBB);
10195
10196   // Transfer the remainder of MBB and its successor edges to EndMBB.
10197   EndMBB->splice(EndMBB->begin(), MBB,
10198                  llvm::next(MachineBasicBlock::iterator(MI)),
10199                  MBB->end());
10200   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
10201
10202   // The original block will now fall through to the XMM save block.
10203   MBB->addSuccessor(XMMSaveMBB);
10204   // The XMMSaveMBB will fall through to the end block.
10205   XMMSaveMBB->addSuccessor(EndMBB);
10206
10207   // Now add the instructions.
10208   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10209   DebugLoc DL = MI->getDebugLoc();
10210
10211   unsigned CountReg = MI->getOperand(0).getReg();
10212   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
10213   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
10214
10215   if (!Subtarget->isTargetWin64()) {
10216     // If %al is 0, branch around the XMM save block.
10217     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
10218     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
10219     MBB->addSuccessor(EndMBB);
10220   }
10221
10222   // In the XMM save block, save all the XMM argument registers.
10223   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
10224     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
10225     MachineMemOperand *MMO =
10226       F->getMachineMemOperand(
10227           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
10228         MachineMemOperand::MOStore,
10229         /*Size=*/16, /*Align=*/16);
10230     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
10231       .addFrameIndex(RegSaveFrameIndex)
10232       .addImm(/*Scale=*/1)
10233       .addReg(/*IndexReg=*/0)
10234       .addImm(/*Disp=*/Offset)
10235       .addReg(/*Segment=*/0)
10236       .addReg(MI->getOperand(i).getReg())
10237       .addMemOperand(MMO);
10238   }
10239
10240   MI->eraseFromParent();   // The pseudo instruction is gone now.
10241
10242   return EndMBB;
10243 }
10244
10245 MachineBasicBlock *
10246 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
10247                                      MachineBasicBlock *BB) const {
10248   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10249   DebugLoc DL = MI->getDebugLoc();
10250
10251   // To "insert" a SELECT_CC instruction, we actually have to insert the
10252   // diamond control-flow pattern.  The incoming instruction knows the
10253   // destination vreg to set, the condition code register to branch on, the
10254   // true/false values to select between, and a branch opcode to use.
10255   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10256   MachineFunction::iterator It = BB;
10257   ++It;
10258
10259   //  thisMBB:
10260   //  ...
10261   //   TrueVal = ...
10262   //   cmpTY ccX, r1, r2
10263   //   bCC copy1MBB
10264   //   fallthrough --> copy0MBB
10265   MachineBasicBlock *thisMBB = BB;
10266   MachineFunction *F = BB->getParent();
10267   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10268   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10269   F->insert(It, copy0MBB);
10270   F->insert(It, sinkMBB);
10271
10272   // If the EFLAGS register isn't dead in the terminator, then claim that it's
10273   // live into the sink and copy blocks.
10274   const MachineFunction *MF = BB->getParent();
10275   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
10276   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
10277
10278   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
10279     const MachineOperand &MO = MI->getOperand(I);
10280     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
10281     unsigned Reg = MO.getReg();
10282     if (Reg != X86::EFLAGS) continue;
10283     copy0MBB->addLiveIn(Reg);
10284     sinkMBB->addLiveIn(Reg);
10285   }
10286
10287   // Transfer the remainder of BB and its successor edges to sinkMBB.
10288   sinkMBB->splice(sinkMBB->begin(), BB,
10289                   llvm::next(MachineBasicBlock::iterator(MI)),
10290                   BB->end());
10291   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10292
10293   // Add the true and fallthrough blocks as its successors.
10294   BB->addSuccessor(copy0MBB);
10295   BB->addSuccessor(sinkMBB);
10296
10297   // Create the conditional branch instruction.
10298   unsigned Opc =
10299     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
10300   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
10301
10302   //  copy0MBB:
10303   //   %FalseValue = ...
10304   //   # fallthrough to sinkMBB
10305   copy0MBB->addSuccessor(sinkMBB);
10306
10307   //  sinkMBB:
10308   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10309   //  ...
10310   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10311           TII->get(X86::PHI), MI->getOperand(0).getReg())
10312     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
10313     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
10314
10315   MI->eraseFromParent();   // The pseudo instruction is gone now.
10316   return sinkMBB;
10317 }
10318
10319 MachineBasicBlock *
10320 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
10321                                           MachineBasicBlock *BB) const {
10322   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10323   DebugLoc DL = MI->getDebugLoc();
10324
10325   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
10326   // non-trivial part is impdef of ESP.
10327   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10328   // mingw-w64.
10329
10330   const char *StackProbeSymbol =
10331       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10332
10333   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10334     .addExternalSymbol(StackProbeSymbol)
10335     .addReg(X86::EAX, RegState::Implicit)
10336     .addReg(X86::ESP, RegState::Implicit)
10337     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10338     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10339     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10340
10341   MI->eraseFromParent();   // The pseudo instruction is gone now.
10342   return BB;
10343 }
10344
10345 MachineBasicBlock *
10346 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10347                                       MachineBasicBlock *BB) const {
10348   // This is pretty easy.  We're taking the value that we received from
10349   // our load from the relocation, sticking it in either RDI (x86-64)
10350   // or EAX and doing an indirect call.  The return value will then
10351   // be in the normal return register.
10352   const X86InstrInfo *TII
10353     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10354   DebugLoc DL = MI->getDebugLoc();
10355   MachineFunction *F = BB->getParent();
10356
10357   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10358   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10359
10360   if (Subtarget->is64Bit()) {
10361     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10362                                       TII->get(X86::MOV64rm), X86::RDI)
10363     .addReg(X86::RIP)
10364     .addImm(0).addReg(0)
10365     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10366                       MI->getOperand(3).getTargetFlags())
10367     .addReg(0);
10368     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10369     addDirectMem(MIB, X86::RDI);
10370   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10371     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10372                                       TII->get(X86::MOV32rm), X86::EAX)
10373     .addReg(0)
10374     .addImm(0).addReg(0)
10375     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10376                       MI->getOperand(3).getTargetFlags())
10377     .addReg(0);
10378     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10379     addDirectMem(MIB, X86::EAX);
10380   } else {
10381     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10382                                       TII->get(X86::MOV32rm), X86::EAX)
10383     .addReg(TII->getGlobalBaseReg(F))
10384     .addImm(0).addReg(0)
10385     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10386                       MI->getOperand(3).getTargetFlags())
10387     .addReg(0);
10388     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10389     addDirectMem(MIB, X86::EAX);
10390   }
10391
10392   MI->eraseFromParent(); // The pseudo instruction is gone now.
10393   return BB;
10394 }
10395
10396 MachineBasicBlock *
10397 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10398                                                MachineBasicBlock *BB) const {
10399   switch (MI->getOpcode()) {
10400   default: assert(false && "Unexpected instr type to insert");
10401   case X86::TAILJMPd64:
10402   case X86::TAILJMPr64:
10403   case X86::TAILJMPm64:
10404     assert(!"TAILJMP64 would not be touched here.");
10405   case X86::TCRETURNdi64:
10406   case X86::TCRETURNri64:
10407   case X86::TCRETURNmi64:
10408     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
10409     // On AMD64, additional defs should be added before register allocation.
10410     if (!Subtarget->isTargetWin64()) {
10411       MI->addRegisterDefined(X86::RSI);
10412       MI->addRegisterDefined(X86::RDI);
10413       MI->addRegisterDefined(X86::XMM6);
10414       MI->addRegisterDefined(X86::XMM7);
10415       MI->addRegisterDefined(X86::XMM8);
10416       MI->addRegisterDefined(X86::XMM9);
10417       MI->addRegisterDefined(X86::XMM10);
10418       MI->addRegisterDefined(X86::XMM11);
10419       MI->addRegisterDefined(X86::XMM12);
10420       MI->addRegisterDefined(X86::XMM13);
10421       MI->addRegisterDefined(X86::XMM14);
10422       MI->addRegisterDefined(X86::XMM15);
10423     }
10424     return BB;
10425   case X86::WIN_ALLOCA:
10426     return EmitLoweredWinAlloca(MI, BB);
10427   case X86::TLSCall_32:
10428   case X86::TLSCall_64:
10429     return EmitLoweredTLSCall(MI, BB);
10430   case X86::CMOV_GR8:
10431   case X86::CMOV_FR32:
10432   case X86::CMOV_FR64:
10433   case X86::CMOV_V4F32:
10434   case X86::CMOV_V2F64:
10435   case X86::CMOV_V2I64:
10436   case X86::CMOV_GR16:
10437   case X86::CMOV_GR32:
10438   case X86::CMOV_RFP32:
10439   case X86::CMOV_RFP64:
10440   case X86::CMOV_RFP80:
10441     return EmitLoweredSelect(MI, BB);
10442
10443   case X86::FP32_TO_INT16_IN_MEM:
10444   case X86::FP32_TO_INT32_IN_MEM:
10445   case X86::FP32_TO_INT64_IN_MEM:
10446   case X86::FP64_TO_INT16_IN_MEM:
10447   case X86::FP64_TO_INT32_IN_MEM:
10448   case X86::FP64_TO_INT64_IN_MEM:
10449   case X86::FP80_TO_INT16_IN_MEM:
10450   case X86::FP80_TO_INT32_IN_MEM:
10451   case X86::FP80_TO_INT64_IN_MEM: {
10452     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10453     DebugLoc DL = MI->getDebugLoc();
10454
10455     // Change the floating point control register to use "round towards zero"
10456     // mode when truncating to an integer value.
10457     MachineFunction *F = BB->getParent();
10458     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10459     addFrameReference(BuildMI(*BB, MI, DL,
10460                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10461
10462     // Load the old value of the high byte of the control word...
10463     unsigned OldCW =
10464       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10465     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10466                       CWFrameIdx);
10467
10468     // Set the high part to be round to zero...
10469     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10470       .addImm(0xC7F);
10471
10472     // Reload the modified control word now...
10473     addFrameReference(BuildMI(*BB, MI, DL,
10474                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10475
10476     // Restore the memory image of control word to original value
10477     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10478       .addReg(OldCW);
10479
10480     // Get the X86 opcode to use.
10481     unsigned Opc;
10482     switch (MI->getOpcode()) {
10483     default: llvm_unreachable("illegal opcode!");
10484     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10485     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10486     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10487     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10488     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10489     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10490     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10491     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10492     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10493     }
10494
10495     X86AddressMode AM;
10496     MachineOperand &Op = MI->getOperand(0);
10497     if (Op.isReg()) {
10498       AM.BaseType = X86AddressMode::RegBase;
10499       AM.Base.Reg = Op.getReg();
10500     } else {
10501       AM.BaseType = X86AddressMode::FrameIndexBase;
10502       AM.Base.FrameIndex = Op.getIndex();
10503     }
10504     Op = MI->getOperand(1);
10505     if (Op.isImm())
10506       AM.Scale = Op.getImm();
10507     Op = MI->getOperand(2);
10508     if (Op.isImm())
10509       AM.IndexReg = Op.getImm();
10510     Op = MI->getOperand(3);
10511     if (Op.isGlobal()) {
10512       AM.GV = Op.getGlobal();
10513     } else {
10514       AM.Disp = Op.getImm();
10515     }
10516     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10517                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10518
10519     // Reload the original control word now.
10520     addFrameReference(BuildMI(*BB, MI, DL,
10521                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10522
10523     MI->eraseFromParent();   // The pseudo instruction is gone now.
10524     return BB;
10525   }
10526     // String/text processing lowering.
10527   case X86::PCMPISTRM128REG:
10528   case X86::VPCMPISTRM128REG:
10529     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10530   case X86::PCMPISTRM128MEM:
10531   case X86::VPCMPISTRM128MEM:
10532     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10533   case X86::PCMPESTRM128REG:
10534   case X86::VPCMPESTRM128REG:
10535     return EmitPCMP(MI, BB, 5, false /* in mem */);
10536   case X86::PCMPESTRM128MEM:
10537   case X86::VPCMPESTRM128MEM:
10538     return EmitPCMP(MI, BB, 5, true /* in mem */);
10539
10540     // Thread synchronization.
10541   case X86::MONITOR:
10542     return EmitMonitor(MI, BB);
10543   case X86::MWAIT:
10544     return EmitMwait(MI, BB);
10545
10546     // Atomic Lowering.
10547   case X86::ATOMAND32:
10548     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10549                                                X86::AND32ri, X86::MOV32rm,
10550                                                X86::LCMPXCHG32,
10551                                                X86::NOT32r, X86::EAX,
10552                                                X86::GR32RegisterClass);
10553   case X86::ATOMOR32:
10554     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10555                                                X86::OR32ri, X86::MOV32rm,
10556                                                X86::LCMPXCHG32,
10557                                                X86::NOT32r, X86::EAX,
10558                                                X86::GR32RegisterClass);
10559   case X86::ATOMXOR32:
10560     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10561                                                X86::XOR32ri, X86::MOV32rm,
10562                                                X86::LCMPXCHG32,
10563                                                X86::NOT32r, X86::EAX,
10564                                                X86::GR32RegisterClass);
10565   case X86::ATOMNAND32:
10566     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10567                                                X86::AND32ri, X86::MOV32rm,
10568                                                X86::LCMPXCHG32,
10569                                                X86::NOT32r, X86::EAX,
10570                                                X86::GR32RegisterClass, true);
10571   case X86::ATOMMIN32:
10572     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10573   case X86::ATOMMAX32:
10574     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10575   case X86::ATOMUMIN32:
10576     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10577   case X86::ATOMUMAX32:
10578     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10579
10580   case X86::ATOMAND16:
10581     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10582                                                X86::AND16ri, X86::MOV16rm,
10583                                                X86::LCMPXCHG16,
10584                                                X86::NOT16r, X86::AX,
10585                                                X86::GR16RegisterClass);
10586   case X86::ATOMOR16:
10587     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10588                                                X86::OR16ri, X86::MOV16rm,
10589                                                X86::LCMPXCHG16,
10590                                                X86::NOT16r, X86::AX,
10591                                                X86::GR16RegisterClass);
10592   case X86::ATOMXOR16:
10593     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10594                                                X86::XOR16ri, X86::MOV16rm,
10595                                                X86::LCMPXCHG16,
10596                                                X86::NOT16r, X86::AX,
10597                                                X86::GR16RegisterClass);
10598   case X86::ATOMNAND16:
10599     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10600                                                X86::AND16ri, X86::MOV16rm,
10601                                                X86::LCMPXCHG16,
10602                                                X86::NOT16r, X86::AX,
10603                                                X86::GR16RegisterClass, true);
10604   case X86::ATOMMIN16:
10605     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10606   case X86::ATOMMAX16:
10607     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10608   case X86::ATOMUMIN16:
10609     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10610   case X86::ATOMUMAX16:
10611     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10612
10613   case X86::ATOMAND8:
10614     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10615                                                X86::AND8ri, X86::MOV8rm,
10616                                                X86::LCMPXCHG8,
10617                                                X86::NOT8r, X86::AL,
10618                                                X86::GR8RegisterClass);
10619   case X86::ATOMOR8:
10620     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10621                                                X86::OR8ri, X86::MOV8rm,
10622                                                X86::LCMPXCHG8,
10623                                                X86::NOT8r, X86::AL,
10624                                                X86::GR8RegisterClass);
10625   case X86::ATOMXOR8:
10626     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10627                                                X86::XOR8ri, X86::MOV8rm,
10628                                                X86::LCMPXCHG8,
10629                                                X86::NOT8r, X86::AL,
10630                                                X86::GR8RegisterClass);
10631   case X86::ATOMNAND8:
10632     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10633                                                X86::AND8ri, X86::MOV8rm,
10634                                                X86::LCMPXCHG8,
10635                                                X86::NOT8r, X86::AL,
10636                                                X86::GR8RegisterClass, true);
10637   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10638   // This group is for 64-bit host.
10639   case X86::ATOMAND64:
10640     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10641                                                X86::AND64ri32, X86::MOV64rm,
10642                                                X86::LCMPXCHG64,
10643                                                X86::NOT64r, X86::RAX,
10644                                                X86::GR64RegisterClass);
10645   case X86::ATOMOR64:
10646     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10647                                                X86::OR64ri32, X86::MOV64rm,
10648                                                X86::LCMPXCHG64,
10649                                                X86::NOT64r, X86::RAX,
10650                                                X86::GR64RegisterClass);
10651   case X86::ATOMXOR64:
10652     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10653                                                X86::XOR64ri32, X86::MOV64rm,
10654                                                X86::LCMPXCHG64,
10655                                                X86::NOT64r, X86::RAX,
10656                                                X86::GR64RegisterClass);
10657   case X86::ATOMNAND64:
10658     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10659                                                X86::AND64ri32, X86::MOV64rm,
10660                                                X86::LCMPXCHG64,
10661                                                X86::NOT64r, X86::RAX,
10662                                                X86::GR64RegisterClass, true);
10663   case X86::ATOMMIN64:
10664     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10665   case X86::ATOMMAX64:
10666     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10667   case X86::ATOMUMIN64:
10668     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10669   case X86::ATOMUMAX64:
10670     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10671
10672   // This group does 64-bit operations on a 32-bit host.
10673   case X86::ATOMAND6432:
10674     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10675                                                X86::AND32rr, X86::AND32rr,
10676                                                X86::AND32ri, X86::AND32ri,
10677                                                false);
10678   case X86::ATOMOR6432:
10679     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10680                                                X86::OR32rr, X86::OR32rr,
10681                                                X86::OR32ri, X86::OR32ri,
10682                                                false);
10683   case X86::ATOMXOR6432:
10684     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10685                                                X86::XOR32rr, X86::XOR32rr,
10686                                                X86::XOR32ri, X86::XOR32ri,
10687                                                false);
10688   case X86::ATOMNAND6432:
10689     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10690                                                X86::AND32rr, X86::AND32rr,
10691                                                X86::AND32ri, X86::AND32ri,
10692                                                true);
10693   case X86::ATOMADD6432:
10694     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10695                                                X86::ADD32rr, X86::ADC32rr,
10696                                                X86::ADD32ri, X86::ADC32ri,
10697                                                false);
10698   case X86::ATOMSUB6432:
10699     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10700                                                X86::SUB32rr, X86::SBB32rr,
10701                                                X86::SUB32ri, X86::SBB32ri,
10702                                                false);
10703   case X86::ATOMSWAP6432:
10704     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10705                                                X86::MOV32rr, X86::MOV32rr,
10706                                                X86::MOV32ri, X86::MOV32ri,
10707                                                false);
10708   case X86::VASTART_SAVE_XMM_REGS:
10709     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10710
10711   case X86::VAARG_64:
10712     return EmitVAARG64WithCustomInserter(MI, BB);
10713   }
10714 }
10715
10716 //===----------------------------------------------------------------------===//
10717 //                           X86 Optimization Hooks
10718 //===----------------------------------------------------------------------===//
10719
10720 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10721                                                        const APInt &Mask,
10722                                                        APInt &KnownZero,
10723                                                        APInt &KnownOne,
10724                                                        const SelectionDAG &DAG,
10725                                                        unsigned Depth) const {
10726   unsigned Opc = Op.getOpcode();
10727   assert((Opc >= ISD::BUILTIN_OP_END ||
10728           Opc == ISD::INTRINSIC_WO_CHAIN ||
10729           Opc == ISD::INTRINSIC_W_CHAIN ||
10730           Opc == ISD::INTRINSIC_VOID) &&
10731          "Should use MaskedValueIsZero if you don't know whether Op"
10732          " is a target node!");
10733
10734   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10735   switch (Opc) {
10736   default: break;
10737   case X86ISD::ADD:
10738   case X86ISD::SUB:
10739   case X86ISD::ADC:
10740   case X86ISD::SBB:
10741   case X86ISD::SMUL:
10742   case X86ISD::UMUL:
10743   case X86ISD::INC:
10744   case X86ISD::DEC:
10745   case X86ISD::OR:
10746   case X86ISD::XOR:
10747   case X86ISD::AND:
10748     // These nodes' second result is a boolean.
10749     if (Op.getResNo() == 0)
10750       break;
10751     // Fallthrough
10752   case X86ISD::SETCC:
10753     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10754                                        Mask.getBitWidth() - 1);
10755     break;
10756   }
10757 }
10758
10759 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10760                                                          unsigned Depth) const {
10761   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10762   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10763     return Op.getValueType().getScalarType().getSizeInBits();
10764
10765   // Fallback case.
10766   return 1;
10767 }
10768
10769 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10770 /// node is a GlobalAddress + offset.
10771 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10772                                        const GlobalValue* &GA,
10773                                        int64_t &Offset) const {
10774   if (N->getOpcode() == X86ISD::Wrapper) {
10775     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10776       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10777       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10778       return true;
10779     }
10780   }
10781   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10782 }
10783
10784 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10785 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10786 /// if the load addresses are consecutive, non-overlapping, and in the right
10787 /// order.
10788 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10789                                      TargetLowering::DAGCombinerInfo &DCI) {
10790   DebugLoc dl = N->getDebugLoc();
10791   EVT VT = N->getValueType(0);
10792
10793   if (VT.getSizeInBits() != 128)
10794     return SDValue();
10795
10796   // Don't create instructions with illegal types after legalize types has run.
10797   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10798   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10799     return SDValue();
10800
10801   SmallVector<SDValue, 16> Elts;
10802   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10803     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10804
10805   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10806 }
10807
10808 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10809 /// generation and convert it from being a bunch of shuffles and extracts
10810 /// to a simple store and scalar loads to extract the elements.
10811 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10812                                                 const TargetLowering &TLI) {
10813   SDValue InputVector = N->getOperand(0);
10814
10815   // Only operate on vectors of 4 elements, where the alternative shuffling
10816   // gets to be more expensive.
10817   if (InputVector.getValueType() != MVT::v4i32)
10818     return SDValue();
10819
10820   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10821   // single use which is a sign-extend or zero-extend, and all elements are
10822   // used.
10823   SmallVector<SDNode *, 4> Uses;
10824   unsigned ExtractedElements = 0;
10825   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10826        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10827     if (UI.getUse().getResNo() != InputVector.getResNo())
10828       return SDValue();
10829
10830     SDNode *Extract = *UI;
10831     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10832       return SDValue();
10833
10834     if (Extract->getValueType(0) != MVT::i32)
10835       return SDValue();
10836     if (!Extract->hasOneUse())
10837       return SDValue();
10838     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10839         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10840       return SDValue();
10841     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10842       return SDValue();
10843
10844     // Record which element was extracted.
10845     ExtractedElements |=
10846       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10847
10848     Uses.push_back(Extract);
10849   }
10850
10851   // If not all the elements were used, this may not be worthwhile.
10852   if (ExtractedElements != 15)
10853     return SDValue();
10854
10855   // Ok, we've now decided to do the transformation.
10856   DebugLoc dl = InputVector.getDebugLoc();
10857
10858   // Store the value to a temporary stack slot.
10859   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10860   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10861                             MachinePointerInfo(), false, false, 0);
10862
10863   // Replace each use (extract) with a load of the appropriate element.
10864   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10865        UE = Uses.end(); UI != UE; ++UI) {
10866     SDNode *Extract = *UI;
10867
10868     // Compute the element's address.
10869     SDValue Idx = Extract->getOperand(1);
10870     unsigned EltSize =
10871         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10872     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10873     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10874
10875     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10876                                      StackPtr, OffsetVal);
10877
10878     // Load the scalar.
10879     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10880                                      ScalarAddr, MachinePointerInfo(),
10881                                      false, false, 0);
10882
10883     // Replace the exact with the load.
10884     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10885   }
10886
10887   // The replacement was made in place; don't return anything.
10888   return SDValue();
10889 }
10890
10891 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10892 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10893                                     const X86Subtarget *Subtarget) {
10894   DebugLoc DL = N->getDebugLoc();
10895   SDValue Cond = N->getOperand(0);
10896   // Get the LHS/RHS of the select.
10897   SDValue LHS = N->getOperand(1);
10898   SDValue RHS = N->getOperand(2);
10899
10900   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10901   // instructions match the semantics of the common C idiom x<y?x:y but not
10902   // x<=y?x:y, because of how they handle negative zero (which can be
10903   // ignored in unsafe-math mode).
10904   if (Subtarget->hasSSE2() &&
10905       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10906       Cond.getOpcode() == ISD::SETCC) {
10907     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10908
10909     unsigned Opcode = 0;
10910     // Check for x CC y ? x : y.
10911     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10912         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10913       switch (CC) {
10914       default: break;
10915       case ISD::SETULT:
10916         // Converting this to a min would handle NaNs incorrectly, and swapping
10917         // the operands would cause it to handle comparisons between positive
10918         // and negative zero incorrectly.
10919         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10920           if (!UnsafeFPMath &&
10921               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10922             break;
10923           std::swap(LHS, RHS);
10924         }
10925         Opcode = X86ISD::FMIN;
10926         break;
10927       case ISD::SETOLE:
10928         // Converting this to a min would handle comparisons between positive
10929         // and negative zero incorrectly.
10930         if (!UnsafeFPMath &&
10931             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10932           break;
10933         Opcode = X86ISD::FMIN;
10934         break;
10935       case ISD::SETULE:
10936         // Converting this to a min would handle both negative zeros and NaNs
10937         // incorrectly, but we can swap the operands to fix both.
10938         std::swap(LHS, RHS);
10939       case ISD::SETOLT:
10940       case ISD::SETLT:
10941       case ISD::SETLE:
10942         Opcode = X86ISD::FMIN;
10943         break;
10944
10945       case ISD::SETOGE:
10946         // Converting this to a max would handle comparisons between positive
10947         // and negative zero incorrectly.
10948         if (!UnsafeFPMath &&
10949             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10950           break;
10951         Opcode = X86ISD::FMAX;
10952         break;
10953       case ISD::SETUGT:
10954         // Converting this to a max would handle NaNs incorrectly, and swapping
10955         // the operands would cause it to handle comparisons between positive
10956         // and negative zero incorrectly.
10957         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10958           if (!UnsafeFPMath &&
10959               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10960             break;
10961           std::swap(LHS, RHS);
10962         }
10963         Opcode = X86ISD::FMAX;
10964         break;
10965       case ISD::SETUGE:
10966         // Converting this to a max would handle both negative zeros and NaNs
10967         // incorrectly, but we can swap the operands to fix both.
10968         std::swap(LHS, RHS);
10969       case ISD::SETOGT:
10970       case ISD::SETGT:
10971       case ISD::SETGE:
10972         Opcode = X86ISD::FMAX;
10973         break;
10974       }
10975     // Check for x CC y ? y : x -- a min/max with reversed arms.
10976     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10977                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10978       switch (CC) {
10979       default: break;
10980       case ISD::SETOGE:
10981         // Converting this to a min would handle comparisons between positive
10982         // and negative zero incorrectly, and swapping the operands would
10983         // cause it to handle NaNs incorrectly.
10984         if (!UnsafeFPMath &&
10985             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10986           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10987             break;
10988           std::swap(LHS, RHS);
10989         }
10990         Opcode = X86ISD::FMIN;
10991         break;
10992       case ISD::SETUGT:
10993         // Converting this to a min would handle NaNs incorrectly.
10994         if (!UnsafeFPMath &&
10995             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10996           break;
10997         Opcode = X86ISD::FMIN;
10998         break;
10999       case ISD::SETUGE:
11000         // Converting this to a min would handle both negative zeros and NaNs
11001         // incorrectly, but we can swap the operands to fix both.
11002         std::swap(LHS, RHS);
11003       case ISD::SETOGT:
11004       case ISD::SETGT:
11005       case ISD::SETGE:
11006         Opcode = X86ISD::FMIN;
11007         break;
11008
11009       case ISD::SETULT:
11010         // Converting this to a max would handle NaNs incorrectly.
11011         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11012           break;
11013         Opcode = X86ISD::FMAX;
11014         break;
11015       case ISD::SETOLE:
11016         // Converting this to a max would handle comparisons between positive
11017         // and negative zero incorrectly, and swapping the operands would
11018         // cause it to handle NaNs incorrectly.
11019         if (!UnsafeFPMath &&
11020             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
11021           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
11022             break;
11023           std::swap(LHS, RHS);
11024         }
11025         Opcode = X86ISD::FMAX;
11026         break;
11027       case ISD::SETULE:
11028         // Converting this to a max would handle both negative zeros and NaNs
11029         // incorrectly, but we can swap the operands to fix both.
11030         std::swap(LHS, RHS);
11031       case ISD::SETOLT:
11032       case ISD::SETLT:
11033       case ISD::SETLE:
11034         Opcode = X86ISD::FMAX;
11035         break;
11036       }
11037     }
11038
11039     if (Opcode)
11040       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
11041   }
11042
11043   // If this is a select between two integer constants, try to do some
11044   // optimizations.
11045   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
11046     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
11047       // Don't do this for crazy integer types.
11048       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
11049         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
11050         // so that TrueC (the true value) is larger than FalseC.
11051         bool NeedsCondInvert = false;
11052
11053         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
11054             // Efficiently invertible.
11055             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
11056              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
11057               isa<ConstantSDNode>(Cond.getOperand(1))))) {
11058           NeedsCondInvert = true;
11059           std::swap(TrueC, FalseC);
11060         }
11061
11062         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
11063         if (FalseC->getAPIntValue() == 0 &&
11064             TrueC->getAPIntValue().isPowerOf2()) {
11065           if (NeedsCondInvert) // Invert the condition if needed.
11066             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11067                                DAG.getConstant(1, Cond.getValueType()));
11068
11069           // Zero extend the condition if needed.
11070           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
11071
11072           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11073           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
11074                              DAG.getConstant(ShAmt, MVT::i8));
11075         }
11076
11077         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
11078         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11079           if (NeedsCondInvert) // Invert the condition if needed.
11080             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11081                                DAG.getConstant(1, Cond.getValueType()));
11082
11083           // Zero extend the condition if needed.
11084           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11085                              FalseC->getValueType(0), Cond);
11086           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11087                              SDValue(FalseC, 0));
11088         }
11089
11090         // Optimize cases that will turn into an LEA instruction.  This requires
11091         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11092         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11093           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11094           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11095
11096           bool isFastMultiplier = false;
11097           if (Diff < 10) {
11098             switch ((unsigned char)Diff) {
11099               default: break;
11100               case 1:  // result = add base, cond
11101               case 2:  // result = lea base(    , cond*2)
11102               case 3:  // result = lea base(cond, cond*2)
11103               case 4:  // result = lea base(    , cond*4)
11104               case 5:  // result = lea base(cond, cond*4)
11105               case 8:  // result = lea base(    , cond*8)
11106               case 9:  // result = lea base(cond, cond*8)
11107                 isFastMultiplier = true;
11108                 break;
11109             }
11110           }
11111
11112           if (isFastMultiplier) {
11113             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11114             if (NeedsCondInvert) // Invert the condition if needed.
11115               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
11116                                  DAG.getConstant(1, Cond.getValueType()));
11117
11118             // Zero extend the condition if needed.
11119             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11120                                Cond);
11121             // Scale the condition by the difference.
11122             if (Diff != 1)
11123               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11124                                  DAG.getConstant(Diff, Cond.getValueType()));
11125
11126             // Add the base if non-zero.
11127             if (FalseC->getAPIntValue() != 0)
11128               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11129                                  SDValue(FalseC, 0));
11130             return Cond;
11131           }
11132         }
11133       }
11134   }
11135
11136   return SDValue();
11137 }
11138
11139 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
11140 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
11141                                   TargetLowering::DAGCombinerInfo &DCI) {
11142   DebugLoc DL = N->getDebugLoc();
11143
11144   // If the flag operand isn't dead, don't touch this CMOV.
11145   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
11146     return SDValue();
11147
11148   // If this is a select between two integer constants, try to do some
11149   // optimizations.  Note that the operands are ordered the opposite of SELECT
11150   // operands.
11151   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
11152     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11153       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
11154       // larger than FalseC (the false value).
11155       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
11156
11157       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
11158         CC = X86::GetOppositeBranchCondition(CC);
11159         std::swap(TrueC, FalseC);
11160       }
11161
11162       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
11163       // This is efficient for any integer data type (including i8/i16) and
11164       // shift amount.
11165       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
11166         SDValue Cond = N->getOperand(3);
11167         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11168                            DAG.getConstant(CC, MVT::i8), Cond);
11169
11170         // Zero extend the condition if needed.
11171         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
11172
11173         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
11174         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
11175                            DAG.getConstant(ShAmt, MVT::i8));
11176         if (N->getNumValues() == 2)  // Dead flag value?
11177           return DCI.CombineTo(N, Cond, SDValue());
11178         return Cond;
11179       }
11180
11181       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
11182       // for any integer data type, including i8/i16.
11183       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
11184         SDValue Cond = N->getOperand(3);
11185         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11186                            DAG.getConstant(CC, MVT::i8), Cond);
11187
11188         // Zero extend the condition if needed.
11189         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
11190                            FalseC->getValueType(0), Cond);
11191         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11192                            SDValue(FalseC, 0));
11193
11194         if (N->getNumValues() == 2)  // Dead flag value?
11195           return DCI.CombineTo(N, Cond, SDValue());
11196         return Cond;
11197       }
11198
11199       // Optimize cases that will turn into an LEA instruction.  This requires
11200       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
11201       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
11202         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
11203         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
11204
11205         bool isFastMultiplier = false;
11206         if (Diff < 10) {
11207           switch ((unsigned char)Diff) {
11208           default: break;
11209           case 1:  // result = add base, cond
11210           case 2:  // result = lea base(    , cond*2)
11211           case 3:  // result = lea base(cond, cond*2)
11212           case 4:  // result = lea base(    , cond*4)
11213           case 5:  // result = lea base(cond, cond*4)
11214           case 8:  // result = lea base(    , cond*8)
11215           case 9:  // result = lea base(cond, cond*8)
11216             isFastMultiplier = true;
11217             break;
11218           }
11219         }
11220
11221         if (isFastMultiplier) {
11222           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
11223           SDValue Cond = N->getOperand(3);
11224           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11225                              DAG.getConstant(CC, MVT::i8), Cond);
11226           // Zero extend the condition if needed.
11227           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
11228                              Cond);
11229           // Scale the condition by the difference.
11230           if (Diff != 1)
11231             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
11232                                DAG.getConstant(Diff, Cond.getValueType()));
11233
11234           // Add the base if non-zero.
11235           if (FalseC->getAPIntValue() != 0)
11236             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
11237                                SDValue(FalseC, 0));
11238           if (N->getNumValues() == 2)  // Dead flag value?
11239             return DCI.CombineTo(N, Cond, SDValue());
11240           return Cond;
11241         }
11242       }
11243     }
11244   }
11245   return SDValue();
11246 }
11247
11248
11249 /// PerformMulCombine - Optimize a single multiply with constant into two
11250 /// in order to implement it with two cheaper instructions, e.g.
11251 /// LEA + SHL, LEA + LEA.
11252 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
11253                                  TargetLowering::DAGCombinerInfo &DCI) {
11254   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11255     return SDValue();
11256
11257   EVT VT = N->getValueType(0);
11258   if (VT != MVT::i64)
11259     return SDValue();
11260
11261   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11262   if (!C)
11263     return SDValue();
11264   uint64_t MulAmt = C->getZExtValue();
11265   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
11266     return SDValue();
11267
11268   uint64_t MulAmt1 = 0;
11269   uint64_t MulAmt2 = 0;
11270   if ((MulAmt % 9) == 0) {
11271     MulAmt1 = 9;
11272     MulAmt2 = MulAmt / 9;
11273   } else if ((MulAmt % 5) == 0) {
11274     MulAmt1 = 5;
11275     MulAmt2 = MulAmt / 5;
11276   } else if ((MulAmt % 3) == 0) {
11277     MulAmt1 = 3;
11278     MulAmt2 = MulAmt / 3;
11279   }
11280   if (MulAmt2 &&
11281       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
11282     DebugLoc DL = N->getDebugLoc();
11283
11284     if (isPowerOf2_64(MulAmt2) &&
11285         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
11286       // If second multiplifer is pow2, issue it first. We want the multiply by
11287       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
11288       // is an add.
11289       std::swap(MulAmt1, MulAmt2);
11290
11291     SDValue NewMul;
11292     if (isPowerOf2_64(MulAmt1))
11293       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
11294                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
11295     else
11296       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
11297                            DAG.getConstant(MulAmt1, VT));
11298
11299     if (isPowerOf2_64(MulAmt2))
11300       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
11301                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
11302     else
11303       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
11304                            DAG.getConstant(MulAmt2, VT));
11305
11306     // Do not add new nodes to DAG combiner worklist.
11307     DCI.CombineTo(N, NewMul, false);
11308   }
11309   return SDValue();
11310 }
11311
11312 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
11313   SDValue N0 = N->getOperand(0);
11314   SDValue N1 = N->getOperand(1);
11315   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
11316   EVT VT = N0.getValueType();
11317
11318   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
11319   // since the result of setcc_c is all zero's or all ones.
11320   if (N1C && N0.getOpcode() == ISD::AND &&
11321       N0.getOperand(1).getOpcode() == ISD::Constant) {
11322     SDValue N00 = N0.getOperand(0);
11323     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
11324         ((N00.getOpcode() == ISD::ANY_EXTEND ||
11325           N00.getOpcode() == ISD::ZERO_EXTEND) &&
11326          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
11327       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
11328       APInt ShAmt = N1C->getAPIntValue();
11329       Mask = Mask.shl(ShAmt);
11330       if (Mask != 0)
11331         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
11332                            N00, DAG.getConstant(Mask, VT));
11333     }
11334   }
11335
11336   return SDValue();
11337 }
11338
11339 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
11340 ///                       when possible.
11341 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
11342                                    const X86Subtarget *Subtarget) {
11343   EVT VT = N->getValueType(0);
11344   if (!VT.isVector() && VT.isInteger() &&
11345       N->getOpcode() == ISD::SHL)
11346     return PerformSHLCombine(N, DAG);
11347
11348   // On X86 with SSE2 support, we can transform this to a vector shift if
11349   // all elements are shifted by the same amount.  We can't do this in legalize
11350   // because the a constant vector is typically transformed to a constant pool
11351   // so we have no knowledge of the shift amount.
11352   if (!Subtarget->hasSSE2())
11353     return SDValue();
11354
11355   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11356     return SDValue();
11357
11358   SDValue ShAmtOp = N->getOperand(1);
11359   EVT EltVT = VT.getVectorElementType();
11360   DebugLoc DL = N->getDebugLoc();
11361   SDValue BaseShAmt = SDValue();
11362   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11363     unsigned NumElts = VT.getVectorNumElements();
11364     unsigned i = 0;
11365     for (; i != NumElts; ++i) {
11366       SDValue Arg = ShAmtOp.getOperand(i);
11367       if (Arg.getOpcode() == ISD::UNDEF) continue;
11368       BaseShAmt = Arg;
11369       break;
11370     }
11371     for (; i != NumElts; ++i) {
11372       SDValue Arg = ShAmtOp.getOperand(i);
11373       if (Arg.getOpcode() == ISD::UNDEF) continue;
11374       if (Arg != BaseShAmt) {
11375         return SDValue();
11376       }
11377     }
11378   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11379              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11380     SDValue InVec = ShAmtOp.getOperand(0);
11381     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11382       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11383       unsigned i = 0;
11384       for (; i != NumElts; ++i) {
11385         SDValue Arg = InVec.getOperand(i);
11386         if (Arg.getOpcode() == ISD::UNDEF) continue;
11387         BaseShAmt = Arg;
11388         break;
11389       }
11390     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11391        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11392          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11393          if (C->getZExtValue() == SplatIdx)
11394            BaseShAmt = InVec.getOperand(1);
11395        }
11396     }
11397     if (BaseShAmt.getNode() == 0)
11398       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11399                               DAG.getIntPtrConstant(0));
11400   } else
11401     return SDValue();
11402
11403   // The shift amount is an i32.
11404   if (EltVT.bitsGT(MVT::i32))
11405     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11406   else if (EltVT.bitsLT(MVT::i32))
11407     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11408
11409   // The shift amount is identical so we can do a vector shift.
11410   SDValue  ValOp = N->getOperand(0);
11411   switch (N->getOpcode()) {
11412   default:
11413     llvm_unreachable("Unknown shift opcode!");
11414     break;
11415   case ISD::SHL:
11416     if (VT == MVT::v2i64)
11417       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11418                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11419                          ValOp, BaseShAmt);
11420     if (VT == MVT::v4i32)
11421       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11422                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11423                          ValOp, BaseShAmt);
11424     if (VT == MVT::v8i16)
11425       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11426                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11427                          ValOp, BaseShAmt);
11428     break;
11429   case ISD::SRA:
11430     if (VT == MVT::v4i32)
11431       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11432                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11433                          ValOp, BaseShAmt);
11434     if (VT == MVT::v8i16)
11435       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11436                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11437                          ValOp, BaseShAmt);
11438     break;
11439   case ISD::SRL:
11440     if (VT == MVT::v2i64)
11441       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11442                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11443                          ValOp, BaseShAmt);
11444     if (VT == MVT::v4i32)
11445       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11446                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11447                          ValOp, BaseShAmt);
11448     if (VT ==  MVT::v8i16)
11449       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11450                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11451                          ValOp, BaseShAmt);
11452     break;
11453   }
11454   return SDValue();
11455 }
11456
11457
11458 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11459                                  TargetLowering::DAGCombinerInfo &DCI,
11460                                  const X86Subtarget *Subtarget) {
11461   if (DCI.isBeforeLegalizeOps())
11462     return SDValue();
11463
11464   // Want to form PANDN nodes, in the hopes of then easily combining them with
11465   // OR and AND nodes to form PBLEND/PSIGN.
11466   EVT VT = N->getValueType(0);
11467   if (VT != MVT::v2i64)
11468     return SDValue();
11469
11470   SDValue N0 = N->getOperand(0);
11471   SDValue N1 = N->getOperand(1);
11472   DebugLoc DL = N->getDebugLoc();
11473
11474   // Check LHS for vnot
11475   if (N0.getOpcode() == ISD::XOR &&
11476       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11477     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11478
11479   // Check RHS for vnot
11480   if (N1.getOpcode() == ISD::XOR &&
11481       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11482     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11483
11484   return SDValue();
11485 }
11486
11487 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11488                                 TargetLowering::DAGCombinerInfo &DCI,
11489                                 const X86Subtarget *Subtarget) {
11490   if (DCI.isBeforeLegalizeOps())
11491     return SDValue();
11492
11493   EVT VT = N->getValueType(0);
11494   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11495     return SDValue();
11496
11497   SDValue N0 = N->getOperand(0);
11498   SDValue N1 = N->getOperand(1);
11499
11500   // look for psign/blend
11501   if (Subtarget->hasSSSE3()) {
11502     if (VT == MVT::v2i64) {
11503       // Canonicalize pandn to RHS
11504       if (N0.getOpcode() == X86ISD::PANDN)
11505         std::swap(N0, N1);
11506       // or (and (m, x), (pandn m, y))
11507       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11508         SDValue Mask = N1.getOperand(0);
11509         SDValue X    = N1.getOperand(1);
11510         SDValue Y;
11511         if (N0.getOperand(0) == Mask)
11512           Y = N0.getOperand(1);
11513         if (N0.getOperand(1) == Mask)
11514           Y = N0.getOperand(0);
11515
11516         // Check to see if the mask appeared in both the AND and PANDN and
11517         if (!Y.getNode())
11518           return SDValue();
11519
11520         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11521         if (Mask.getOpcode() != ISD::BITCAST ||
11522             X.getOpcode() != ISD::BITCAST ||
11523             Y.getOpcode() != ISD::BITCAST)
11524           return SDValue();
11525
11526         // Look through mask bitcast.
11527         Mask = Mask.getOperand(0);
11528         EVT MaskVT = Mask.getValueType();
11529
11530         // Validate that the Mask operand is a vector sra node.  The sra node
11531         // will be an intrinsic.
11532         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11533           return SDValue();
11534
11535         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11536         // there is no psrai.b
11537         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11538         case Intrinsic::x86_sse2_psrai_w:
11539         case Intrinsic::x86_sse2_psrai_d:
11540           break;
11541         default: return SDValue();
11542         }
11543
11544         // Check that the SRA is all signbits.
11545         SDValue SraC = Mask.getOperand(2);
11546         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11547         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11548         if ((SraAmt + 1) != EltBits)
11549           return SDValue();
11550
11551         DebugLoc DL = N->getDebugLoc();
11552
11553         // Now we know we at least have a plendvb with the mask val.  See if
11554         // we can form a psignb/w/d.
11555         // psign = x.type == y.type == mask.type && y = sub(0, x);
11556         X = X.getOperand(0);
11557         Y = Y.getOperand(0);
11558         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11559             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11560             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11561           unsigned Opc = 0;
11562           switch (EltBits) {
11563           case 8: Opc = X86ISD::PSIGNB; break;
11564           case 16: Opc = X86ISD::PSIGNW; break;
11565           case 32: Opc = X86ISD::PSIGND; break;
11566           default: break;
11567           }
11568           if (Opc) {
11569             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11570             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11571           }
11572         }
11573         // PBLENDVB only available on SSE 4.1
11574         if (!Subtarget->hasSSE41())
11575           return SDValue();
11576
11577         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11578         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11579         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11580         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11581         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11582       }
11583     }
11584   }
11585
11586   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11587   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11588     std::swap(N0, N1);
11589   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11590     return SDValue();
11591   if (!N0.hasOneUse() || !N1.hasOneUse())
11592     return SDValue();
11593
11594   SDValue ShAmt0 = N0.getOperand(1);
11595   if (ShAmt0.getValueType() != MVT::i8)
11596     return SDValue();
11597   SDValue ShAmt1 = N1.getOperand(1);
11598   if (ShAmt1.getValueType() != MVT::i8)
11599     return SDValue();
11600   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11601     ShAmt0 = ShAmt0.getOperand(0);
11602   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11603     ShAmt1 = ShAmt1.getOperand(0);
11604
11605   DebugLoc DL = N->getDebugLoc();
11606   unsigned Opc = X86ISD::SHLD;
11607   SDValue Op0 = N0.getOperand(0);
11608   SDValue Op1 = N1.getOperand(0);
11609   if (ShAmt0.getOpcode() == ISD::SUB) {
11610     Opc = X86ISD::SHRD;
11611     std::swap(Op0, Op1);
11612     std::swap(ShAmt0, ShAmt1);
11613   }
11614
11615   unsigned Bits = VT.getSizeInBits();
11616   if (ShAmt1.getOpcode() == ISD::SUB) {
11617     SDValue Sum = ShAmt1.getOperand(0);
11618     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11619       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11620       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11621         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11622       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11623         return DAG.getNode(Opc, DL, VT,
11624                            Op0, Op1,
11625                            DAG.getNode(ISD::TRUNCATE, DL,
11626                                        MVT::i8, ShAmt0));
11627     }
11628   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11629     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11630     if (ShAmt0C &&
11631         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11632       return DAG.getNode(Opc, DL, VT,
11633                          N0.getOperand(0), N1.getOperand(0),
11634                          DAG.getNode(ISD::TRUNCATE, DL,
11635                                        MVT::i8, ShAmt0));
11636   }
11637
11638   return SDValue();
11639 }
11640
11641 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11642 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11643                                    const X86Subtarget *Subtarget) {
11644   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11645   // the FP state in cases where an emms may be missing.
11646   // A preferable solution to the general problem is to figure out the right
11647   // places to insert EMMS.  This qualifies as a quick hack.
11648
11649   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11650   StoreSDNode *St = cast<StoreSDNode>(N);
11651   EVT VT = St->getValue().getValueType();
11652   if (VT.getSizeInBits() != 64)
11653     return SDValue();
11654
11655   const Function *F = DAG.getMachineFunction().getFunction();
11656   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11657   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11658     && Subtarget->hasSSE2();
11659   if ((VT.isVector() ||
11660        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11661       isa<LoadSDNode>(St->getValue()) &&
11662       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11663       St->getChain().hasOneUse() && !St->isVolatile()) {
11664     SDNode* LdVal = St->getValue().getNode();
11665     LoadSDNode *Ld = 0;
11666     int TokenFactorIndex = -1;
11667     SmallVector<SDValue, 8> Ops;
11668     SDNode* ChainVal = St->getChain().getNode();
11669     // Must be a store of a load.  We currently handle two cases:  the load
11670     // is a direct child, and it's under an intervening TokenFactor.  It is
11671     // possible to dig deeper under nested TokenFactors.
11672     if (ChainVal == LdVal)
11673       Ld = cast<LoadSDNode>(St->getChain());
11674     else if (St->getValue().hasOneUse() &&
11675              ChainVal->getOpcode() == ISD::TokenFactor) {
11676       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11677         if (ChainVal->getOperand(i).getNode() == LdVal) {
11678           TokenFactorIndex = i;
11679           Ld = cast<LoadSDNode>(St->getValue());
11680         } else
11681           Ops.push_back(ChainVal->getOperand(i));
11682       }
11683     }
11684
11685     if (!Ld || !ISD::isNormalLoad(Ld))
11686       return SDValue();
11687
11688     // If this is not the MMX case, i.e. we are just turning i64 load/store
11689     // into f64 load/store, avoid the transformation if there are multiple
11690     // uses of the loaded value.
11691     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11692       return SDValue();
11693
11694     DebugLoc LdDL = Ld->getDebugLoc();
11695     DebugLoc StDL = N->getDebugLoc();
11696     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11697     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11698     // pair instead.
11699     if (Subtarget->is64Bit() || F64IsLegal) {
11700       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11701       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11702                                   Ld->getPointerInfo(), Ld->isVolatile(),
11703                                   Ld->isNonTemporal(), Ld->getAlignment());
11704       SDValue NewChain = NewLd.getValue(1);
11705       if (TokenFactorIndex != -1) {
11706         Ops.push_back(NewChain);
11707         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11708                                Ops.size());
11709       }
11710       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11711                           St->getPointerInfo(),
11712                           St->isVolatile(), St->isNonTemporal(),
11713                           St->getAlignment());
11714     }
11715
11716     // Otherwise, lower to two pairs of 32-bit loads / stores.
11717     SDValue LoAddr = Ld->getBasePtr();
11718     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11719                                  DAG.getConstant(4, MVT::i32));
11720
11721     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11722                                Ld->getPointerInfo(),
11723                                Ld->isVolatile(), Ld->isNonTemporal(),
11724                                Ld->getAlignment());
11725     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11726                                Ld->getPointerInfo().getWithOffset(4),
11727                                Ld->isVolatile(), Ld->isNonTemporal(),
11728                                MinAlign(Ld->getAlignment(), 4));
11729
11730     SDValue NewChain = LoLd.getValue(1);
11731     if (TokenFactorIndex != -1) {
11732       Ops.push_back(LoLd);
11733       Ops.push_back(HiLd);
11734       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11735                              Ops.size());
11736     }
11737
11738     LoAddr = St->getBasePtr();
11739     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11740                          DAG.getConstant(4, MVT::i32));
11741
11742     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11743                                 St->getPointerInfo(),
11744                                 St->isVolatile(), St->isNonTemporal(),
11745                                 St->getAlignment());
11746     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11747                                 St->getPointerInfo().getWithOffset(4),
11748                                 St->isVolatile(),
11749                                 St->isNonTemporal(),
11750                                 MinAlign(St->getAlignment(), 4));
11751     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11752   }
11753   return SDValue();
11754 }
11755
11756 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11757 /// X86ISD::FXOR nodes.
11758 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11759   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11760   // F[X]OR(0.0, x) -> x
11761   // F[X]OR(x, 0.0) -> x
11762   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11763     if (C->getValueAPF().isPosZero())
11764       return N->getOperand(1);
11765   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11766     if (C->getValueAPF().isPosZero())
11767       return N->getOperand(0);
11768   return SDValue();
11769 }
11770
11771 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11772 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11773   // FAND(0.0, x) -> 0.0
11774   // FAND(x, 0.0) -> 0.0
11775   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11776     if (C->getValueAPF().isPosZero())
11777       return N->getOperand(0);
11778   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11779     if (C->getValueAPF().isPosZero())
11780       return N->getOperand(1);
11781   return SDValue();
11782 }
11783
11784 static SDValue PerformBTCombine(SDNode *N,
11785                                 SelectionDAG &DAG,
11786                                 TargetLowering::DAGCombinerInfo &DCI) {
11787   // BT ignores high bits in the bit index operand.
11788   SDValue Op1 = N->getOperand(1);
11789   if (Op1.hasOneUse()) {
11790     unsigned BitWidth = Op1.getValueSizeInBits();
11791     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11792     APInt KnownZero, KnownOne;
11793     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11794                                           !DCI.isBeforeLegalizeOps());
11795     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11796     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11797         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11798       DCI.CommitTargetLoweringOpt(TLO);
11799   }
11800   return SDValue();
11801 }
11802
11803 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11804   SDValue Op = N->getOperand(0);
11805   if (Op.getOpcode() == ISD::BITCAST)
11806     Op = Op.getOperand(0);
11807   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11808   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11809       VT.getVectorElementType().getSizeInBits() ==
11810       OpVT.getVectorElementType().getSizeInBits()) {
11811     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11812   }
11813   return SDValue();
11814 }
11815
11816 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11817   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11818   //           (and (i32 x86isd::setcc_carry), 1)
11819   // This eliminates the zext. This transformation is necessary because
11820   // ISD::SETCC is always legalized to i8.
11821   DebugLoc dl = N->getDebugLoc();
11822   SDValue N0 = N->getOperand(0);
11823   EVT VT = N->getValueType(0);
11824   if (N0.getOpcode() == ISD::AND &&
11825       N0.hasOneUse() &&
11826       N0.getOperand(0).hasOneUse()) {
11827     SDValue N00 = N0.getOperand(0);
11828     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11829       return SDValue();
11830     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11831     if (!C || C->getZExtValue() != 1)
11832       return SDValue();
11833     return DAG.getNode(ISD::AND, dl, VT,
11834                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11835                                    N00.getOperand(0), N00.getOperand(1)),
11836                        DAG.getConstant(1, VT));
11837   }
11838
11839   return SDValue();
11840 }
11841
11842 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11843 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11844   unsigned X86CC = N->getConstantOperandVal(0);
11845   SDValue EFLAG = N->getOperand(1);
11846   DebugLoc DL = N->getDebugLoc();
11847
11848   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11849   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11850   // cases.
11851   if (X86CC == X86::COND_B)
11852     return DAG.getNode(ISD::AND, DL, MVT::i8,
11853                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11854                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11855                        DAG.getConstant(1, MVT::i8));
11856
11857   return SDValue();
11858 }
11859
11860 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11861 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11862                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11863   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11864   // the result is either zero or one (depending on the input carry bit).
11865   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11866   if (X86::isZeroNode(N->getOperand(0)) &&
11867       X86::isZeroNode(N->getOperand(1)) &&
11868       // We don't have a good way to replace an EFLAGS use, so only do this when
11869       // dead right now.
11870       SDValue(N, 1).use_empty()) {
11871     DebugLoc DL = N->getDebugLoc();
11872     EVT VT = N->getValueType(0);
11873     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11874     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11875                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11876                                            DAG.getConstant(X86::COND_B,MVT::i8),
11877                                            N->getOperand(2)),
11878                                DAG.getConstant(1, VT));
11879     return DCI.CombineTo(N, Res1, CarryOut);
11880   }
11881
11882   return SDValue();
11883 }
11884
11885 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11886 //      (add Y, (setne X, 0)) -> sbb -1, Y
11887 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11888 //      (sub (setne X, 0), Y) -> adc -1, Y
11889 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11890   DebugLoc DL = N->getDebugLoc();
11891
11892   // Look through ZExts.
11893   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11894   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11895     return SDValue();
11896
11897   SDValue SetCC = Ext.getOperand(0);
11898   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11899     return SDValue();
11900
11901   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11902   if (CC != X86::COND_E && CC != X86::COND_NE)
11903     return SDValue();
11904
11905   SDValue Cmp = SetCC.getOperand(1);
11906   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11907       !X86::isZeroNode(Cmp.getOperand(1)) ||
11908       !Cmp.getOperand(0).getValueType().isInteger())
11909     return SDValue();
11910
11911   SDValue CmpOp0 = Cmp.getOperand(0);
11912   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11913                                DAG.getConstant(1, CmpOp0.getValueType()));
11914
11915   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11916   if (CC == X86::COND_NE)
11917     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11918                        DL, OtherVal.getValueType(), OtherVal,
11919                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11920   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11921                      DL, OtherVal.getValueType(), OtherVal,
11922                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11923 }
11924
11925 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11926                                              DAGCombinerInfo &DCI) const {
11927   SelectionDAG &DAG = DCI.DAG;
11928   switch (N->getOpcode()) {
11929   default: break;
11930   case ISD::EXTRACT_VECTOR_ELT:
11931     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11932   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11933   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11934   case ISD::ADD:
11935   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
11936   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11937   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11938   case ISD::SHL:
11939   case ISD::SRA:
11940   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11941   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11942   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11943   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11944   case X86ISD::FXOR:
11945   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11946   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11947   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11948   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11949   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11950   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
11951   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11952   case X86ISD::SHUFPD:
11953   case X86ISD::PALIGN:
11954   case X86ISD::PUNPCKHBW:
11955   case X86ISD::PUNPCKHWD:
11956   case X86ISD::PUNPCKHDQ:
11957   case X86ISD::PUNPCKHQDQ:
11958   case X86ISD::UNPCKHPS:
11959   case X86ISD::UNPCKHPD:
11960   case X86ISD::PUNPCKLBW:
11961   case X86ISD::PUNPCKLWD:
11962   case X86ISD::PUNPCKLDQ:
11963   case X86ISD::PUNPCKLQDQ:
11964   case X86ISD::UNPCKLPS:
11965   case X86ISD::UNPCKLPD:
11966   case X86ISD::MOVHLPS:
11967   case X86ISD::MOVLHPS:
11968   case X86ISD::PSHUFD:
11969   case X86ISD::PSHUFHW:
11970   case X86ISD::PSHUFLW:
11971   case X86ISD::MOVSS:
11972   case X86ISD::MOVSD:
11973   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11974   }
11975
11976   return SDValue();
11977 }
11978
11979 /// isTypeDesirableForOp - Return true if the target has native support for
11980 /// the specified value type and it is 'desirable' to use the type for the
11981 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11982 /// instruction encodings are longer and some i16 instructions are slow.
11983 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11984   if (!isTypeLegal(VT))
11985     return false;
11986   if (VT != MVT::i16)
11987     return true;
11988
11989   switch (Opc) {
11990   default:
11991     return true;
11992   case ISD::LOAD:
11993   case ISD::SIGN_EXTEND:
11994   case ISD::ZERO_EXTEND:
11995   case ISD::ANY_EXTEND:
11996   case ISD::SHL:
11997   case ISD::SRL:
11998   case ISD::SUB:
11999   case ISD::ADD:
12000   case ISD::MUL:
12001   case ISD::AND:
12002   case ISD::OR:
12003   case ISD::XOR:
12004     return false;
12005   }
12006 }
12007
12008 /// IsDesirableToPromoteOp - This method query the target whether it is
12009 /// beneficial for dag combiner to promote the specified node. If true, it
12010 /// should return the desired promotion type by reference.
12011 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
12012   EVT VT = Op.getValueType();
12013   if (VT != MVT::i16)
12014     return false;
12015
12016   bool Promote = false;
12017   bool Commute = false;
12018   switch (Op.getOpcode()) {
12019   default: break;
12020   case ISD::LOAD: {
12021     LoadSDNode *LD = cast<LoadSDNode>(Op);
12022     // If the non-extending load has a single use and it's not live out, then it
12023     // might be folded.
12024     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
12025                                                      Op.hasOneUse()*/) {
12026       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12027              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
12028         // The only case where we'd want to promote LOAD (rather then it being
12029         // promoted as an operand is when it's only use is liveout.
12030         if (UI->getOpcode() != ISD::CopyToReg)
12031           return false;
12032       }
12033     }
12034     Promote = true;
12035     break;
12036   }
12037   case ISD::SIGN_EXTEND:
12038   case ISD::ZERO_EXTEND:
12039   case ISD::ANY_EXTEND:
12040     Promote = true;
12041     break;
12042   case ISD::SHL:
12043   case ISD::SRL: {
12044     SDValue N0 = Op.getOperand(0);
12045     // Look out for (store (shl (load), x)).
12046     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
12047       return false;
12048     Promote = true;
12049     break;
12050   }
12051   case ISD::ADD:
12052   case ISD::MUL:
12053   case ISD::AND:
12054   case ISD::OR:
12055   case ISD::XOR:
12056     Commute = true;
12057     // fallthrough
12058   case ISD::SUB: {
12059     SDValue N0 = Op.getOperand(0);
12060     SDValue N1 = Op.getOperand(1);
12061     if (!Commute && MayFoldLoad(N1))
12062       return false;
12063     // Avoid disabling potential load folding opportunities.
12064     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
12065       return false;
12066     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
12067       return false;
12068     Promote = true;
12069   }
12070   }
12071
12072   PVT = MVT::i32;
12073   return Promote;
12074 }
12075
12076 //===----------------------------------------------------------------------===//
12077 //                           X86 Inline Assembly Support
12078 //===----------------------------------------------------------------------===//
12079
12080 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
12081   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12082
12083   std::string AsmStr = IA->getAsmString();
12084
12085   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
12086   SmallVector<StringRef, 4> AsmPieces;
12087   SplitString(AsmStr, AsmPieces, ";\n");
12088
12089   switch (AsmPieces.size()) {
12090   default: return false;
12091   case 1:
12092     AsmStr = AsmPieces[0];
12093     AsmPieces.clear();
12094     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
12095
12096     // FIXME: this should verify that we are targetting a 486 or better.  If not,
12097     // we will turn this bswap into something that will be lowered to logical ops
12098     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
12099     // so don't worry about this.
12100     // bswap $0
12101     if (AsmPieces.size() == 2 &&
12102         (AsmPieces[0] == "bswap" ||
12103          AsmPieces[0] == "bswapq" ||
12104          AsmPieces[0] == "bswapl") &&
12105         (AsmPieces[1] == "$0" ||
12106          AsmPieces[1] == "${0:q}")) {
12107       // No need to check constraints, nothing other than the equivalent of
12108       // "=r,0" would be valid here.
12109       const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12110       if (!Ty || Ty->getBitWidth() % 16 != 0)
12111         return false;
12112       return IntrinsicLowering::LowerToByteSwap(CI);
12113     }
12114     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
12115     if (CI->getType()->isIntegerTy(16) &&
12116         AsmPieces.size() == 3 &&
12117         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
12118         AsmPieces[1] == "$$8," &&
12119         AsmPieces[2] == "${0:w}" &&
12120         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12121       AsmPieces.clear();
12122       const std::string &ConstraintsStr = IA->getConstraintString();
12123       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12124       std::sort(AsmPieces.begin(), AsmPieces.end());
12125       if (AsmPieces.size() == 4 &&
12126           AsmPieces[0] == "~{cc}" &&
12127           AsmPieces[1] == "~{dirflag}" &&
12128           AsmPieces[2] == "~{flags}" &&
12129           AsmPieces[3] == "~{fpsr}") {
12130         const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12131         if (!Ty || Ty->getBitWidth() % 16 != 0)
12132           return false;
12133         return IntrinsicLowering::LowerToByteSwap(CI);
12134       }
12135     }
12136     break;
12137   case 3:
12138     if (CI->getType()->isIntegerTy(32) &&
12139         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
12140       SmallVector<StringRef, 4> Words;
12141       SplitString(AsmPieces[0], Words, " \t,");
12142       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12143           Words[2] == "${0:w}") {
12144         Words.clear();
12145         SplitString(AsmPieces[1], Words, " \t,");
12146         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
12147             Words[2] == "$0") {
12148           Words.clear();
12149           SplitString(AsmPieces[2], Words, " \t,");
12150           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
12151               Words[2] == "${0:w}") {
12152             AsmPieces.clear();
12153             const std::string &ConstraintsStr = IA->getConstraintString();
12154             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
12155             std::sort(AsmPieces.begin(), AsmPieces.end());
12156             if (AsmPieces.size() == 4 &&
12157                 AsmPieces[0] == "~{cc}" &&
12158                 AsmPieces[1] == "~{dirflag}" &&
12159                 AsmPieces[2] == "~{flags}" &&
12160                 AsmPieces[3] == "~{fpsr}") {
12161               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12162               if (!Ty || Ty->getBitWidth() % 16 != 0)
12163                 return false;
12164               return IntrinsicLowering::LowerToByteSwap(CI);
12165             }
12166           }
12167         }
12168       }
12169     }
12170
12171     if (CI->getType()->isIntegerTy(64)) {
12172       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
12173       if (Constraints.size() >= 2 &&
12174           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
12175           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
12176         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
12177         SmallVector<StringRef, 4> Words;
12178         SplitString(AsmPieces[0], Words, " \t");
12179         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
12180           Words.clear();
12181           SplitString(AsmPieces[1], Words, " \t");
12182           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
12183             Words.clear();
12184             SplitString(AsmPieces[2], Words, " \t,");
12185             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
12186                 Words[2] == "%edx") {
12187               const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12188               if (!Ty || Ty->getBitWidth() % 16 != 0)
12189                 return false;
12190               return IntrinsicLowering::LowerToByteSwap(CI);
12191             }
12192           }
12193         }
12194       }
12195     }
12196     break;
12197   }
12198   return false;
12199 }
12200
12201
12202
12203 /// getConstraintType - Given a constraint letter, return the type of
12204 /// constraint it is for this target.
12205 X86TargetLowering::ConstraintType
12206 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
12207   if (Constraint.size() == 1) {
12208     switch (Constraint[0]) {
12209     case 'R':
12210     case 'q':
12211     case 'Q':
12212     case 'f':
12213     case 't':
12214     case 'u':
12215     case 'y':
12216     case 'x':
12217     case 'Y':
12218       return C_RegisterClass;
12219     case 'a':
12220     case 'b':
12221     case 'c':
12222     case 'd':
12223     case 'S':
12224     case 'D':
12225     case 'A':
12226       return C_Register;
12227     case 'I':
12228     case 'J':
12229     case 'K':
12230     case 'L':
12231     case 'M':
12232     case 'N':
12233     case 'G':
12234     case 'C':
12235     case 'e':
12236     case 'Z':
12237       return C_Other;
12238     default:
12239       break;
12240     }
12241   }
12242   return TargetLowering::getConstraintType(Constraint);
12243 }
12244
12245 /// Examine constraint type and operand type and determine a weight value.
12246 /// This object must already have been set up with the operand type
12247 /// and the current alternative constraint selected.
12248 TargetLowering::ConstraintWeight
12249   X86TargetLowering::getSingleConstraintMatchWeight(
12250     AsmOperandInfo &info, const char *constraint) const {
12251   ConstraintWeight weight = CW_Invalid;
12252   Value *CallOperandVal = info.CallOperandVal;
12253     // If we don't have a value, we can't do a match,
12254     // but allow it at the lowest weight.
12255   if (CallOperandVal == NULL)
12256     return CW_Default;
12257   const Type *type = CallOperandVal->getType();
12258   // Look at the constraint type.
12259   switch (*constraint) {
12260   default:
12261     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12262   case 'R':
12263   case 'q':
12264   case 'Q':
12265   case 'a':
12266   case 'b':
12267   case 'c':
12268   case 'd':
12269   case 'S':
12270   case 'D':
12271   case 'A':
12272     if (CallOperandVal->getType()->isIntegerTy())
12273       weight = CW_SpecificReg;
12274     break;
12275   case 'f':
12276   case 't':
12277   case 'u':
12278       if (type->isFloatingPointTy())
12279         weight = CW_SpecificReg;
12280       break;
12281   case 'y':
12282       if (type->isX86_MMXTy() && Subtarget->hasMMX())
12283         weight = CW_SpecificReg;
12284       break;
12285   case 'x':
12286   case 'Y':
12287     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
12288       weight = CW_Register;
12289     break;
12290   case 'I':
12291     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
12292       if (C->getZExtValue() <= 31)
12293         weight = CW_Constant;
12294     }
12295     break;
12296   case 'J':
12297     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12298       if (C->getZExtValue() <= 63)
12299         weight = CW_Constant;
12300     }
12301     break;
12302   case 'K':
12303     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12304       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
12305         weight = CW_Constant;
12306     }
12307     break;
12308   case 'L':
12309     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12310       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
12311         weight = CW_Constant;
12312     }
12313     break;
12314   case 'M':
12315     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12316       if (C->getZExtValue() <= 3)
12317         weight = CW_Constant;
12318     }
12319     break;
12320   case 'N':
12321     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12322       if (C->getZExtValue() <= 0xff)
12323         weight = CW_Constant;
12324     }
12325     break;
12326   case 'G':
12327   case 'C':
12328     if (dyn_cast<ConstantFP>(CallOperandVal)) {
12329       weight = CW_Constant;
12330     }
12331     break;
12332   case 'e':
12333     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12334       if ((C->getSExtValue() >= -0x80000000LL) &&
12335           (C->getSExtValue() <= 0x7fffffffLL))
12336         weight = CW_Constant;
12337     }
12338     break;
12339   case 'Z':
12340     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12341       if (C->getZExtValue() <= 0xffffffff)
12342         weight = CW_Constant;
12343     }
12344     break;
12345   }
12346   return weight;
12347 }
12348
12349 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12350 /// with another that has more specific requirements based on the type of the
12351 /// corresponding operand.
12352 const char *X86TargetLowering::
12353 LowerXConstraint(EVT ConstraintVT) const {
12354   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12355   // 'f' like normal targets.
12356   if (ConstraintVT.isFloatingPoint()) {
12357     if (Subtarget->hasXMMInt())
12358       return "Y";
12359     if (Subtarget->hasXMM())
12360       return "x";
12361   }
12362
12363   return TargetLowering::LowerXConstraint(ConstraintVT);
12364 }
12365
12366 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12367 /// vector.  If it is invalid, don't add anything to Ops.
12368 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12369                                                      char Constraint,
12370                                                      std::vector<SDValue>&Ops,
12371                                                      SelectionDAG &DAG) const {
12372   SDValue Result(0, 0);
12373
12374   switch (Constraint) {
12375   default: break;
12376   case 'I':
12377     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12378       if (C->getZExtValue() <= 31) {
12379         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12380         break;
12381       }
12382     }
12383     return;
12384   case 'J':
12385     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12386       if (C->getZExtValue() <= 63) {
12387         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12388         break;
12389       }
12390     }
12391     return;
12392   case 'K':
12393     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12394       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12395         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12396         break;
12397       }
12398     }
12399     return;
12400   case 'N':
12401     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12402       if (C->getZExtValue() <= 255) {
12403         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12404         break;
12405       }
12406     }
12407     return;
12408   case 'e': {
12409     // 32-bit signed value
12410     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12411       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12412                                            C->getSExtValue())) {
12413         // Widen to 64 bits here to get it sign extended.
12414         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12415         break;
12416       }
12417     // FIXME gcc accepts some relocatable values here too, but only in certain
12418     // memory models; it's complicated.
12419     }
12420     return;
12421   }
12422   case 'Z': {
12423     // 32-bit unsigned value
12424     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12425       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12426                                            C->getZExtValue())) {
12427         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12428         break;
12429       }
12430     }
12431     // FIXME gcc accepts some relocatable values here too, but only in certain
12432     // memory models; it's complicated.
12433     return;
12434   }
12435   case 'i': {
12436     // Literal immediates are always ok.
12437     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12438       // Widen to 64 bits here to get it sign extended.
12439       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12440       break;
12441     }
12442
12443     // In any sort of PIC mode addresses need to be computed at runtime by
12444     // adding in a register or some sort of table lookup.  These can't
12445     // be used as immediates.
12446     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12447       return;
12448
12449     // If we are in non-pic codegen mode, we allow the address of a global (with
12450     // an optional displacement) to be used with 'i'.
12451     GlobalAddressSDNode *GA = 0;
12452     int64_t Offset = 0;
12453
12454     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12455     while (1) {
12456       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12457         Offset += GA->getOffset();
12458         break;
12459       } else if (Op.getOpcode() == ISD::ADD) {
12460         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12461           Offset += C->getZExtValue();
12462           Op = Op.getOperand(0);
12463           continue;
12464         }
12465       } else if (Op.getOpcode() == ISD::SUB) {
12466         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12467           Offset += -C->getZExtValue();
12468           Op = Op.getOperand(0);
12469           continue;
12470         }
12471       }
12472
12473       // Otherwise, this isn't something we can handle, reject it.
12474       return;
12475     }
12476
12477     const GlobalValue *GV = GA->getGlobal();
12478     // If we require an extra load to get this address, as in PIC mode, we
12479     // can't accept it.
12480     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12481                                                         getTargetMachine())))
12482       return;
12483
12484     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12485                                         GA->getValueType(0), Offset);
12486     break;
12487   }
12488   }
12489
12490   if (Result.getNode()) {
12491     Ops.push_back(Result);
12492     return;
12493   }
12494   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12495 }
12496
12497 std::vector<unsigned> X86TargetLowering::
12498 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12499                                   EVT VT) const {
12500   if (Constraint.size() == 1) {
12501     // FIXME: not handling fp-stack yet!
12502     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12503     default: break;  // Unknown constraint letter
12504     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12505       if (Subtarget->is64Bit()) {
12506         if (VT == MVT::i32)
12507           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12508                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12509                                        X86::R10D,X86::R11D,X86::R12D,
12510                                        X86::R13D,X86::R14D,X86::R15D,
12511                                        X86::EBP, X86::ESP, 0);
12512         else if (VT == MVT::i16)
12513           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12514                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12515                                        X86::R10W,X86::R11W,X86::R12W,
12516                                        X86::R13W,X86::R14W,X86::R15W,
12517                                        X86::BP,  X86::SP, 0);
12518         else if (VT == MVT::i8)
12519           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12520                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12521                                        X86::R10B,X86::R11B,X86::R12B,
12522                                        X86::R13B,X86::R14B,X86::R15B,
12523                                        X86::BPL, X86::SPL, 0);
12524
12525         else if (VT == MVT::i64)
12526           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12527                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12528                                        X86::R10, X86::R11, X86::R12,
12529                                        X86::R13, X86::R14, X86::R15,
12530                                        X86::RBP, X86::RSP, 0);
12531
12532         break;
12533       }
12534       // 32-bit fallthrough
12535     case 'Q':   // Q_REGS
12536       if (VT == MVT::i32)
12537         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12538       else if (VT == MVT::i16)
12539         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12540       else if (VT == MVT::i8)
12541         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12542       else if (VT == MVT::i64)
12543         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12544       break;
12545     }
12546   }
12547
12548   return std::vector<unsigned>();
12549 }
12550
12551 std::pair<unsigned, const TargetRegisterClass*>
12552 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12553                                                 EVT VT) const {
12554   // First, see if this is a constraint that directly corresponds to an LLVM
12555   // register class.
12556   if (Constraint.size() == 1) {
12557     // GCC Constraint Letters
12558     switch (Constraint[0]) {
12559     default: break;
12560     case 'r':   // GENERAL_REGS
12561     case 'l':   // INDEX_REGS
12562       if (VT == MVT::i8)
12563         return std::make_pair(0U, X86::GR8RegisterClass);
12564       if (VT == MVT::i16)
12565         return std::make_pair(0U, X86::GR16RegisterClass);
12566       if (VT == MVT::i32 || !Subtarget->is64Bit())
12567         return std::make_pair(0U, X86::GR32RegisterClass);
12568       return std::make_pair(0U, X86::GR64RegisterClass);
12569     case 'R':   // LEGACY_REGS
12570       if (VT == MVT::i8)
12571         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12572       if (VT == MVT::i16)
12573         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12574       if (VT == MVT::i32 || !Subtarget->is64Bit())
12575         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12576       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12577     case 'f':  // FP Stack registers.
12578       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12579       // value to the correct fpstack register class.
12580       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12581         return std::make_pair(0U, X86::RFP32RegisterClass);
12582       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12583         return std::make_pair(0U, X86::RFP64RegisterClass);
12584       return std::make_pair(0U, X86::RFP80RegisterClass);
12585     case 'y':   // MMX_REGS if MMX allowed.
12586       if (!Subtarget->hasMMX()) break;
12587       return std::make_pair(0U, X86::VR64RegisterClass);
12588     case 'Y':   // SSE_REGS if SSE2 allowed
12589       if (!Subtarget->hasXMMInt()) break;
12590       // FALL THROUGH.
12591     case 'x':   // SSE_REGS if SSE1 allowed
12592       if (!Subtarget->hasXMM()) break;
12593
12594       switch (VT.getSimpleVT().SimpleTy) {
12595       default: break;
12596       // Scalar SSE types.
12597       case MVT::f32:
12598       case MVT::i32:
12599         return std::make_pair(0U, X86::FR32RegisterClass);
12600       case MVT::f64:
12601       case MVT::i64:
12602         return std::make_pair(0U, X86::FR64RegisterClass);
12603       // Vector types.
12604       case MVT::v16i8:
12605       case MVT::v8i16:
12606       case MVT::v4i32:
12607       case MVT::v2i64:
12608       case MVT::v4f32:
12609       case MVT::v2f64:
12610         return std::make_pair(0U, X86::VR128RegisterClass);
12611       }
12612       break;
12613     }
12614   }
12615
12616   // Use the default implementation in TargetLowering to convert the register
12617   // constraint into a member of a register class.
12618   std::pair<unsigned, const TargetRegisterClass*> Res;
12619   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12620
12621   // Not found as a standard register?
12622   if (Res.second == 0) {
12623     // Map st(0) -> st(7) -> ST0
12624     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12625         tolower(Constraint[1]) == 's' &&
12626         tolower(Constraint[2]) == 't' &&
12627         Constraint[3] == '(' &&
12628         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12629         Constraint[5] == ')' &&
12630         Constraint[6] == '}') {
12631
12632       Res.first = X86::ST0+Constraint[4]-'0';
12633       Res.second = X86::RFP80RegisterClass;
12634       return Res;
12635     }
12636
12637     // GCC allows "st(0)" to be called just plain "st".
12638     if (StringRef("{st}").equals_lower(Constraint)) {
12639       Res.first = X86::ST0;
12640       Res.second = X86::RFP80RegisterClass;
12641       return Res;
12642     }
12643
12644     // flags -> EFLAGS
12645     if (StringRef("{flags}").equals_lower(Constraint)) {
12646       Res.first = X86::EFLAGS;
12647       Res.second = X86::CCRRegisterClass;
12648       return Res;
12649     }
12650
12651     // 'A' means EAX + EDX.
12652     if (Constraint == "A") {
12653       Res.first = X86::EAX;
12654       Res.second = X86::GR32_ADRegisterClass;
12655       return Res;
12656     }
12657     return Res;
12658   }
12659
12660   // Otherwise, check to see if this is a register class of the wrong value
12661   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12662   // turn into {ax},{dx}.
12663   if (Res.second->hasType(VT))
12664     return Res;   // Correct type already, nothing to do.
12665
12666   // All of the single-register GCC register classes map their values onto
12667   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12668   // really want an 8-bit or 32-bit register, map to the appropriate register
12669   // class and return the appropriate register.
12670   if (Res.second == X86::GR16RegisterClass) {
12671     if (VT == MVT::i8) {
12672       unsigned DestReg = 0;
12673       switch (Res.first) {
12674       default: break;
12675       case X86::AX: DestReg = X86::AL; break;
12676       case X86::DX: DestReg = X86::DL; break;
12677       case X86::CX: DestReg = X86::CL; break;
12678       case X86::BX: DestReg = X86::BL; break;
12679       }
12680       if (DestReg) {
12681         Res.first = DestReg;
12682         Res.second = X86::GR8RegisterClass;
12683       }
12684     } else if (VT == MVT::i32) {
12685       unsigned DestReg = 0;
12686       switch (Res.first) {
12687       default: break;
12688       case X86::AX: DestReg = X86::EAX; break;
12689       case X86::DX: DestReg = X86::EDX; break;
12690       case X86::CX: DestReg = X86::ECX; break;
12691       case X86::BX: DestReg = X86::EBX; break;
12692       case X86::SI: DestReg = X86::ESI; break;
12693       case X86::DI: DestReg = X86::EDI; break;
12694       case X86::BP: DestReg = X86::EBP; break;
12695       case X86::SP: DestReg = X86::ESP; break;
12696       }
12697       if (DestReg) {
12698         Res.first = DestReg;
12699         Res.second = X86::GR32RegisterClass;
12700       }
12701     } else if (VT == MVT::i64) {
12702       unsigned DestReg = 0;
12703       switch (Res.first) {
12704       default: break;
12705       case X86::AX: DestReg = X86::RAX; break;
12706       case X86::DX: DestReg = X86::RDX; break;
12707       case X86::CX: DestReg = X86::RCX; break;
12708       case X86::BX: DestReg = X86::RBX; break;
12709       case X86::SI: DestReg = X86::RSI; break;
12710       case X86::DI: DestReg = X86::RDI; break;
12711       case X86::BP: DestReg = X86::RBP; break;
12712       case X86::SP: DestReg = X86::RSP; break;
12713       }
12714       if (DestReg) {
12715         Res.first = DestReg;
12716         Res.second = X86::GR64RegisterClass;
12717       }
12718     }
12719   } else if (Res.second == X86::FR32RegisterClass ||
12720              Res.second == X86::FR64RegisterClass ||
12721              Res.second == X86::VR128RegisterClass) {
12722     // Handle references to XMM physical registers that got mapped into the
12723     // wrong class.  This can happen with constraints like {xmm0} where the
12724     // target independent register mapper will just pick the first match it can
12725     // find, ignoring the required type.
12726     if (VT == MVT::f32)
12727       Res.second = X86::FR32RegisterClass;
12728     else if (VT == MVT::f64)
12729       Res.second = X86::FR64RegisterClass;
12730     else if (X86::VR128RegisterClass->hasType(VT))
12731       Res.second = X86::VR128RegisterClass;
12732   }
12733
12734   return Res;
12735 }