035248c08fa2a509e9442ef889f9fd86374da229
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference.  Idx is an index in the 128 bits we
77 /// want.  It need not be aligned to a 128-bit bounday.  That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
80                                    SDValue Idx,
81                                    SelectionDAG &DAG,
82                                    DebugLoc dl) {
83   EVT VT = Vec.getValueType();
84   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85   EVT ElVT = VT.getVectorElementType();
86   int Factor = VT.getSizeInBits()/128;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94   if (isa<ConstantSDNode>(Idx)) {
95     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98     // we can match to VEXTRACTF128.
99     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101     // This is the index of the first element of the 128-bit chunk
102     // we want.
103     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                  * ElemsPerChunk);
105
106     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                  VecIdx);
109
110     return Result;
111   }
112
113   return SDValue();
114 }
115
116 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference.  Idx is an index in the 128 bits
119 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
122                                   SDValue Vec,
123                                   SDValue Idx,
124                                   SelectionDAG &DAG,
125                                   DebugLoc dl) {
126   if (isa<ConstantSDNode>(Idx)) {
127     EVT VT = Vec.getValueType();
128     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130     EVT ElVT = VT.getVectorElementType();
131     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132     EVT ResultVT = Result.getValueType();
133
134     // Insert the relevant 128 bits.
135     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137     // This is the index of the first element of the 128-bit chunk
138     // we want.
139     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                  * ElemsPerChunk);
141
142     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                          VecIdx);
145     return Result;
146   }
147
148   return SDValue();
149 }
150
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153   bool is64Bit = Subtarget->is64Bit();
154
155   if (Subtarget->isTargetEnvMacho()) {
156     if (is64Bit)
157       return new X8664_MachoTargetObjectFile();
158     return new TargetLoweringObjectFileMachO();
159   }
160
161   if (Subtarget->isTargetELF())
162     return new TargetLoweringObjectFileELF();
163   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164     return new TargetLoweringObjectFileCOFF();
165   llvm_unreachable("unknown subtarget type");
166 }
167
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169   : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<X86Subtarget>();
171   X86ScalarSSEf64 = Subtarget->hasXMMInt() || Subtarget->hasAVX();
172   X86ScalarSSEf32 = Subtarget->hasXMM() || Subtarget->hasAVX();
173   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175   RegInfo = TM.getRegisterInfo();
176   TD = getTargetData();
177
178   // Set up the TargetLowering object.
179   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181   // X86 is weird, it always uses i8 for shift amounts and setcc results.
182   setBooleanContents(ZeroOrOneBooleanContent);
183
184   // For 64-bit since we have so many registers use the ILP scheduler, for
185   // 32-bit code use the register pressure specific scheduling.
186   if (Subtarget->is64Bit())
187     setSchedulingPreference(Sched::ILP);
188   else
189     setSchedulingPreference(Sched::RegPressure);
190   setStackPointerRegisterToSaveRestore(X86StackPtr);
191
192   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
193     // Setup Windows compiler runtime calls.
194     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
195     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
196     setLibcallName(RTLIB::SREM_I64, "_allrem");
197     setLibcallName(RTLIB::UREM_I64, "_aullrem");
198     setLibcallName(RTLIB::MUL_I64, "_allmul");
199     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
200     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
201     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
202     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
203     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
207     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
225   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
226   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
257   } else if (!UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!UseSoftFloat) {
315     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
316       // Expand FP_TO_UINT into a select.
317       // FIXME: We would like to use a Custom expander here eventually to do
318       // the optimal thing for SSE vs. the default expansion in the legalizer.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
320     else
321       // With SSE3 we can use fisttpll to convert to a signed i64; without
322       // SSE, we're stuck with a fistpll.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
324   }
325
326   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
327   if (!X86ScalarSSEf64) {
328     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
329     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
330     if (Subtarget->is64Bit()) {
331       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
332       // Without SSE, i64->f64 goes through memory.
333       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
334     }
335   }
336
337   // Scalar integer divide and remainder are lowered to use operations that
338   // produce two results, to match the available instructions. This exposes
339   // the two-result form to trivial CSE, which is able to combine x/y and x%y
340   // into a single instruction.
341   //
342   // Scalar integer multiply-high is also lowered to use two-result
343   // operations, to match the available instructions. However, plain multiply
344   // (low) operations are left as Legal, as there are single-result
345   // instructions for this in x86. Using the two-result multiply instructions
346   // when both high and low results are needed must be arranged by dagcombine.
347   for (unsigned i = 0, e = 4; i != e; ++i) {
348     MVT VT = IntVTs[i];
349     setOperationAction(ISD::MULHS, VT, Expand);
350     setOperationAction(ISD::MULHU, VT, Expand);
351     setOperationAction(ISD::SDIV, VT, Expand);
352     setOperationAction(ISD::UDIV, VT, Expand);
353     setOperationAction(ISD::SREM, VT, Expand);
354     setOperationAction(ISD::UREM, VT, Expand);
355
356     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
357     setOperationAction(ISD::ADDC, VT, Custom);
358     setOperationAction(ISD::ADDE, VT, Custom);
359     setOperationAction(ISD::SUBC, VT, Custom);
360     setOperationAction(ISD::SUBE, VT, Custom);
361   }
362
363   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
364   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
365   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
366   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
367   if (Subtarget->is64Bit())
368     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
369   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
370   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
371   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
372   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
373   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
374   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
375   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
376   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
377
378   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
379   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
380   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
381   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
382   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
383   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
384   if (Subtarget->is64Bit()) {
385     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
386     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
387   }
388
389   if (Subtarget->hasPOPCNT()) {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
391   } else {
392     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
393     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
394     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
397   }
398
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
401
402   // These should be promoted to a larger select which is supported.
403   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
404   // X86 wants to expand cmov itself.
405   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
406   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
407   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
408   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
409   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
410   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
412   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
413   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
414   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
415   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
416   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
417   if (Subtarget->is64Bit()) {
418     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
419     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
420   }
421   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
422
423   // Darwin ABI issue.
424   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
425   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
426   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
427   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
428   if (Subtarget->is64Bit())
429     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
431   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
434     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
435     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
436     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
437     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
438   }
439   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
441   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
442   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
443   if (Subtarget->is64Bit()) {
444     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
445     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
446     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
447   }
448
449   if (Subtarget->hasXMM())
450     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
451
452   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
453   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
454
455   // On X86 and X86-64, atomic operations are lowered to locked instructions.
456   // Locked instructions, in turn, have implicit fence semantics (all memory
457   // operations are flushed before issuing the locked instruction, and they
458   // are not buffered), so we can fold away the common pattern of
459   // fence-atomic-fence.
460   setShouldFoldAtomicFences(true);
461
462   // Expand certain atomics
463   for (unsigned i = 0, e = 4; i != e; ++i) {
464     MVT VT = IntVTs[i];
465     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
466     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
467     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
468   }
469
470   if (!Subtarget->is64Bit()) {
471     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
472     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
473     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
474     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
475     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
476     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
477     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
478     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
479   }
480
481   // FIXME - use subtarget debug flags
482   if (!Subtarget->isTargetDarwin() &&
483       !Subtarget->isTargetELF() &&
484       !Subtarget->isTargetCygMing()) {
485     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
486   }
487
488   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
489   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
490   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
491   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
492   if (Subtarget->is64Bit()) {
493     setExceptionPointerRegister(X86::RAX);
494     setExceptionSelectorRegister(X86::RDX);
495   } else {
496     setExceptionPointerRegister(X86::EAX);
497     setExceptionSelectorRegister(X86::EDX);
498   }
499   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
500   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
501
502   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
503
504   setOperationAction(ISD::TRAP, MVT::Other, Legal);
505
506   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
507   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
508   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
509   if (Subtarget->is64Bit()) {
510     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
511     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
512   } else {
513     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
514     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
515   }
516
517   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
518   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
519   setOperationAction(ISD::DYNAMIC_STACKALLOC,
520                      (Subtarget->is64Bit() ? MVT::i64 : MVT::i32),
521                      (Subtarget->isTargetCOFF()
522                       && !Subtarget->isTargetEnvMacho()
523                       ? Custom : Expand));
524
525   if (!UseSoftFloat && X86ScalarSSEf64) {
526     // f32 and f64 use SSE.
527     // Set up the FP register classes.
528     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
529     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
530
531     // Use ANDPD to simulate FABS.
532     setOperationAction(ISD::FABS , MVT::f64, Custom);
533     setOperationAction(ISD::FABS , MVT::f32, Custom);
534
535     // Use XORP to simulate FNEG.
536     setOperationAction(ISD::FNEG , MVT::f64, Custom);
537     setOperationAction(ISD::FNEG , MVT::f32, Custom);
538
539     // Use ANDPD and ORPD to simulate FCOPYSIGN.
540     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
541     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
542
543     // Lower this to FGETSIGNx86 plus an AND.
544     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
545     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
546
547     // We don't support sin/cos/fmod
548     setOperationAction(ISD::FSIN , MVT::f64, Expand);
549     setOperationAction(ISD::FCOS , MVT::f64, Expand);
550     setOperationAction(ISD::FSIN , MVT::f32, Expand);
551     setOperationAction(ISD::FCOS , MVT::f32, Expand);
552
553     // Expand FP immediates into loads from the stack, except for the special
554     // cases we handle.
555     addLegalFPImmediate(APFloat(+0.0)); // xorpd
556     addLegalFPImmediate(APFloat(+0.0f)); // xorps
557   } else if (!UseSoftFloat && X86ScalarSSEf32) {
558     // Use SSE for f32, x87 for f64.
559     // Set up the FP register classes.
560     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
561     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
562
563     // Use ANDPS to simulate FABS.
564     setOperationAction(ISD::FABS , MVT::f32, Custom);
565
566     // Use XORP to simulate FNEG.
567     setOperationAction(ISD::FNEG , MVT::f32, Custom);
568
569     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
570
571     // Use ANDPS and ORPS to simulate FCOPYSIGN.
572     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
573     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
574
575     // We don't support sin/cos/fmod
576     setOperationAction(ISD::FSIN , MVT::f32, Expand);
577     setOperationAction(ISD::FCOS , MVT::f32, Expand);
578
579     // Special cases we handle for FP constants.
580     addLegalFPImmediate(APFloat(+0.0f)); // xorps
581     addLegalFPImmediate(APFloat(+0.0)); // FLD0
582     addLegalFPImmediate(APFloat(+1.0)); // FLD1
583     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
584     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
585
586     if (!UnsafeFPMath) {
587       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
588       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
589     }
590   } else if (!UseSoftFloat) {
591     // f32 and f64 in x87.
592     // Set up the FP register classes.
593     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
594     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
595
596     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
597     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
598     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
599     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
600
601     if (!UnsafeFPMath) {
602       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
603       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
604     }
605     addLegalFPImmediate(APFloat(+0.0)); // FLD0
606     addLegalFPImmediate(APFloat(+1.0)); // FLD1
607     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
608     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
609     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
610     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
611     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
612     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
613   }
614
615   // We don't support FMA.
616   setOperationAction(ISD::FMA, MVT::f64, Expand);
617   setOperationAction(ISD::FMA, MVT::f32, Expand);
618
619   // Long double always uses X87.
620   if (!UseSoftFloat) {
621     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
622     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
623     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
624     {
625       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
626       addLegalFPImmediate(TmpFlt);  // FLD0
627       TmpFlt.changeSign();
628       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
629
630       bool ignored;
631       APFloat TmpFlt2(+1.0);
632       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
633                       &ignored);
634       addLegalFPImmediate(TmpFlt2);  // FLD1
635       TmpFlt2.changeSign();
636       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
637     }
638
639     if (!UnsafeFPMath) {
640       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
641       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
642     }
643
644     setOperationAction(ISD::FMA, MVT::f80, Expand);
645   }
646
647   // Always use a library call for pow.
648   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
649   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
650   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
651
652   setOperationAction(ISD::FLOG, MVT::f80, Expand);
653   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
654   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
655   setOperationAction(ISD::FEXP, MVT::f80, Expand);
656   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
657
658   // First set operation action for all vector types to either promote
659   // (for widening) or expand (for scalarization). Then we will selectively
660   // turn on ones that can be effectively codegen'd.
661   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
662        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
663     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
664     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
665     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
666     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
667     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
668     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
669     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
670     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
671     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
672     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
673     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
674     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
675     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
676     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
677     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
678     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
679     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
680     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
681     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
682     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
683     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
684     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
685     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
703     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
713     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
717     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
718          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
719       setTruncStoreAction((MVT::SimpleValueType)VT,
720                           (MVT::SimpleValueType)InnerVT, Expand);
721     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
722     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
723     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
724   }
725
726   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
727   // with -msoft-float, disable use of MMX as well.
728   if (!UseSoftFloat && Subtarget->hasMMX()) {
729     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
730     // No operations on x86mmx supported, everything uses intrinsics.
731   }
732
733   // MMX-sized vectors (other than x86mmx) are expected to be expanded
734   // into smaller operations.
735   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
736   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
737   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
738   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
739   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
740   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
741   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
742   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
743   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
744   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
745   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
746   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
747   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
748   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
749   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
750   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
751   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
752   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
753   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
754   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
755   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
756   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
757   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
758   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
759   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
760   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
761   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
762   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
763   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
764
765   if (!UseSoftFloat && Subtarget->hasXMM()) {
766     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
767
768     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
769     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
770     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
771     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
772     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
773     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
774     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
776     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
777     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
778     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
779     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
780   }
781
782   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
783     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
784
785     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
786     // registers cannot be used even for integer operations.
787     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
788     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
789     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
790     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
793     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
794     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
795     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
796     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
797     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
798     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
799     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
800     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
801     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
802     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
803     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
804     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
805     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
806     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
807     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
808
809     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
810     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
811     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
812     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
813
814     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
815     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
816     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
817     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
818     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
819
820     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
821     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
822     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
823     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
824     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
825
826     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
827     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
828       EVT VT = (MVT::SimpleValueType)i;
829       // Do not attempt to custom lower non-power-of-2 vectors
830       if (!isPowerOf2_32(VT.getVectorNumElements()))
831         continue;
832       // Do not attempt to custom lower non-128-bit vectors
833       if (!VT.is128BitVector())
834         continue;
835       setOperationAction(ISD::BUILD_VECTOR,
836                          VT.getSimpleVT().SimpleTy, Custom);
837       setOperationAction(ISD::VECTOR_SHUFFLE,
838                          VT.getSimpleVT().SimpleTy, Custom);
839       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
840                          VT.getSimpleVT().SimpleTy, Custom);
841     }
842
843     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
844     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
845     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
846     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
847     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
848     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
849
850     if (Subtarget->is64Bit()) {
851       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
852       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
853     }
854
855     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
856     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
857       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
858       EVT VT = SVT;
859
860       // Do not attempt to promote non-128-bit vectors
861       if (!VT.is128BitVector())
862         continue;
863
864       setOperationAction(ISD::AND,    SVT, Promote);
865       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
866       setOperationAction(ISD::OR,     SVT, Promote);
867       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
868       setOperationAction(ISD::XOR,    SVT, Promote);
869       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
870       setOperationAction(ISD::LOAD,   SVT, Promote);
871       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
872       setOperationAction(ISD::SELECT, SVT, Promote);
873       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
874     }
875
876     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
877
878     // Custom lower v2i64 and v2f64 selects.
879     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
880     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
881     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
882     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
883
884     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
885     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
886   }
887
888   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
889     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
890     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
891     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
892     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
893     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
894     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
895     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
896     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
897     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
898     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
899
900     // FIXME: Do we need to handle scalar-to-vector here?
901     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
902
903     // Can turn SHL into an integer multiply.
904     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
905     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
906
907     // i8 and i16 vectors are custom , because the source register and source
908     // source memory operand types are not the same width.  f32 vectors are
909     // custom since the immediate controlling the insert encodes additional
910     // information.
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
913     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
914     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
915
916     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
917     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
918     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
919     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
920
921     if (Subtarget->is64Bit()) {
922       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
923       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
924     }
925   }
926
927   if (Subtarget->hasSSE2() || Subtarget->hasAVX()) {
928     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
929     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
930     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
931     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
932
933     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
934     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
935     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
936
937     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
938     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
939   }
940
941   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
942     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
943
944   if (!UseSoftFloat && Subtarget->hasAVX()) {
945     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
946     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
947     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
948     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
949     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
950     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
951
952     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
953     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
954     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
955
956     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
957     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
958     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
959     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
960     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
961     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
962
963     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
964     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
965     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
966     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
967     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
968     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
969
970     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
971     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
972     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
973
974     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
975     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
976     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
977     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
978     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
979     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
980
981     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
982     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
983     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
984     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
985
986     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
987     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
988     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
989     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
990
991     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
992     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
993
994     setOperationAction(ISD::VSETCC,            MVT::v32i8, Custom);
995     setOperationAction(ISD::VSETCC,            MVT::v16i16, Custom);
996     setOperationAction(ISD::VSETCC,            MVT::v8i32, Custom);
997     setOperationAction(ISD::VSETCC,            MVT::v4i64, Custom);
998
999     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1000     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1001     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1002
1003     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1004     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1005     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1006     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1007
1008     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1009     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1010     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1011     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1012
1013     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1014     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1015     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1016     // Don't lower v32i8 because there is no 128-bit byte mul
1017
1018     // Custom lower several nodes for 256-bit types.
1019     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1020                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1021       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1022       EVT VT = SVT;
1023
1024       // Extract subvector is special because the value type
1025       // (result) is 128-bit but the source is 256-bit wide.
1026       if (VT.is128BitVector())
1027         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1028
1029       // Do not attempt to custom lower other non-256-bit vectors
1030       if (!VT.is256BitVector())
1031         continue;
1032
1033       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1034       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1035       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1036       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1037       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1038       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1039     }
1040
1041     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1042     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1043       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1044       EVT VT = SVT;
1045
1046       // Do not attempt to promote non-256-bit vectors
1047       if (!VT.is256BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    SVT, Promote);
1051       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1052       setOperationAction(ISD::OR,     SVT, Promote);
1053       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1054       setOperationAction(ISD::XOR,    SVT, Promote);
1055       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1056       setOperationAction(ISD::LOAD,   SVT, Promote);
1057       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1058       setOperationAction(ISD::SELECT, SVT, Promote);
1059       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1060     }
1061   }
1062
1063   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1064   // of this type with custom code.
1065   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1066          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1067     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1068   }
1069
1070   // We want to custom lower some of our intrinsics.
1071   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1072
1073
1074   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1075   // handle type legalization for these operations here.
1076   //
1077   // FIXME: We really should do custom legalization for addition and
1078   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1079   // than generic legalization for 64-bit multiplication-with-overflow, though.
1080   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1081     // Add/Sub/Mul with overflow operations are custom lowered.
1082     MVT VT = IntVTs[i];
1083     setOperationAction(ISD::SADDO, VT, Custom);
1084     setOperationAction(ISD::UADDO, VT, Custom);
1085     setOperationAction(ISD::SSUBO, VT, Custom);
1086     setOperationAction(ISD::USUBO, VT, Custom);
1087     setOperationAction(ISD::SMULO, VT, Custom);
1088     setOperationAction(ISD::UMULO, VT, Custom);
1089   }
1090
1091   // There are no 8-bit 3-address imul/mul instructions
1092   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1093   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1094
1095   if (!Subtarget->is64Bit()) {
1096     // These libcalls are not available in 32-bit.
1097     setLibcallName(RTLIB::SHL_I128, 0);
1098     setLibcallName(RTLIB::SRL_I128, 0);
1099     setLibcallName(RTLIB::SRA_I128, 0);
1100   }
1101
1102   // We have target-specific dag combine patterns for the following nodes:
1103   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1104   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1105   setTargetDAGCombine(ISD::BUILD_VECTOR);
1106   setTargetDAGCombine(ISD::SELECT);
1107   setTargetDAGCombine(ISD::SHL);
1108   setTargetDAGCombine(ISD::SRA);
1109   setTargetDAGCombine(ISD::SRL);
1110   setTargetDAGCombine(ISD::OR);
1111   setTargetDAGCombine(ISD::AND);
1112   setTargetDAGCombine(ISD::ADD);
1113   setTargetDAGCombine(ISD::SUB);
1114   setTargetDAGCombine(ISD::STORE);
1115   setTargetDAGCombine(ISD::ZERO_EXTEND);
1116   setTargetDAGCombine(ISD::SINT_TO_FP);
1117   if (Subtarget->is64Bit())
1118     setTargetDAGCombine(ISD::MUL);
1119
1120   computeRegisterProperties();
1121
1122   // On Darwin, -Os means optimize for size without hurting performance,
1123   // do not reduce the limit.
1124   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1125   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1126   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1127   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1128   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1129   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1130   setPrefLoopAlignment(16);
1131   benefitFromCodePlacementOpt = true;
1132
1133   setPrefFunctionAlignment(4);
1134 }
1135
1136
1137 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1138   return MVT::i8;
1139 }
1140
1141
1142 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1143 /// the desired ByVal argument alignment.
1144 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1145   if (MaxAlign == 16)
1146     return;
1147   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1148     if (VTy->getBitWidth() == 128)
1149       MaxAlign = 16;
1150   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1151     unsigned EltAlign = 0;
1152     getMaxByValAlign(ATy->getElementType(), EltAlign);
1153     if (EltAlign > MaxAlign)
1154       MaxAlign = EltAlign;
1155   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1156     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1157       unsigned EltAlign = 0;
1158       getMaxByValAlign(STy->getElementType(i), EltAlign);
1159       if (EltAlign > MaxAlign)
1160         MaxAlign = EltAlign;
1161       if (MaxAlign == 16)
1162         break;
1163     }
1164   }
1165   return;
1166 }
1167
1168 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1169 /// function arguments in the caller parameter area. For X86, aggregates
1170 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1171 /// are at 4-byte boundaries.
1172 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1173   if (Subtarget->is64Bit()) {
1174     // Max of 8 and alignment of type.
1175     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1176     if (TyAlign > 8)
1177       return TyAlign;
1178     return 8;
1179   }
1180
1181   unsigned Align = 4;
1182   if (Subtarget->hasXMM())
1183     getMaxByValAlign(Ty, Align);
1184   return Align;
1185 }
1186
1187 /// getOptimalMemOpType - Returns the target specific optimal type for load
1188 /// and store operations as a result of memset, memcpy, and memmove
1189 /// lowering. If DstAlign is zero that means it's safe to destination
1190 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1191 /// means there isn't a need to check it against alignment requirement,
1192 /// probably because the source does not need to be loaded. If
1193 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1194 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1195 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1196 /// constant so it does not need to be loaded.
1197 /// It returns EVT::Other if the type should be determined using generic
1198 /// target-independent logic.
1199 EVT
1200 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1201                                        unsigned DstAlign, unsigned SrcAlign,
1202                                        bool NonScalarIntSafe,
1203                                        bool MemcpyStrSrc,
1204                                        MachineFunction &MF) const {
1205   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1206   // linux.  This is because the stack realignment code can't handle certain
1207   // cases like PR2962.  This should be removed when PR2962 is fixed.
1208   const Function *F = MF.getFunction();
1209   if (NonScalarIntSafe &&
1210       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1211     if (Size >= 16 &&
1212         (Subtarget->isUnalignedMemAccessFast() ||
1213          ((DstAlign == 0 || DstAlign >= 16) &&
1214           (SrcAlign == 0 || SrcAlign >= 16))) &&
1215         Subtarget->getStackAlignment() >= 16) {
1216       if (Subtarget->hasSSE2())
1217         return MVT::v4i32;
1218       if (Subtarget->hasSSE1())
1219         return MVT::v4f32;
1220     } else if (!MemcpyStrSrc && Size >= 8 &&
1221                !Subtarget->is64Bit() &&
1222                Subtarget->getStackAlignment() >= 8 &&
1223                Subtarget->hasXMMInt()) {
1224       // Do not use f64 to lower memcpy if source is string constant. It's
1225       // better to use i32 to avoid the loads.
1226       return MVT::f64;
1227     }
1228   }
1229   if (Subtarget->is64Bit() && Size >= 8)
1230     return MVT::i64;
1231   return MVT::i32;
1232 }
1233
1234 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1235 /// current function.  The returned value is a member of the
1236 /// MachineJumpTableInfo::JTEntryKind enum.
1237 unsigned X86TargetLowering::getJumpTableEncoding() const {
1238   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1239   // symbol.
1240   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1241       Subtarget->isPICStyleGOT())
1242     return MachineJumpTableInfo::EK_Custom32;
1243
1244   // Otherwise, use the normal jump table encoding heuristics.
1245   return TargetLowering::getJumpTableEncoding();
1246 }
1247
1248 const MCExpr *
1249 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1250                                              const MachineBasicBlock *MBB,
1251                                              unsigned uid,MCContext &Ctx) const{
1252   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1253          Subtarget->isPICStyleGOT());
1254   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1255   // entries.
1256   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1257                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1258 }
1259
1260 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1261 /// jumptable.
1262 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1263                                                     SelectionDAG &DAG) const {
1264   if (!Subtarget->is64Bit())
1265     // This doesn't have DebugLoc associated with it, but is not really the
1266     // same as a Register.
1267     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1268   return Table;
1269 }
1270
1271 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1272 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1273 /// MCExpr.
1274 const MCExpr *X86TargetLowering::
1275 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1276                              MCContext &Ctx) const {
1277   // X86-64 uses RIP relative addressing based on the jump table label.
1278   if (Subtarget->isPICStyleRIPRel())
1279     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1280
1281   // Otherwise, the reference is relative to the PIC base.
1282   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1283 }
1284
1285 // FIXME: Why this routine is here? Move to RegInfo!
1286 std::pair<const TargetRegisterClass*, uint8_t>
1287 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1288   const TargetRegisterClass *RRC = 0;
1289   uint8_t Cost = 1;
1290   switch (VT.getSimpleVT().SimpleTy) {
1291   default:
1292     return TargetLowering::findRepresentativeClass(VT);
1293   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1294     RRC = (Subtarget->is64Bit()
1295            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1296     break;
1297   case MVT::x86mmx:
1298     RRC = X86::VR64RegisterClass;
1299     break;
1300   case MVT::f32: case MVT::f64:
1301   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1302   case MVT::v4f32: case MVT::v2f64:
1303   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1304   case MVT::v4f64:
1305     RRC = X86::VR128RegisterClass;
1306     break;
1307   }
1308   return std::make_pair(RRC, Cost);
1309 }
1310
1311 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1312                                                unsigned &Offset) const {
1313   if (!Subtarget->isTargetLinux())
1314     return false;
1315
1316   if (Subtarget->is64Bit()) {
1317     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1318     Offset = 0x28;
1319     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1320       AddressSpace = 256;
1321     else
1322       AddressSpace = 257;
1323   } else {
1324     // %gs:0x14 on i386
1325     Offset = 0x14;
1326     AddressSpace = 256;
1327   }
1328   return true;
1329 }
1330
1331
1332 //===----------------------------------------------------------------------===//
1333 //               Return Value Calling Convention Implementation
1334 //===----------------------------------------------------------------------===//
1335
1336 #include "X86GenCallingConv.inc"
1337
1338 bool
1339 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1340                                   MachineFunction &MF, bool isVarArg,
1341                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1342                         LLVMContext &Context) const {
1343   SmallVector<CCValAssign, 16> RVLocs;
1344   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1345                  RVLocs, Context);
1346   return CCInfo.CheckReturn(Outs, RetCC_X86);
1347 }
1348
1349 SDValue
1350 X86TargetLowering::LowerReturn(SDValue Chain,
1351                                CallingConv::ID CallConv, bool isVarArg,
1352                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1353                                const SmallVectorImpl<SDValue> &OutVals,
1354                                DebugLoc dl, SelectionDAG &DAG) const {
1355   MachineFunction &MF = DAG.getMachineFunction();
1356   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1357
1358   SmallVector<CCValAssign, 16> RVLocs;
1359   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1360                  RVLocs, *DAG.getContext());
1361   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1362
1363   // Add the regs to the liveout set for the function.
1364   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1365   for (unsigned i = 0; i != RVLocs.size(); ++i)
1366     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1367       MRI.addLiveOut(RVLocs[i].getLocReg());
1368
1369   SDValue Flag;
1370
1371   SmallVector<SDValue, 6> RetOps;
1372   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1373   // Operand #1 = Bytes To Pop
1374   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1375                    MVT::i16));
1376
1377   // Copy the result values into the output registers.
1378   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1379     CCValAssign &VA = RVLocs[i];
1380     assert(VA.isRegLoc() && "Can only return in registers!");
1381     SDValue ValToCopy = OutVals[i];
1382     EVT ValVT = ValToCopy.getValueType();
1383
1384     // If this is x86-64, and we disabled SSE, we can't return FP values,
1385     // or SSE or MMX vectors.
1386     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1387          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1388           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1389       report_fatal_error("SSE register return with SSE disabled");
1390     }
1391     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1392     // llvm-gcc has never done it right and no one has noticed, so this
1393     // should be OK for now.
1394     if (ValVT == MVT::f64 &&
1395         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1396       report_fatal_error("SSE2 register return with SSE2 disabled");
1397
1398     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1399     // the RET instruction and handled by the FP Stackifier.
1400     if (VA.getLocReg() == X86::ST0 ||
1401         VA.getLocReg() == X86::ST1) {
1402       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1403       // change the value to the FP stack register class.
1404       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1405         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1406       RetOps.push_back(ValToCopy);
1407       // Don't emit a copytoreg.
1408       continue;
1409     }
1410
1411     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1412     // which is returned in RAX / RDX.
1413     if (Subtarget->is64Bit()) {
1414       if (ValVT == MVT::x86mmx) {
1415         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1416           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1417           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1418                                   ValToCopy);
1419           // If we don't have SSE2 available, convert to v4f32 so the generated
1420           // register is legal.
1421           if (!Subtarget->hasSSE2())
1422             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1423         }
1424       }
1425     }
1426
1427     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1428     Flag = Chain.getValue(1);
1429   }
1430
1431   // The x86-64 ABI for returning structs by value requires that we copy
1432   // the sret argument into %rax for the return. We saved the argument into
1433   // a virtual register in the entry block, so now we copy the value out
1434   // and into %rax.
1435   if (Subtarget->is64Bit() &&
1436       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1437     MachineFunction &MF = DAG.getMachineFunction();
1438     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1439     unsigned Reg = FuncInfo->getSRetReturnReg();
1440     assert(Reg &&
1441            "SRetReturnReg should have been set in LowerFormalArguments().");
1442     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1443
1444     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1445     Flag = Chain.getValue(1);
1446
1447     // RAX now acts like a return value.
1448     MRI.addLiveOut(X86::RAX);
1449   }
1450
1451   RetOps[0] = Chain;  // Update chain.
1452
1453   // Add the flag if we have it.
1454   if (Flag.getNode())
1455     RetOps.push_back(Flag);
1456
1457   return DAG.getNode(X86ISD::RET_FLAG, dl,
1458                      MVT::Other, &RetOps[0], RetOps.size());
1459 }
1460
1461 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1462   if (N->getNumValues() != 1)
1463     return false;
1464   if (!N->hasNUsesOfValue(1, 0))
1465     return false;
1466
1467   SDNode *Copy = *N->use_begin();
1468   if (Copy->getOpcode() != ISD::CopyToReg &&
1469       Copy->getOpcode() != ISD::FP_EXTEND)
1470     return false;
1471
1472   bool HasRet = false;
1473   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1474        UI != UE; ++UI) {
1475     if (UI->getOpcode() != X86ISD::RET_FLAG)
1476       return false;
1477     HasRet = true;
1478   }
1479
1480   return HasRet;
1481 }
1482
1483 EVT
1484 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1485                                             ISD::NodeType ExtendKind) const {
1486   MVT ReturnMVT;
1487   // TODO: Is this also valid on 32-bit?
1488   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1489     ReturnMVT = MVT::i8;
1490   else
1491     ReturnMVT = MVT::i32;
1492
1493   EVT MinVT = getRegisterType(Context, ReturnMVT);
1494   return VT.bitsLT(MinVT) ? MinVT : VT;
1495 }
1496
1497 /// LowerCallResult - Lower the result values of a call into the
1498 /// appropriate copies out of appropriate physical registers.
1499 ///
1500 SDValue
1501 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1502                                    CallingConv::ID CallConv, bool isVarArg,
1503                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1504                                    DebugLoc dl, SelectionDAG &DAG,
1505                                    SmallVectorImpl<SDValue> &InVals) const {
1506
1507   // Assign locations to each value returned by this call.
1508   SmallVector<CCValAssign, 16> RVLocs;
1509   bool Is64Bit = Subtarget->is64Bit();
1510   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1511                  getTargetMachine(), RVLocs, *DAG.getContext());
1512   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1513
1514   // Copy all of the result registers out of their specified physreg.
1515   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1516     CCValAssign &VA = RVLocs[i];
1517     EVT CopyVT = VA.getValVT();
1518
1519     // If this is x86-64, and we disabled SSE, we can't return FP values
1520     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1521         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1522       report_fatal_error("SSE register return with SSE disabled");
1523     }
1524
1525     SDValue Val;
1526
1527     // If this is a call to a function that returns an fp value on the floating
1528     // point stack, we must guarantee the the value is popped from the stack, so
1529     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1530     // if the return value is not used. We use the FpPOP_RETVAL instruction
1531     // instead.
1532     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1533       // If we prefer to use the value in xmm registers, copy it out as f80 and
1534       // use a truncate to move it from fp stack reg to xmm reg.
1535       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1536       SDValue Ops[] = { Chain, InFlag };
1537       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1538                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1539       Val = Chain.getValue(0);
1540
1541       // Round the f80 to the right size, which also moves it to the appropriate
1542       // xmm register.
1543       if (CopyVT != VA.getValVT())
1544         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1545                           // This truncation won't change the value.
1546                           DAG.getIntPtrConstant(1));
1547     } else {
1548       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1549                                  CopyVT, InFlag).getValue(1);
1550       Val = Chain.getValue(0);
1551     }
1552     InFlag = Chain.getValue(2);
1553     InVals.push_back(Val);
1554   }
1555
1556   return Chain;
1557 }
1558
1559
1560 //===----------------------------------------------------------------------===//
1561 //                C & StdCall & Fast Calling Convention implementation
1562 //===----------------------------------------------------------------------===//
1563 //  StdCall calling convention seems to be standard for many Windows' API
1564 //  routines and around. It differs from C calling convention just a little:
1565 //  callee should clean up the stack, not caller. Symbols should be also
1566 //  decorated in some fancy way :) It doesn't support any vector arguments.
1567 //  For info on fast calling convention see Fast Calling Convention (tail call)
1568 //  implementation LowerX86_32FastCCCallTo.
1569
1570 /// CallIsStructReturn - Determines whether a call uses struct return
1571 /// semantics.
1572 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1573   if (Outs.empty())
1574     return false;
1575
1576   return Outs[0].Flags.isSRet();
1577 }
1578
1579 /// ArgsAreStructReturn - Determines whether a function uses struct
1580 /// return semantics.
1581 static bool
1582 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1583   if (Ins.empty())
1584     return false;
1585
1586   return Ins[0].Flags.isSRet();
1587 }
1588
1589 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1590 /// by "Src" to address "Dst" with size and alignment information specified by
1591 /// the specific parameter attribute. The copy will be passed as a byval
1592 /// function parameter.
1593 static SDValue
1594 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1595                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1596                           DebugLoc dl) {
1597   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1598
1599   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1600                        /*isVolatile*/false, /*AlwaysInline=*/true,
1601                        MachinePointerInfo(), MachinePointerInfo());
1602 }
1603
1604 /// IsTailCallConvention - Return true if the calling convention is one that
1605 /// supports tail call optimization.
1606 static bool IsTailCallConvention(CallingConv::ID CC) {
1607   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1608 }
1609
1610 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1611   if (!CI->isTailCall())
1612     return false;
1613
1614   CallSite CS(CI);
1615   CallingConv::ID CalleeCC = CS.getCallingConv();
1616   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1617     return false;
1618
1619   return true;
1620 }
1621
1622 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1623 /// a tailcall target by changing its ABI.
1624 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1625   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1626 }
1627
1628 SDValue
1629 X86TargetLowering::LowerMemArgument(SDValue Chain,
1630                                     CallingConv::ID CallConv,
1631                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1632                                     DebugLoc dl, SelectionDAG &DAG,
1633                                     const CCValAssign &VA,
1634                                     MachineFrameInfo *MFI,
1635                                     unsigned i) const {
1636   // Create the nodes corresponding to a load from this parameter slot.
1637   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1638   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1639   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1640   EVT ValVT;
1641
1642   // If value is passed by pointer we have address passed instead of the value
1643   // itself.
1644   if (VA.getLocInfo() == CCValAssign::Indirect)
1645     ValVT = VA.getLocVT();
1646   else
1647     ValVT = VA.getValVT();
1648
1649   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1650   // changed with more analysis.
1651   // In case of tail call optimization mark all arguments mutable. Since they
1652   // could be overwritten by lowering of arguments in case of a tail call.
1653   if (Flags.isByVal()) {
1654     unsigned Bytes = Flags.getByValSize();
1655     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1656     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1657     return DAG.getFrameIndex(FI, getPointerTy());
1658   } else {
1659     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1660                                     VA.getLocMemOffset(), isImmutable);
1661     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1662     return DAG.getLoad(ValVT, dl, Chain, FIN,
1663                        MachinePointerInfo::getFixedStack(FI),
1664                        false, false, 0);
1665   }
1666 }
1667
1668 SDValue
1669 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1670                                         CallingConv::ID CallConv,
1671                                         bool isVarArg,
1672                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1673                                         DebugLoc dl,
1674                                         SelectionDAG &DAG,
1675                                         SmallVectorImpl<SDValue> &InVals)
1676                                           const {
1677   MachineFunction &MF = DAG.getMachineFunction();
1678   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1679
1680   const Function* Fn = MF.getFunction();
1681   if (Fn->hasExternalLinkage() &&
1682       Subtarget->isTargetCygMing() &&
1683       Fn->getName() == "main")
1684     FuncInfo->setForceFramePointer(true);
1685
1686   MachineFrameInfo *MFI = MF.getFrameInfo();
1687   bool Is64Bit = Subtarget->is64Bit();
1688   bool IsWin64 = Subtarget->isTargetWin64();
1689
1690   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1691          "Var args not supported with calling convention fastcc or ghc");
1692
1693   // Assign locations to all of the incoming arguments.
1694   SmallVector<CCValAssign, 16> ArgLocs;
1695   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1696                  ArgLocs, *DAG.getContext());
1697
1698   // Allocate shadow area for Win64
1699   if (IsWin64) {
1700     CCInfo.AllocateStack(32, 8);
1701   }
1702
1703   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1704
1705   unsigned LastVal = ~0U;
1706   SDValue ArgValue;
1707   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1708     CCValAssign &VA = ArgLocs[i];
1709     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1710     // places.
1711     assert(VA.getValNo() != LastVal &&
1712            "Don't support value assigned to multiple locs yet");
1713     LastVal = VA.getValNo();
1714
1715     if (VA.isRegLoc()) {
1716       EVT RegVT = VA.getLocVT();
1717       TargetRegisterClass *RC = NULL;
1718       if (RegVT == MVT::i32)
1719         RC = X86::GR32RegisterClass;
1720       else if (Is64Bit && RegVT == MVT::i64)
1721         RC = X86::GR64RegisterClass;
1722       else if (RegVT == MVT::f32)
1723         RC = X86::FR32RegisterClass;
1724       else if (RegVT == MVT::f64)
1725         RC = X86::FR64RegisterClass;
1726       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1727         RC = X86::VR256RegisterClass;
1728       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1729         RC = X86::VR128RegisterClass;
1730       else if (RegVT == MVT::x86mmx)
1731         RC = X86::VR64RegisterClass;
1732       else
1733         llvm_unreachable("Unknown argument type!");
1734
1735       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1736       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1737
1738       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1739       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1740       // right size.
1741       if (VA.getLocInfo() == CCValAssign::SExt)
1742         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1743                                DAG.getValueType(VA.getValVT()));
1744       else if (VA.getLocInfo() == CCValAssign::ZExt)
1745         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1746                                DAG.getValueType(VA.getValVT()));
1747       else if (VA.getLocInfo() == CCValAssign::BCvt)
1748         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1749
1750       if (VA.isExtInLoc()) {
1751         // Handle MMX values passed in XMM regs.
1752         if (RegVT.isVector()) {
1753           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1754                                  ArgValue);
1755         } else
1756           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1757       }
1758     } else {
1759       assert(VA.isMemLoc());
1760       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1761     }
1762
1763     // If value is passed via pointer - do a load.
1764     if (VA.getLocInfo() == CCValAssign::Indirect)
1765       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1766                              MachinePointerInfo(), false, false, 0);
1767
1768     InVals.push_back(ArgValue);
1769   }
1770
1771   // The x86-64 ABI for returning structs by value requires that we copy
1772   // the sret argument into %rax for the return. Save the argument into
1773   // a virtual register so that we can access it from the return points.
1774   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1775     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1776     unsigned Reg = FuncInfo->getSRetReturnReg();
1777     if (!Reg) {
1778       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1779       FuncInfo->setSRetReturnReg(Reg);
1780     }
1781     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1782     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1783   }
1784
1785   unsigned StackSize = CCInfo.getNextStackOffset();
1786   // Align stack specially for tail calls.
1787   if (FuncIsMadeTailCallSafe(CallConv))
1788     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1789
1790   // If the function takes variable number of arguments, make a frame index for
1791   // the start of the first vararg value... for expansion of llvm.va_start.
1792   if (isVarArg) {
1793     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1794                     CallConv != CallingConv::X86_ThisCall)) {
1795       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1796     }
1797     if (Is64Bit) {
1798       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1799
1800       // FIXME: We should really autogenerate these arrays
1801       static const unsigned GPR64ArgRegsWin64[] = {
1802         X86::RCX, X86::RDX, X86::R8,  X86::R9
1803       };
1804       static const unsigned GPR64ArgRegs64Bit[] = {
1805         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1806       };
1807       static const unsigned XMMArgRegs64Bit[] = {
1808         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1809         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1810       };
1811       const unsigned *GPR64ArgRegs;
1812       unsigned NumXMMRegs = 0;
1813
1814       if (IsWin64) {
1815         // The XMM registers which might contain var arg parameters are shadowed
1816         // in their paired GPR.  So we only need to save the GPR to their home
1817         // slots.
1818         TotalNumIntRegs = 4;
1819         GPR64ArgRegs = GPR64ArgRegsWin64;
1820       } else {
1821         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1822         GPR64ArgRegs = GPR64ArgRegs64Bit;
1823
1824         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1825       }
1826       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1827                                                        TotalNumIntRegs);
1828
1829       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1830       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1831              "SSE register cannot be used when SSE is disabled!");
1832       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1833              "SSE register cannot be used when SSE is disabled!");
1834       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1835         // Kernel mode asks for SSE to be disabled, so don't push them
1836         // on the stack.
1837         TotalNumXMMRegs = 0;
1838
1839       if (IsWin64) {
1840         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1841         // Get to the caller-allocated home save location.  Add 8 to account
1842         // for the return address.
1843         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1844         FuncInfo->setRegSaveFrameIndex(
1845           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1846         // Fixup to set vararg frame on shadow area (4 x i64).
1847         if (NumIntRegs < 4)
1848           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1849       } else {
1850         // For X86-64, if there are vararg parameters that are passed via
1851         // registers, then we must store them to their spots on the stack so they
1852         // may be loaded by deferencing the result of va_next.
1853         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1854         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1855         FuncInfo->setRegSaveFrameIndex(
1856           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1857                                false));
1858       }
1859
1860       // Store the integer parameter registers.
1861       SmallVector<SDValue, 8> MemOps;
1862       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1863                                         getPointerTy());
1864       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1865       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1866         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1867                                   DAG.getIntPtrConstant(Offset));
1868         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1869                                      X86::GR64RegisterClass);
1870         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1871         SDValue Store =
1872           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1873                        MachinePointerInfo::getFixedStack(
1874                          FuncInfo->getRegSaveFrameIndex(), Offset),
1875                        false, false, 0);
1876         MemOps.push_back(Store);
1877         Offset += 8;
1878       }
1879
1880       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1881         // Now store the XMM (fp + vector) parameter registers.
1882         SmallVector<SDValue, 11> SaveXMMOps;
1883         SaveXMMOps.push_back(Chain);
1884
1885         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1886         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1887         SaveXMMOps.push_back(ALVal);
1888
1889         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1890                                FuncInfo->getRegSaveFrameIndex()));
1891         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1892                                FuncInfo->getVarArgsFPOffset()));
1893
1894         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1895           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1896                                        X86::VR128RegisterClass);
1897           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1898           SaveXMMOps.push_back(Val);
1899         }
1900         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1901                                      MVT::Other,
1902                                      &SaveXMMOps[0], SaveXMMOps.size()));
1903       }
1904
1905       if (!MemOps.empty())
1906         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1907                             &MemOps[0], MemOps.size());
1908     }
1909   }
1910
1911   // Some CCs need callee pop.
1912   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1913     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1914   } else {
1915     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1916     // If this is an sret function, the return should pop the hidden pointer.
1917     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1918       FuncInfo->setBytesToPopOnReturn(4);
1919   }
1920
1921   if (!Is64Bit) {
1922     // RegSaveFrameIndex is X86-64 only.
1923     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1924     if (CallConv == CallingConv::X86_FastCall ||
1925         CallConv == CallingConv::X86_ThisCall)
1926       // fastcc functions can't have varargs.
1927       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1928   }
1929
1930   return Chain;
1931 }
1932
1933 SDValue
1934 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1935                                     SDValue StackPtr, SDValue Arg,
1936                                     DebugLoc dl, SelectionDAG &DAG,
1937                                     const CCValAssign &VA,
1938                                     ISD::ArgFlagsTy Flags) const {
1939   unsigned LocMemOffset = VA.getLocMemOffset();
1940   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1941   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1942   if (Flags.isByVal())
1943     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1944
1945   return DAG.getStore(Chain, dl, Arg, PtrOff,
1946                       MachinePointerInfo::getStack(LocMemOffset),
1947                       false, false, 0);
1948 }
1949
1950 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1951 /// optimization is performed and it is required.
1952 SDValue
1953 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1954                                            SDValue &OutRetAddr, SDValue Chain,
1955                                            bool IsTailCall, bool Is64Bit,
1956                                            int FPDiff, DebugLoc dl) const {
1957   // Adjust the Return address stack slot.
1958   EVT VT = getPointerTy();
1959   OutRetAddr = getReturnAddressFrameIndex(DAG);
1960
1961   // Load the "old" Return address.
1962   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1963                            false, false, 0);
1964   return SDValue(OutRetAddr.getNode(), 1);
1965 }
1966
1967 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
1968 /// optimization is performed and it is required (FPDiff!=0).
1969 static SDValue
1970 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1971                          SDValue Chain, SDValue RetAddrFrIdx,
1972                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1973   // Store the return address to the appropriate stack slot.
1974   if (!FPDiff) return Chain;
1975   // Calculate the new stack slot for the return address.
1976   int SlotSize = Is64Bit ? 8 : 4;
1977   int NewReturnAddrFI =
1978     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1979   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1980   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1981   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1982                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1983                        false, false, 0);
1984   return Chain;
1985 }
1986
1987 SDValue
1988 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1989                              CallingConv::ID CallConv, bool isVarArg,
1990                              bool &isTailCall,
1991                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1992                              const SmallVectorImpl<SDValue> &OutVals,
1993                              const SmallVectorImpl<ISD::InputArg> &Ins,
1994                              DebugLoc dl, SelectionDAG &DAG,
1995                              SmallVectorImpl<SDValue> &InVals) const {
1996   MachineFunction &MF = DAG.getMachineFunction();
1997   bool Is64Bit        = Subtarget->is64Bit();
1998   bool IsWin64        = Subtarget->isTargetWin64();
1999   bool IsStructRet    = CallIsStructReturn(Outs);
2000   bool IsSibcall      = false;
2001
2002   if (isTailCall) {
2003     // Check if it's really possible to do a tail call.
2004     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2005                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2006                                                    Outs, OutVals, Ins, DAG);
2007
2008     // Sibcalls are automatically detected tailcalls which do not require
2009     // ABI changes.
2010     if (!GuaranteedTailCallOpt && isTailCall)
2011       IsSibcall = true;
2012
2013     if (isTailCall)
2014       ++NumTailCalls;
2015   }
2016
2017   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2018          "Var args not supported with calling convention fastcc or ghc");
2019
2020   // Analyze operands of the call, assigning locations to each operand.
2021   SmallVector<CCValAssign, 16> ArgLocs;
2022   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2023                  ArgLocs, *DAG.getContext());
2024
2025   // Allocate shadow area for Win64
2026   if (IsWin64) {
2027     CCInfo.AllocateStack(32, 8);
2028   }
2029
2030   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2031
2032   // Get a count of how many bytes are to be pushed on the stack.
2033   unsigned NumBytes = CCInfo.getNextStackOffset();
2034   if (IsSibcall)
2035     // This is a sibcall. The memory operands are available in caller's
2036     // own caller's stack.
2037     NumBytes = 0;
2038   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2039     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2040
2041   int FPDiff = 0;
2042   if (isTailCall && !IsSibcall) {
2043     // Lower arguments at fp - stackoffset + fpdiff.
2044     unsigned NumBytesCallerPushed =
2045       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2046     FPDiff = NumBytesCallerPushed - NumBytes;
2047
2048     // Set the delta of movement of the returnaddr stackslot.
2049     // But only set if delta is greater than previous delta.
2050     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2051       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2052   }
2053
2054   if (!IsSibcall)
2055     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2056
2057   SDValue RetAddrFrIdx;
2058   // Load return address for tail calls.
2059   if (isTailCall && FPDiff)
2060     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2061                                     Is64Bit, FPDiff, dl);
2062
2063   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2064   SmallVector<SDValue, 8> MemOpChains;
2065   SDValue StackPtr;
2066
2067   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2068   // of tail call optimization arguments are handle later.
2069   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2070     CCValAssign &VA = ArgLocs[i];
2071     EVT RegVT = VA.getLocVT();
2072     SDValue Arg = OutVals[i];
2073     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2074     bool isByVal = Flags.isByVal();
2075
2076     // Promote the value if needed.
2077     switch (VA.getLocInfo()) {
2078     default: llvm_unreachable("Unknown loc info!");
2079     case CCValAssign::Full: break;
2080     case CCValAssign::SExt:
2081       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2082       break;
2083     case CCValAssign::ZExt:
2084       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2085       break;
2086     case CCValAssign::AExt:
2087       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2088         // Special case: passing MMX values in XMM registers.
2089         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2090         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2091         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2092       } else
2093         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2094       break;
2095     case CCValAssign::BCvt:
2096       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2097       break;
2098     case CCValAssign::Indirect: {
2099       // Store the argument.
2100       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2101       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2102       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2103                            MachinePointerInfo::getFixedStack(FI),
2104                            false, false, 0);
2105       Arg = SpillSlot;
2106       break;
2107     }
2108     }
2109
2110     if (VA.isRegLoc()) {
2111       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2112       if (isVarArg && IsWin64) {
2113         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2114         // shadow reg if callee is a varargs function.
2115         unsigned ShadowReg = 0;
2116         switch (VA.getLocReg()) {
2117         case X86::XMM0: ShadowReg = X86::RCX; break;
2118         case X86::XMM1: ShadowReg = X86::RDX; break;
2119         case X86::XMM2: ShadowReg = X86::R8; break;
2120         case X86::XMM3: ShadowReg = X86::R9; break;
2121         }
2122         if (ShadowReg)
2123           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2124       }
2125     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2126       assert(VA.isMemLoc());
2127       if (StackPtr.getNode() == 0)
2128         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2129       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2130                                              dl, DAG, VA, Flags));
2131     }
2132   }
2133
2134   if (!MemOpChains.empty())
2135     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2136                         &MemOpChains[0], MemOpChains.size());
2137
2138   // Build a sequence of copy-to-reg nodes chained together with token chain
2139   // and flag operands which copy the outgoing args into registers.
2140   SDValue InFlag;
2141   // Tail call byval lowering might overwrite argument registers so in case of
2142   // tail call optimization the copies to registers are lowered later.
2143   if (!isTailCall)
2144     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2145       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2146                                RegsToPass[i].second, InFlag);
2147       InFlag = Chain.getValue(1);
2148     }
2149
2150   if (Subtarget->isPICStyleGOT()) {
2151     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2152     // GOT pointer.
2153     if (!isTailCall) {
2154       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2155                                DAG.getNode(X86ISD::GlobalBaseReg,
2156                                            DebugLoc(), getPointerTy()),
2157                                InFlag);
2158       InFlag = Chain.getValue(1);
2159     } else {
2160       // If we are tail calling and generating PIC/GOT style code load the
2161       // address of the callee into ECX. The value in ecx is used as target of
2162       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2163       // for tail calls on PIC/GOT architectures. Normally we would just put the
2164       // address of GOT into ebx and then call target@PLT. But for tail calls
2165       // ebx would be restored (since ebx is callee saved) before jumping to the
2166       // target@PLT.
2167
2168       // Note: The actual moving to ECX is done further down.
2169       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2170       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2171           !G->getGlobal()->hasProtectedVisibility())
2172         Callee = LowerGlobalAddress(Callee, DAG);
2173       else if (isa<ExternalSymbolSDNode>(Callee))
2174         Callee = LowerExternalSymbol(Callee, DAG);
2175     }
2176   }
2177
2178   if (Is64Bit && isVarArg && !IsWin64) {
2179     // From AMD64 ABI document:
2180     // For calls that may call functions that use varargs or stdargs
2181     // (prototype-less calls or calls to functions containing ellipsis (...) in
2182     // the declaration) %al is used as hidden argument to specify the number
2183     // of SSE registers used. The contents of %al do not need to match exactly
2184     // the number of registers, but must be an ubound on the number of SSE
2185     // registers used and is in the range 0 - 8 inclusive.
2186
2187     // Count the number of XMM registers allocated.
2188     static const unsigned XMMArgRegs[] = {
2189       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2190       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2191     };
2192     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2193     assert((Subtarget->hasXMM() || !NumXMMRegs)
2194            && "SSE registers cannot be used when SSE is disabled");
2195
2196     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2197                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2198     InFlag = Chain.getValue(1);
2199   }
2200
2201
2202   // For tail calls lower the arguments to the 'real' stack slot.
2203   if (isTailCall) {
2204     // Force all the incoming stack arguments to be loaded from the stack
2205     // before any new outgoing arguments are stored to the stack, because the
2206     // outgoing stack slots may alias the incoming argument stack slots, and
2207     // the alias isn't otherwise explicit. This is slightly more conservative
2208     // than necessary, because it means that each store effectively depends
2209     // on every argument instead of just those arguments it would clobber.
2210     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2211
2212     SmallVector<SDValue, 8> MemOpChains2;
2213     SDValue FIN;
2214     int FI = 0;
2215     // Do not flag preceding copytoreg stuff together with the following stuff.
2216     InFlag = SDValue();
2217     if (GuaranteedTailCallOpt) {
2218       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2219         CCValAssign &VA = ArgLocs[i];
2220         if (VA.isRegLoc())
2221           continue;
2222         assert(VA.isMemLoc());
2223         SDValue Arg = OutVals[i];
2224         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2225         // Create frame index.
2226         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2227         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2228         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2229         FIN = DAG.getFrameIndex(FI, getPointerTy());
2230
2231         if (Flags.isByVal()) {
2232           // Copy relative to framepointer.
2233           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2234           if (StackPtr.getNode() == 0)
2235             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2236                                           getPointerTy());
2237           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2238
2239           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2240                                                            ArgChain,
2241                                                            Flags, DAG, dl));
2242         } else {
2243           // Store relative to framepointer.
2244           MemOpChains2.push_back(
2245             DAG.getStore(ArgChain, dl, Arg, FIN,
2246                          MachinePointerInfo::getFixedStack(FI),
2247                          false, false, 0));
2248         }
2249       }
2250     }
2251
2252     if (!MemOpChains2.empty())
2253       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2254                           &MemOpChains2[0], MemOpChains2.size());
2255
2256     // Copy arguments to their registers.
2257     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2258       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2259                                RegsToPass[i].second, InFlag);
2260       InFlag = Chain.getValue(1);
2261     }
2262     InFlag =SDValue();
2263
2264     // Store the return address to the appropriate stack slot.
2265     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2266                                      FPDiff, dl);
2267   }
2268
2269   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2270     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2271     // In the 64-bit large code model, we have to make all calls
2272     // through a register, since the call instruction's 32-bit
2273     // pc-relative offset may not be large enough to hold the whole
2274     // address.
2275   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2276     // If the callee is a GlobalAddress node (quite common, every direct call
2277     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2278     // it.
2279
2280     // We should use extra load for direct calls to dllimported functions in
2281     // non-JIT mode.
2282     const GlobalValue *GV = G->getGlobal();
2283     if (!GV->hasDLLImportLinkage()) {
2284       unsigned char OpFlags = 0;
2285       bool ExtraLoad = false;
2286       unsigned WrapperKind = ISD::DELETED_NODE;
2287
2288       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2289       // external symbols most go through the PLT in PIC mode.  If the symbol
2290       // has hidden or protected visibility, or if it is static or local, then
2291       // we don't need to use the PLT - we can directly call it.
2292       if (Subtarget->isTargetELF() &&
2293           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2294           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2295         OpFlags = X86II::MO_PLT;
2296       } else if (Subtarget->isPICStyleStubAny() &&
2297                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2298                  (!Subtarget->getTargetTriple().isMacOSX() ||
2299                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2300         // PC-relative references to external symbols should go through $stub,
2301         // unless we're building with the leopard linker or later, which
2302         // automatically synthesizes these stubs.
2303         OpFlags = X86II::MO_DARWIN_STUB;
2304       } else if (Subtarget->isPICStyleRIPRel() &&
2305                  isa<Function>(GV) &&
2306                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2307         // If the function is marked as non-lazy, generate an indirect call
2308         // which loads from the GOT directly. This avoids runtime overhead
2309         // at the cost of eager binding (and one extra byte of encoding).
2310         OpFlags = X86II::MO_GOTPCREL;
2311         WrapperKind = X86ISD::WrapperRIP;
2312         ExtraLoad = true;
2313       }
2314
2315       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2316                                           G->getOffset(), OpFlags);
2317
2318       // Add a wrapper if needed.
2319       if (WrapperKind != ISD::DELETED_NODE)
2320         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2321       // Add extra indirection if needed.
2322       if (ExtraLoad)
2323         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2324                              MachinePointerInfo::getGOT(),
2325                              false, false, 0);
2326     }
2327   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2328     unsigned char OpFlags = 0;
2329
2330     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2331     // external symbols should go through the PLT.
2332     if (Subtarget->isTargetELF() &&
2333         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2334       OpFlags = X86II::MO_PLT;
2335     } else if (Subtarget->isPICStyleStubAny() &&
2336                (!Subtarget->getTargetTriple().isMacOSX() ||
2337                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2338       // PC-relative references to external symbols should go through $stub,
2339       // unless we're building with the leopard linker or later, which
2340       // automatically synthesizes these stubs.
2341       OpFlags = X86II::MO_DARWIN_STUB;
2342     }
2343
2344     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2345                                          OpFlags);
2346   }
2347
2348   // Returns a chain & a flag for retval copy to use.
2349   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2350   SmallVector<SDValue, 8> Ops;
2351
2352   if (!IsSibcall && isTailCall) {
2353     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2354                            DAG.getIntPtrConstant(0, true), InFlag);
2355     InFlag = Chain.getValue(1);
2356   }
2357
2358   Ops.push_back(Chain);
2359   Ops.push_back(Callee);
2360
2361   if (isTailCall)
2362     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2363
2364   // Add argument registers to the end of the list so that they are known live
2365   // into the call.
2366   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2367     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2368                                   RegsToPass[i].second.getValueType()));
2369
2370   // Add an implicit use GOT pointer in EBX.
2371   if (!isTailCall && Subtarget->isPICStyleGOT())
2372     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2373
2374   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2375   if (Is64Bit && isVarArg && !IsWin64)
2376     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2377
2378   if (InFlag.getNode())
2379     Ops.push_back(InFlag);
2380
2381   if (isTailCall) {
2382     // We used to do:
2383     //// If this is the first return lowered for this function, add the regs
2384     //// to the liveout set for the function.
2385     // This isn't right, although it's probably harmless on x86; liveouts
2386     // should be computed from returns not tail calls.  Consider a void
2387     // function making a tail call to a function returning int.
2388     return DAG.getNode(X86ISD::TC_RETURN, dl,
2389                        NodeTys, &Ops[0], Ops.size());
2390   }
2391
2392   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2393   InFlag = Chain.getValue(1);
2394
2395   // Create the CALLSEQ_END node.
2396   unsigned NumBytesForCalleeToPush;
2397   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2398     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2399   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2400     // If this is a call to a struct-return function, the callee
2401     // pops the hidden struct pointer, so we have to push it back.
2402     // This is common for Darwin/X86, Linux & Mingw32 targets.
2403     NumBytesForCalleeToPush = 4;
2404   else
2405     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2406
2407   // Returns a flag for retval copy to use.
2408   if (!IsSibcall) {
2409     Chain = DAG.getCALLSEQ_END(Chain,
2410                                DAG.getIntPtrConstant(NumBytes, true),
2411                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2412                                                      true),
2413                                InFlag);
2414     InFlag = Chain.getValue(1);
2415   }
2416
2417   // Handle result values, copying them out of physregs into vregs that we
2418   // return.
2419   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2420                          Ins, dl, DAG, InVals);
2421 }
2422
2423
2424 //===----------------------------------------------------------------------===//
2425 //                Fast Calling Convention (tail call) implementation
2426 //===----------------------------------------------------------------------===//
2427
2428 //  Like std call, callee cleans arguments, convention except that ECX is
2429 //  reserved for storing the tail called function address. Only 2 registers are
2430 //  free for argument passing (inreg). Tail call optimization is performed
2431 //  provided:
2432 //                * tailcallopt is enabled
2433 //                * caller/callee are fastcc
2434 //  On X86_64 architecture with GOT-style position independent code only local
2435 //  (within module) calls are supported at the moment.
2436 //  To keep the stack aligned according to platform abi the function
2437 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2438 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2439 //  If a tail called function callee has more arguments than the caller the
2440 //  caller needs to make sure that there is room to move the RETADDR to. This is
2441 //  achieved by reserving an area the size of the argument delta right after the
2442 //  original REtADDR, but before the saved framepointer or the spilled registers
2443 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2444 //  stack layout:
2445 //    arg1
2446 //    arg2
2447 //    RETADDR
2448 //    [ new RETADDR
2449 //      move area ]
2450 //    (possible EBP)
2451 //    ESI
2452 //    EDI
2453 //    local1 ..
2454
2455 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2456 /// for a 16 byte align requirement.
2457 unsigned
2458 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2459                                                SelectionDAG& DAG) const {
2460   MachineFunction &MF = DAG.getMachineFunction();
2461   const TargetMachine &TM = MF.getTarget();
2462   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2463   unsigned StackAlignment = TFI.getStackAlignment();
2464   uint64_t AlignMask = StackAlignment - 1;
2465   int64_t Offset = StackSize;
2466   uint64_t SlotSize = TD->getPointerSize();
2467   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2468     // Number smaller than 12 so just add the difference.
2469     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2470   } else {
2471     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2472     Offset = ((~AlignMask) & Offset) + StackAlignment +
2473       (StackAlignment-SlotSize);
2474   }
2475   return Offset;
2476 }
2477
2478 /// MatchingStackOffset - Return true if the given stack call argument is
2479 /// already available in the same position (relatively) of the caller's
2480 /// incoming argument stack.
2481 static
2482 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2483                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2484                          const X86InstrInfo *TII) {
2485   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2486   int FI = INT_MAX;
2487   if (Arg.getOpcode() == ISD::CopyFromReg) {
2488     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2489     if (!TargetRegisterInfo::isVirtualRegister(VR))
2490       return false;
2491     MachineInstr *Def = MRI->getVRegDef(VR);
2492     if (!Def)
2493       return false;
2494     if (!Flags.isByVal()) {
2495       if (!TII->isLoadFromStackSlot(Def, FI))
2496         return false;
2497     } else {
2498       unsigned Opcode = Def->getOpcode();
2499       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2500           Def->getOperand(1).isFI()) {
2501         FI = Def->getOperand(1).getIndex();
2502         Bytes = Flags.getByValSize();
2503       } else
2504         return false;
2505     }
2506   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2507     if (Flags.isByVal())
2508       // ByVal argument is passed in as a pointer but it's now being
2509       // dereferenced. e.g.
2510       // define @foo(%struct.X* %A) {
2511       //   tail call @bar(%struct.X* byval %A)
2512       // }
2513       return false;
2514     SDValue Ptr = Ld->getBasePtr();
2515     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2516     if (!FINode)
2517       return false;
2518     FI = FINode->getIndex();
2519   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2520     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2521     FI = FINode->getIndex();
2522     Bytes = Flags.getByValSize();
2523   } else
2524     return false;
2525
2526   assert(FI != INT_MAX);
2527   if (!MFI->isFixedObjectIndex(FI))
2528     return false;
2529   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2530 }
2531
2532 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2533 /// for tail call optimization. Targets which want to do tail call
2534 /// optimization should implement this function.
2535 bool
2536 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2537                                                      CallingConv::ID CalleeCC,
2538                                                      bool isVarArg,
2539                                                      bool isCalleeStructRet,
2540                                                      bool isCallerStructRet,
2541                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2542                                     const SmallVectorImpl<SDValue> &OutVals,
2543                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2544                                                      SelectionDAG& DAG) const {
2545   if (!IsTailCallConvention(CalleeCC) &&
2546       CalleeCC != CallingConv::C)
2547     return false;
2548
2549   // If -tailcallopt is specified, make fastcc functions tail-callable.
2550   const MachineFunction &MF = DAG.getMachineFunction();
2551   const Function *CallerF = DAG.getMachineFunction().getFunction();
2552   CallingConv::ID CallerCC = CallerF->getCallingConv();
2553   bool CCMatch = CallerCC == CalleeCC;
2554
2555   if (GuaranteedTailCallOpt) {
2556     if (IsTailCallConvention(CalleeCC) && CCMatch)
2557       return true;
2558     return false;
2559   }
2560
2561   // Look for obvious safe cases to perform tail call optimization that do not
2562   // require ABI changes. This is what gcc calls sibcall.
2563
2564   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2565   // emit a special epilogue.
2566   if (RegInfo->needsStackRealignment(MF))
2567     return false;
2568
2569   // Also avoid sibcall optimization if either caller or callee uses struct
2570   // return semantics.
2571   if (isCalleeStructRet || isCallerStructRet)
2572     return false;
2573
2574   // An stdcall caller is expected to clean up its arguments; the callee
2575   // isn't going to do that.
2576   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2577     return false;
2578
2579   // Do not sibcall optimize vararg calls unless all arguments are passed via
2580   // registers.
2581   if (isVarArg && !Outs.empty()) {
2582
2583     // Optimizing for varargs on Win64 is unlikely to be safe without
2584     // additional testing.
2585     if (Subtarget->isTargetWin64())
2586       return false;
2587
2588     SmallVector<CCValAssign, 16> ArgLocs;
2589     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2590                    getTargetMachine(), ArgLocs, *DAG.getContext());
2591
2592     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2593     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2594       if (!ArgLocs[i].isRegLoc())
2595         return false;
2596   }
2597
2598   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2599   // Therefore if it's not used by the call it is not safe to optimize this into
2600   // a sibcall.
2601   bool Unused = false;
2602   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2603     if (!Ins[i].Used) {
2604       Unused = true;
2605       break;
2606     }
2607   }
2608   if (Unused) {
2609     SmallVector<CCValAssign, 16> RVLocs;
2610     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2611                    getTargetMachine(), RVLocs, *DAG.getContext());
2612     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2613     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2614       CCValAssign &VA = RVLocs[i];
2615       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2616         return false;
2617     }
2618   }
2619
2620   // If the calling conventions do not match, then we'd better make sure the
2621   // results are returned in the same way as what the caller expects.
2622   if (!CCMatch) {
2623     SmallVector<CCValAssign, 16> RVLocs1;
2624     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2625                     getTargetMachine(), RVLocs1, *DAG.getContext());
2626     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2627
2628     SmallVector<CCValAssign, 16> RVLocs2;
2629     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2630                     getTargetMachine(), RVLocs2, *DAG.getContext());
2631     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2632
2633     if (RVLocs1.size() != RVLocs2.size())
2634       return false;
2635     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2636       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2637         return false;
2638       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2639         return false;
2640       if (RVLocs1[i].isRegLoc()) {
2641         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2642           return false;
2643       } else {
2644         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2645           return false;
2646       }
2647     }
2648   }
2649
2650   // If the callee takes no arguments then go on to check the results of the
2651   // call.
2652   if (!Outs.empty()) {
2653     // Check if stack adjustment is needed. For now, do not do this if any
2654     // argument is passed on the stack.
2655     SmallVector<CCValAssign, 16> ArgLocs;
2656     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2657                    getTargetMachine(), ArgLocs, *DAG.getContext());
2658
2659     // Allocate shadow area for Win64
2660     if (Subtarget->isTargetWin64()) {
2661       CCInfo.AllocateStack(32, 8);
2662     }
2663
2664     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2665     if (CCInfo.getNextStackOffset()) {
2666       MachineFunction &MF = DAG.getMachineFunction();
2667       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2668         return false;
2669
2670       // Check if the arguments are already laid out in the right way as
2671       // the caller's fixed stack objects.
2672       MachineFrameInfo *MFI = MF.getFrameInfo();
2673       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2674       const X86InstrInfo *TII =
2675         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2676       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2677         CCValAssign &VA = ArgLocs[i];
2678         SDValue Arg = OutVals[i];
2679         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2680         if (VA.getLocInfo() == CCValAssign::Indirect)
2681           return false;
2682         if (!VA.isRegLoc()) {
2683           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2684                                    MFI, MRI, TII))
2685             return false;
2686         }
2687       }
2688     }
2689
2690     // If the tailcall address may be in a register, then make sure it's
2691     // possible to register allocate for it. In 32-bit, the call address can
2692     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2693     // callee-saved registers are restored. These happen to be the same
2694     // registers used to pass 'inreg' arguments so watch out for those.
2695     if (!Subtarget->is64Bit() &&
2696         !isa<GlobalAddressSDNode>(Callee) &&
2697         !isa<ExternalSymbolSDNode>(Callee)) {
2698       unsigned NumInRegs = 0;
2699       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2700         CCValAssign &VA = ArgLocs[i];
2701         if (!VA.isRegLoc())
2702           continue;
2703         unsigned Reg = VA.getLocReg();
2704         switch (Reg) {
2705         default: break;
2706         case X86::EAX: case X86::EDX: case X86::ECX:
2707           if (++NumInRegs == 3)
2708             return false;
2709           break;
2710         }
2711       }
2712     }
2713   }
2714
2715   return true;
2716 }
2717
2718 FastISel *
2719 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2720   return X86::createFastISel(funcInfo);
2721 }
2722
2723
2724 //===----------------------------------------------------------------------===//
2725 //                           Other Lowering Hooks
2726 //===----------------------------------------------------------------------===//
2727
2728 static bool MayFoldLoad(SDValue Op) {
2729   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2730 }
2731
2732 static bool MayFoldIntoStore(SDValue Op) {
2733   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2734 }
2735
2736 static bool isTargetShuffle(unsigned Opcode) {
2737   switch(Opcode) {
2738   default: return false;
2739   case X86ISD::PSHUFD:
2740   case X86ISD::PSHUFHW:
2741   case X86ISD::PSHUFLW:
2742   case X86ISD::SHUFPD:
2743   case X86ISD::PALIGN:
2744   case X86ISD::SHUFPS:
2745   case X86ISD::MOVLHPS:
2746   case X86ISD::MOVLHPD:
2747   case X86ISD::MOVHLPS:
2748   case X86ISD::MOVLPS:
2749   case X86ISD::MOVLPD:
2750   case X86ISD::MOVSHDUP:
2751   case X86ISD::MOVSLDUP:
2752   case X86ISD::MOVDDUP:
2753   case X86ISD::MOVSS:
2754   case X86ISD::MOVSD:
2755   case X86ISD::UNPCKLPS:
2756   case X86ISD::UNPCKLPD:
2757   case X86ISD::VUNPCKLPSY:
2758   case X86ISD::VUNPCKLPDY:
2759   case X86ISD::PUNPCKLWD:
2760   case X86ISD::PUNPCKLBW:
2761   case X86ISD::PUNPCKLDQ:
2762   case X86ISD::PUNPCKLQDQ:
2763   case X86ISD::UNPCKHPS:
2764   case X86ISD::UNPCKHPD:
2765   case X86ISD::VUNPCKHPSY:
2766   case X86ISD::VUNPCKHPDY:
2767   case X86ISD::PUNPCKHWD:
2768   case X86ISD::PUNPCKHBW:
2769   case X86ISD::PUNPCKHDQ:
2770   case X86ISD::PUNPCKHQDQ:
2771   case X86ISD::VPERMILPS:
2772   case X86ISD::VPERMILPSY:
2773   case X86ISD::VPERMILPD:
2774   case X86ISD::VPERMILPDY:
2775   case X86ISD::VPERM2F128:
2776     return true;
2777   }
2778   return false;
2779 }
2780
2781 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2782                                                SDValue V1, SelectionDAG &DAG) {
2783   switch(Opc) {
2784   default: llvm_unreachable("Unknown x86 shuffle node");
2785   case X86ISD::MOVSHDUP:
2786   case X86ISD::MOVSLDUP:
2787   case X86ISD::MOVDDUP:
2788     return DAG.getNode(Opc, dl, VT, V1);
2789   }
2790
2791   return SDValue();
2792 }
2793
2794 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2795                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2796   switch(Opc) {
2797   default: llvm_unreachable("Unknown x86 shuffle node");
2798   case X86ISD::PSHUFD:
2799   case X86ISD::PSHUFHW:
2800   case X86ISD::PSHUFLW:
2801   case X86ISD::VPERMILPS:
2802   case X86ISD::VPERMILPSY:
2803   case X86ISD::VPERMILPD:
2804   case X86ISD::VPERMILPDY:
2805     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2806   }
2807
2808   return SDValue();
2809 }
2810
2811 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2812                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2813   switch(Opc) {
2814   default: llvm_unreachable("Unknown x86 shuffle node");
2815   case X86ISD::PALIGN:
2816   case X86ISD::SHUFPD:
2817   case X86ISD::SHUFPS:
2818   case X86ISD::VPERM2F128:
2819     return DAG.getNode(Opc, dl, VT, V1, V2,
2820                        DAG.getConstant(TargetMask, MVT::i8));
2821   }
2822   return SDValue();
2823 }
2824
2825 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2826                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2827   switch(Opc) {
2828   default: llvm_unreachable("Unknown x86 shuffle node");
2829   case X86ISD::MOVLHPS:
2830   case X86ISD::MOVLHPD:
2831   case X86ISD::MOVHLPS:
2832   case X86ISD::MOVLPS:
2833   case X86ISD::MOVLPD:
2834   case X86ISD::MOVSS:
2835   case X86ISD::MOVSD:
2836   case X86ISD::UNPCKLPS:
2837   case X86ISD::UNPCKLPD:
2838   case X86ISD::VUNPCKLPSY:
2839   case X86ISD::VUNPCKLPDY:
2840   case X86ISD::PUNPCKLWD:
2841   case X86ISD::PUNPCKLBW:
2842   case X86ISD::PUNPCKLDQ:
2843   case X86ISD::PUNPCKLQDQ:
2844   case X86ISD::UNPCKHPS:
2845   case X86ISD::UNPCKHPD:
2846   case X86ISD::VUNPCKHPSY:
2847   case X86ISD::VUNPCKHPDY:
2848   case X86ISD::PUNPCKHWD:
2849   case X86ISD::PUNPCKHBW:
2850   case X86ISD::PUNPCKHDQ:
2851   case X86ISD::PUNPCKHQDQ:
2852     return DAG.getNode(Opc, dl, VT, V1, V2);
2853   }
2854   return SDValue();
2855 }
2856
2857 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2858   MachineFunction &MF = DAG.getMachineFunction();
2859   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2860   int ReturnAddrIndex = FuncInfo->getRAIndex();
2861
2862   if (ReturnAddrIndex == 0) {
2863     // Set up a frame object for the return address.
2864     uint64_t SlotSize = TD->getPointerSize();
2865     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2866                                                            false);
2867     FuncInfo->setRAIndex(ReturnAddrIndex);
2868   }
2869
2870   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2871 }
2872
2873
2874 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2875                                        bool hasSymbolicDisplacement) {
2876   // Offset should fit into 32 bit immediate field.
2877   if (!isInt<32>(Offset))
2878     return false;
2879
2880   // If we don't have a symbolic displacement - we don't have any extra
2881   // restrictions.
2882   if (!hasSymbolicDisplacement)
2883     return true;
2884
2885   // FIXME: Some tweaks might be needed for medium code model.
2886   if (M != CodeModel::Small && M != CodeModel::Kernel)
2887     return false;
2888
2889   // For small code model we assume that latest object is 16MB before end of 31
2890   // bits boundary. We may also accept pretty large negative constants knowing
2891   // that all objects are in the positive half of address space.
2892   if (M == CodeModel::Small && Offset < 16*1024*1024)
2893     return true;
2894
2895   // For kernel code model we know that all object resist in the negative half
2896   // of 32bits address space. We may not accept negative offsets, since they may
2897   // be just off and we may accept pretty large positive ones.
2898   if (M == CodeModel::Kernel && Offset > 0)
2899     return true;
2900
2901   return false;
2902 }
2903
2904 /// isCalleePop - Determines whether the callee is required to pop its
2905 /// own arguments. Callee pop is necessary to support tail calls.
2906 bool X86::isCalleePop(CallingConv::ID CallingConv,
2907                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2908   if (IsVarArg)
2909     return false;
2910
2911   switch (CallingConv) {
2912   default:
2913     return false;
2914   case CallingConv::X86_StdCall:
2915     return !is64Bit;
2916   case CallingConv::X86_FastCall:
2917     return !is64Bit;
2918   case CallingConv::X86_ThisCall:
2919     return !is64Bit;
2920   case CallingConv::Fast:
2921     return TailCallOpt;
2922   case CallingConv::GHC:
2923     return TailCallOpt;
2924   }
2925 }
2926
2927 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2928 /// specific condition code, returning the condition code and the LHS/RHS of the
2929 /// comparison to make.
2930 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2931                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2932   if (!isFP) {
2933     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2934       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2935         // X > -1   -> X == 0, jump !sign.
2936         RHS = DAG.getConstant(0, RHS.getValueType());
2937         return X86::COND_NS;
2938       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2939         // X < 0   -> X == 0, jump on sign.
2940         return X86::COND_S;
2941       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2942         // X < 1   -> X <= 0
2943         RHS = DAG.getConstant(0, RHS.getValueType());
2944         return X86::COND_LE;
2945       }
2946     }
2947
2948     switch (SetCCOpcode) {
2949     default: llvm_unreachable("Invalid integer condition!");
2950     case ISD::SETEQ:  return X86::COND_E;
2951     case ISD::SETGT:  return X86::COND_G;
2952     case ISD::SETGE:  return X86::COND_GE;
2953     case ISD::SETLT:  return X86::COND_L;
2954     case ISD::SETLE:  return X86::COND_LE;
2955     case ISD::SETNE:  return X86::COND_NE;
2956     case ISD::SETULT: return X86::COND_B;
2957     case ISD::SETUGT: return X86::COND_A;
2958     case ISD::SETULE: return X86::COND_BE;
2959     case ISD::SETUGE: return X86::COND_AE;
2960     }
2961   }
2962
2963   // First determine if it is required or is profitable to flip the operands.
2964
2965   // If LHS is a foldable load, but RHS is not, flip the condition.
2966   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2967       !ISD::isNON_EXTLoad(RHS.getNode())) {
2968     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2969     std::swap(LHS, RHS);
2970   }
2971
2972   switch (SetCCOpcode) {
2973   default: break;
2974   case ISD::SETOLT:
2975   case ISD::SETOLE:
2976   case ISD::SETUGT:
2977   case ISD::SETUGE:
2978     std::swap(LHS, RHS);
2979     break;
2980   }
2981
2982   // On a floating point condition, the flags are set as follows:
2983   // ZF  PF  CF   op
2984   //  0 | 0 | 0 | X > Y
2985   //  0 | 0 | 1 | X < Y
2986   //  1 | 0 | 0 | X == Y
2987   //  1 | 1 | 1 | unordered
2988   switch (SetCCOpcode) {
2989   default: llvm_unreachable("Condcode should be pre-legalized away");
2990   case ISD::SETUEQ:
2991   case ISD::SETEQ:   return X86::COND_E;
2992   case ISD::SETOLT:              // flipped
2993   case ISD::SETOGT:
2994   case ISD::SETGT:   return X86::COND_A;
2995   case ISD::SETOLE:              // flipped
2996   case ISD::SETOGE:
2997   case ISD::SETGE:   return X86::COND_AE;
2998   case ISD::SETUGT:              // flipped
2999   case ISD::SETULT:
3000   case ISD::SETLT:   return X86::COND_B;
3001   case ISD::SETUGE:              // flipped
3002   case ISD::SETULE:
3003   case ISD::SETLE:   return X86::COND_BE;
3004   case ISD::SETONE:
3005   case ISD::SETNE:   return X86::COND_NE;
3006   case ISD::SETUO:   return X86::COND_P;
3007   case ISD::SETO:    return X86::COND_NP;
3008   case ISD::SETOEQ:
3009   case ISD::SETUNE:  return X86::COND_INVALID;
3010   }
3011 }
3012
3013 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3014 /// code. Current x86 isa includes the following FP cmov instructions:
3015 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3016 static bool hasFPCMov(unsigned X86CC) {
3017   switch (X86CC) {
3018   default:
3019     return false;
3020   case X86::COND_B:
3021   case X86::COND_BE:
3022   case X86::COND_E:
3023   case X86::COND_P:
3024   case X86::COND_A:
3025   case X86::COND_AE:
3026   case X86::COND_NE:
3027   case X86::COND_NP:
3028     return true;
3029   }
3030 }
3031
3032 /// isFPImmLegal - Returns true if the target can instruction select the
3033 /// specified FP immediate natively. If false, the legalizer will
3034 /// materialize the FP immediate as a load from a constant pool.
3035 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3036   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3037     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3038       return true;
3039   }
3040   return false;
3041 }
3042
3043 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3044 /// the specified range (L, H].
3045 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3046   return (Val < 0) || (Val >= Low && Val < Hi);
3047 }
3048
3049 /// isUndefOrInRange - Return true if every element in Mask, begining
3050 /// from position Pos and ending in Pos+Size, falls within the specified
3051 /// range (L, L+Pos]. or is undef.
3052 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3053                              int Pos, int Size, int Low, int Hi) {
3054   for (int i = Pos, e = Pos+Size; i != e; ++i)
3055     if (!isUndefOrInRange(Mask[i], Low, Hi))
3056       return false;
3057   return true;
3058 }
3059
3060 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3061 /// specified value.
3062 static bool isUndefOrEqual(int Val, int CmpVal) {
3063   if (Val < 0 || Val == CmpVal)
3064     return true;
3065   return false;
3066 }
3067
3068 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3069 /// from position Pos and ending in Pos+Size, falls within the specified
3070 /// sequential range (L, L+Pos]. or is undef.
3071 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3072                                        int Pos, int Size, int Low) {
3073   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3074     if (!isUndefOrEqual(Mask[i], Low))
3075       return false;
3076   return true;
3077 }
3078
3079 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3080 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3081 /// the second operand.
3082 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3083   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3084     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3085   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3086     return (Mask[0] < 2 && Mask[1] < 2);
3087   return false;
3088 }
3089
3090 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3091   SmallVector<int, 8> M;
3092   N->getMask(M);
3093   return ::isPSHUFDMask(M, N->getValueType(0));
3094 }
3095
3096 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3097 /// is suitable for input to PSHUFHW.
3098 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3099   if (VT != MVT::v8i16)
3100     return false;
3101
3102   // Lower quadword copied in order or undef.
3103   for (int i = 0; i != 4; ++i)
3104     if (Mask[i] >= 0 && Mask[i] != i)
3105       return false;
3106
3107   // Upper quadword shuffled.
3108   for (int i = 4; i != 8; ++i)
3109     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3110       return false;
3111
3112   return true;
3113 }
3114
3115 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3116   SmallVector<int, 8> M;
3117   N->getMask(M);
3118   return ::isPSHUFHWMask(M, N->getValueType(0));
3119 }
3120
3121 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3122 /// is suitable for input to PSHUFLW.
3123 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3124   if (VT != MVT::v8i16)
3125     return false;
3126
3127   // Upper quadword copied in order.
3128   for (int i = 4; i != 8; ++i)
3129     if (Mask[i] >= 0 && Mask[i] != i)
3130       return false;
3131
3132   // Lower quadword shuffled.
3133   for (int i = 0; i != 4; ++i)
3134     if (Mask[i] >= 4)
3135       return false;
3136
3137   return true;
3138 }
3139
3140 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3141   SmallVector<int, 8> M;
3142   N->getMask(M);
3143   return ::isPSHUFLWMask(M, N->getValueType(0));
3144 }
3145
3146 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3147 /// is suitable for input to PALIGNR.
3148 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3149                           bool hasSSSE3) {
3150   int i, e = VT.getVectorNumElements();
3151   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3152     return false;
3153
3154   // Do not handle v2i64 / v2f64 shuffles with palignr.
3155   if (e < 4 || !hasSSSE3)
3156     return false;
3157
3158   for (i = 0; i != e; ++i)
3159     if (Mask[i] >= 0)
3160       break;
3161
3162   // All undef, not a palignr.
3163   if (i == e)
3164     return false;
3165
3166   // Make sure we're shifting in the right direction.
3167   if (Mask[i] <= i)
3168     return false;
3169
3170   int s = Mask[i] - i;
3171
3172   // Check the rest of the elements to see if they are consecutive.
3173   for (++i; i != e; ++i) {
3174     int m = Mask[i];
3175     if (m >= 0 && m != s+i)
3176       return false;
3177   }
3178   return true;
3179 }
3180
3181 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3182 /// specifies a shuffle of elements that is suitable for input to 128-bit
3183 /// SHUFPS and SHUFPD.
3184 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3185   int NumElems = VT.getVectorNumElements();
3186
3187   if (VT.getSizeInBits() != 128)
3188     return false;
3189
3190   if (NumElems != 2 && NumElems != 4)
3191     return false;
3192
3193   int Half = NumElems / 2;
3194   for (int i = 0; i < Half; ++i)
3195     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3196       return false;
3197   for (int i = Half; i < NumElems; ++i)
3198     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3199       return false;
3200
3201   return true;
3202 }
3203
3204 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3205   SmallVector<int, 8> M;
3206   N->getMask(M);
3207   return ::isSHUFPMask(M, N->getValueType(0));
3208 }
3209
3210 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3211 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3212 /// half elements to come from vector 1 (which would equal the dest.) and
3213 /// the upper half to come from vector 2.
3214 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3215   int NumElems = VT.getVectorNumElements();
3216
3217   if (NumElems != 2 && NumElems != 4)
3218     return false;
3219
3220   int Half = NumElems / 2;
3221   for (int i = 0; i < Half; ++i)
3222     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3223       return false;
3224   for (int i = Half; i < NumElems; ++i)
3225     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3226       return false;
3227   return true;
3228 }
3229
3230 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3231   SmallVector<int, 8> M;
3232   N->getMask(M);
3233   return isCommutedSHUFPMask(M, N->getValueType(0));
3234 }
3235
3236 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3237 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3238 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3239   EVT VT = N->getValueType(0);
3240   unsigned NumElems = VT.getVectorNumElements();
3241
3242   if (VT.getSizeInBits() != 128)
3243     return false;
3244
3245   if (NumElems != 4)
3246     return false;
3247
3248   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3249   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3250          isUndefOrEqual(N->getMaskElt(1), 7) &&
3251          isUndefOrEqual(N->getMaskElt(2), 2) &&
3252          isUndefOrEqual(N->getMaskElt(3), 3);
3253 }
3254
3255 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3256 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3257 /// <2, 3, 2, 3>
3258 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3259   EVT VT = N->getValueType(0);
3260   unsigned NumElems = VT.getVectorNumElements();
3261
3262   if (VT.getSizeInBits() != 128)
3263     return false;
3264
3265   if (NumElems != 4)
3266     return false;
3267
3268   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3269          isUndefOrEqual(N->getMaskElt(1), 3) &&
3270          isUndefOrEqual(N->getMaskElt(2), 2) &&
3271          isUndefOrEqual(N->getMaskElt(3), 3);
3272 }
3273
3274 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3275 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3276 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3277   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3278
3279   if (NumElems != 2 && NumElems != 4)
3280     return false;
3281
3282   for (unsigned i = 0; i < NumElems/2; ++i)
3283     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3284       return false;
3285
3286   for (unsigned i = NumElems/2; i < NumElems; ++i)
3287     if (!isUndefOrEqual(N->getMaskElt(i), i))
3288       return false;
3289
3290   return true;
3291 }
3292
3293 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3294 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3295 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3296   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3297
3298   if ((NumElems != 2 && NumElems != 4)
3299       || N->getValueType(0).getSizeInBits() > 128)
3300     return false;
3301
3302   for (unsigned i = 0; i < NumElems/2; ++i)
3303     if (!isUndefOrEqual(N->getMaskElt(i), i))
3304       return false;
3305
3306   for (unsigned i = 0; i < NumElems/2; ++i)
3307     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3308       return false;
3309
3310   return true;
3311 }
3312
3313 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3314 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3315 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3316                          bool V2IsSplat = false) {
3317   int NumElts = VT.getVectorNumElements();
3318
3319   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3320          "Unsupported vector type for unpckh");
3321
3322   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3323     return false;
3324
3325   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3326   // independently on 128-bit lanes.
3327   unsigned NumLanes = VT.getSizeInBits()/128;
3328   unsigned NumLaneElts = NumElts/NumLanes;
3329
3330   unsigned Start = 0;
3331   unsigned End = NumLaneElts;
3332   for (unsigned s = 0; s < NumLanes; ++s) {
3333     for (unsigned i = Start, j = s * NumLaneElts;
3334          i != End;
3335          i += 2, ++j) {
3336       int BitI  = Mask[i];
3337       int BitI1 = Mask[i+1];
3338       if (!isUndefOrEqual(BitI, j))
3339         return false;
3340       if (V2IsSplat) {
3341         if (!isUndefOrEqual(BitI1, NumElts))
3342           return false;
3343       } else {
3344         if (!isUndefOrEqual(BitI1, j + NumElts))
3345           return false;
3346       }
3347     }
3348     // Process the next 128 bits.
3349     Start += NumLaneElts;
3350     End += NumLaneElts;
3351   }
3352
3353   return true;
3354 }
3355
3356 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3357   SmallVector<int, 8> M;
3358   N->getMask(M);
3359   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3360 }
3361
3362 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3363 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3364 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3365                          bool V2IsSplat = false) {
3366   int NumElts = VT.getVectorNumElements();
3367
3368   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3369          "Unsupported vector type for unpckh");
3370
3371   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3372     return false;
3373
3374   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3375   // independently on 128-bit lanes.
3376   unsigned NumLanes = VT.getSizeInBits()/128;
3377   unsigned NumLaneElts = NumElts/NumLanes;
3378
3379   unsigned Start = 0;
3380   unsigned End = NumLaneElts;
3381   for (unsigned l = 0; l != NumLanes; ++l) {
3382     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3383                              i != End; i += 2, ++j) {
3384       int BitI  = Mask[i];
3385       int BitI1 = Mask[i+1];
3386       if (!isUndefOrEqual(BitI, j))
3387         return false;
3388       if (V2IsSplat) {
3389         if (isUndefOrEqual(BitI1, NumElts))
3390           return false;
3391       } else {
3392         if (!isUndefOrEqual(BitI1, j+NumElts))
3393           return false;
3394       }
3395     }
3396     // Process the next 128 bits.
3397     Start += NumLaneElts;
3398     End += NumLaneElts;
3399   }
3400   return true;
3401 }
3402
3403 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3404   SmallVector<int, 8> M;
3405   N->getMask(M);
3406   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3407 }
3408
3409 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3410 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3411 /// <0, 0, 1, 1>
3412 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3413   int NumElems = VT.getVectorNumElements();
3414   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3415     return false;
3416
3417   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3418   // independently on 128-bit lanes.
3419   unsigned NumLanes = VT.getSizeInBits() / 128;
3420   unsigned NumLaneElts = NumElems / NumLanes;
3421
3422   for (unsigned s = 0; s < NumLanes; ++s) {
3423     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3424          i != NumLaneElts * (s + 1);
3425          i += 2, ++j) {
3426       int BitI  = Mask[i];
3427       int BitI1 = Mask[i+1];
3428
3429       if (!isUndefOrEqual(BitI, j))
3430         return false;
3431       if (!isUndefOrEqual(BitI1, j))
3432         return false;
3433     }
3434   }
3435
3436   return true;
3437 }
3438
3439 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3440   SmallVector<int, 8> M;
3441   N->getMask(M);
3442   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3443 }
3444
3445 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3446 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3447 /// <2, 2, 3, 3>
3448 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3449   int NumElems = VT.getVectorNumElements();
3450   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3451     return false;
3452
3453   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3454     int BitI  = Mask[i];
3455     int BitI1 = Mask[i+1];
3456     if (!isUndefOrEqual(BitI, j))
3457       return false;
3458     if (!isUndefOrEqual(BitI1, j))
3459       return false;
3460   }
3461   return true;
3462 }
3463
3464 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3465   SmallVector<int, 8> M;
3466   N->getMask(M);
3467   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3468 }
3469
3470 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3471 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3472 /// MOVSD, and MOVD, i.e. setting the lowest element.
3473 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3474   if (VT.getVectorElementType().getSizeInBits() < 32)
3475     return false;
3476
3477   int NumElts = VT.getVectorNumElements();
3478
3479   if (!isUndefOrEqual(Mask[0], NumElts))
3480     return false;
3481
3482   for (int i = 1; i < NumElts; ++i)
3483     if (!isUndefOrEqual(Mask[i], i))
3484       return false;
3485
3486   return true;
3487 }
3488
3489 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3490   SmallVector<int, 8> M;
3491   N->getMask(M);
3492   return ::isMOVLMask(M, N->getValueType(0));
3493 }
3494
3495 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3496 /// as permutations between 128-bit chunks or halves. As an example: this
3497 /// shuffle bellow:
3498 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3499 /// The first half comes from the second half of V1 and the second half from the
3500 /// the second half of V2.
3501 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3502                              const X86Subtarget *Subtarget) {
3503   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3504     return false;
3505
3506   // The shuffle result is divided into half A and half B. In total the two
3507   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3508   // B must come from C, D, E or F.
3509   int HalfSize = VT.getVectorNumElements()/2;
3510   bool MatchA = false, MatchB = false;
3511
3512   // Check if A comes from one of C, D, E, F.
3513   for (int Half = 0; Half < 4; ++Half) {
3514     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3515       MatchA = true;
3516       break;
3517     }
3518   }
3519
3520   // Check if B comes from one of C, D, E, F.
3521   for (int Half = 0; Half < 4; ++Half) {
3522     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3523       MatchB = true;
3524       break;
3525     }
3526   }
3527
3528   return MatchA && MatchB;
3529 }
3530
3531 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3532 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3533 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3534   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3535   EVT VT = SVOp->getValueType(0);
3536
3537   int HalfSize = VT.getVectorNumElements()/2;
3538
3539   int FstHalf = 0, SndHalf = 0;
3540   for (int i = 0; i < HalfSize; ++i) {
3541     if (SVOp->getMaskElt(i) > 0) {
3542       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3543       break;
3544     }
3545   }
3546   for (int i = HalfSize; i < HalfSize*2; ++i) {
3547     if (SVOp->getMaskElt(i) > 0) {
3548       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3549       break;
3550     }
3551   }
3552
3553   return (FstHalf | (SndHalf << 4));
3554 }
3555
3556 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3557 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3558 /// Note that VPERMIL mask matching is different depending whether theunderlying
3559 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3560 /// to the same elements of the low, but to the higher half of the source.
3561 /// In VPERMILPD the two lanes could be shuffled independently of each other
3562 /// with the same restriction that lanes can't be crossed.
3563 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3564                             const X86Subtarget *Subtarget) {
3565   int NumElts = VT.getVectorNumElements();
3566   int NumLanes = VT.getSizeInBits()/128;
3567
3568   if (!Subtarget->hasAVX())
3569     return false;
3570
3571   // Match any permutation of 128-bit vector with 64-bit types
3572   if (NumLanes == 1 && NumElts != 2)
3573     return false;
3574
3575   // Only match 256-bit with 32 types
3576   if (VT.getSizeInBits() == 256 && NumElts != 4)
3577     return false;
3578
3579   // The mask on the high lane is independent of the low. Both can match
3580   // any element in inside its own lane, but can't cross.
3581   int LaneSize = NumElts/NumLanes;
3582   for (int l = 0; l < NumLanes; ++l)
3583     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3584       int LaneStart = l*LaneSize;
3585       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3586         return false;
3587     }
3588
3589   return true;
3590 }
3591
3592 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3593 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3594 /// Note that VPERMIL mask matching is different depending whether theunderlying
3595 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3596 /// to the same elements of the low, but to the higher half of the source.
3597 /// In VPERMILPD the two lanes could be shuffled independently of each other
3598 /// with the same restriction that lanes can't be crossed.
3599 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3600                             const X86Subtarget *Subtarget) {
3601   unsigned NumElts = VT.getVectorNumElements();
3602   unsigned NumLanes = VT.getSizeInBits()/128;
3603
3604   if (!Subtarget->hasAVX())
3605     return false;
3606
3607   // Match any permutation of 128-bit vector with 32-bit types
3608   if (NumLanes == 1 && NumElts != 4)
3609     return false;
3610
3611   // Only match 256-bit with 32 types
3612   if (VT.getSizeInBits() == 256 && NumElts != 8)
3613     return false;
3614
3615   // The mask on the high lane should be the same as the low. Actually,
3616   // they can differ if any of the corresponding index in a lane is undef
3617   // and the other stays in range.
3618   int LaneSize = NumElts/NumLanes;
3619   for (int i = 0; i < LaneSize; ++i) {
3620     int HighElt = i+LaneSize;
3621     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3622     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3623
3624     if (!HighValid || !LowValid)
3625       return false;
3626     if (Mask[i] < 0 || Mask[HighElt] < 0)
3627       continue;
3628     if (Mask[HighElt]-Mask[i] != LaneSize)
3629       return false;
3630   }
3631
3632   return true;
3633 }
3634
3635 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3636 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3637 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3639   EVT VT = SVOp->getValueType(0);
3640
3641   int NumElts = VT.getVectorNumElements();
3642   int NumLanes = VT.getSizeInBits()/128;
3643   int LaneSize = NumElts/NumLanes;
3644
3645   // Although the mask is equal for both lanes do it twice to get the cases
3646   // where a mask will match because the same mask element is undef on the
3647   // first half but valid on the second. This would get pathological cases
3648   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3649   unsigned Mask = 0;
3650   for (int l = 0; l < NumLanes; ++l) {
3651     for (int i = 0; i < LaneSize; ++i) {
3652       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3653       if (MaskElt < 0)
3654         continue;
3655       if (MaskElt >= LaneSize)
3656         MaskElt -= LaneSize;
3657       Mask |= MaskElt << (i*2);
3658     }
3659   }
3660
3661   return Mask;
3662 }
3663
3664 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3665 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3666 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3667   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3668   EVT VT = SVOp->getValueType(0);
3669
3670   int NumElts = VT.getVectorNumElements();
3671   int NumLanes = VT.getSizeInBits()/128;
3672
3673   unsigned Mask = 0;
3674   int LaneSize = NumElts/NumLanes;
3675   for (int l = 0; l < NumLanes; ++l)
3676     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3677       int MaskElt = SVOp->getMaskElt(i);
3678       if (MaskElt < 0)
3679         continue;
3680       Mask |= (MaskElt-l*LaneSize) << i;
3681     }
3682
3683   return Mask;
3684 }
3685
3686 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3687 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3688 /// element of vector 2 and the other elements to come from vector 1 in order.
3689 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3690                                bool V2IsSplat = false, bool V2IsUndef = false) {
3691   int NumOps = VT.getVectorNumElements();
3692   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3693     return false;
3694
3695   if (!isUndefOrEqual(Mask[0], 0))
3696     return false;
3697
3698   for (int i = 1; i < NumOps; ++i)
3699     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3700           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3701           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3702       return false;
3703
3704   return true;
3705 }
3706
3707 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3708                            bool V2IsUndef = false) {
3709   SmallVector<int, 8> M;
3710   N->getMask(M);
3711   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3712 }
3713
3714 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3715 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3716 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3717 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3718                          const X86Subtarget *Subtarget) {
3719   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3720     return false;
3721
3722   // The second vector must be undef
3723   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3724     return false;
3725
3726   EVT VT = N->getValueType(0);
3727   unsigned NumElems = VT.getVectorNumElements();
3728
3729   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3730       (VT.getSizeInBits() == 256 && NumElems != 8))
3731     return false;
3732
3733   // "i+1" is the value the indexed mask element must have
3734   for (unsigned i = 0; i < NumElems; i += 2)
3735     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3736         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3737       return false;
3738
3739   return true;
3740 }
3741
3742 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3743 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3744 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3745 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3746                          const X86Subtarget *Subtarget) {
3747   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3748     return false;
3749
3750   // The second vector must be undef
3751   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3752     return false;
3753
3754   EVT VT = N->getValueType(0);
3755   unsigned NumElems = VT.getVectorNumElements();
3756
3757   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3758       (VT.getSizeInBits() == 256 && NumElems != 8))
3759     return false;
3760
3761   // "i" is the value the indexed mask element must have
3762   for (unsigned i = 0; i < NumElems; i += 2)
3763     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3764         !isUndefOrEqual(N->getMaskElt(i+1), i))
3765       return false;
3766
3767   return true;
3768 }
3769
3770 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3771 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3772 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3773   int e = N->getValueType(0).getVectorNumElements() / 2;
3774
3775   for (int i = 0; i < e; ++i)
3776     if (!isUndefOrEqual(N->getMaskElt(i), i))
3777       return false;
3778   for (int i = 0; i < e; ++i)
3779     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3780       return false;
3781   return true;
3782 }
3783
3784 /// isVEXTRACTF128Index - Return true if the specified
3785 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3786 /// suitable for input to VEXTRACTF128.
3787 bool X86::isVEXTRACTF128Index(SDNode *N) {
3788   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3789     return false;
3790
3791   // The index should be aligned on a 128-bit boundary.
3792   uint64_t Index =
3793     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3794
3795   unsigned VL = N->getValueType(0).getVectorNumElements();
3796   unsigned VBits = N->getValueType(0).getSizeInBits();
3797   unsigned ElSize = VBits / VL;
3798   bool Result = (Index * ElSize) % 128 == 0;
3799
3800   return Result;
3801 }
3802
3803 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3804 /// operand specifies a subvector insert that is suitable for input to
3805 /// VINSERTF128.
3806 bool X86::isVINSERTF128Index(SDNode *N) {
3807   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3808     return false;
3809
3810   // The index should be aligned on a 128-bit boundary.
3811   uint64_t Index =
3812     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3813
3814   unsigned VL = N->getValueType(0).getVectorNumElements();
3815   unsigned VBits = N->getValueType(0).getSizeInBits();
3816   unsigned ElSize = VBits / VL;
3817   bool Result = (Index * ElSize) % 128 == 0;
3818
3819   return Result;
3820 }
3821
3822 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3823 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3824 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3825   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3826   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3827
3828   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3829   unsigned Mask = 0;
3830   for (int i = 0; i < NumOperands; ++i) {
3831     int Val = SVOp->getMaskElt(NumOperands-i-1);
3832     if (Val < 0) Val = 0;
3833     if (Val >= NumOperands) Val -= NumOperands;
3834     Mask |= Val;
3835     if (i != NumOperands - 1)
3836       Mask <<= Shift;
3837   }
3838   return Mask;
3839 }
3840
3841 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3842 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3843 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3844   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3845   unsigned Mask = 0;
3846   // 8 nodes, but we only care about the last 4.
3847   for (unsigned i = 7; i >= 4; --i) {
3848     int Val = SVOp->getMaskElt(i);
3849     if (Val >= 0)
3850       Mask |= (Val - 4);
3851     if (i != 4)
3852       Mask <<= 2;
3853   }
3854   return Mask;
3855 }
3856
3857 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3858 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3859 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3861   unsigned Mask = 0;
3862   // 8 nodes, but we only care about the first 4.
3863   for (int i = 3; i >= 0; --i) {
3864     int Val = SVOp->getMaskElt(i);
3865     if (Val >= 0)
3866       Mask |= Val;
3867     if (i != 0)
3868       Mask <<= 2;
3869   }
3870   return Mask;
3871 }
3872
3873 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3874 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3875 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3876   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3877   EVT VVT = N->getValueType(0);
3878   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3879   int Val = 0;
3880
3881   unsigned i, e;
3882   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3883     Val = SVOp->getMaskElt(i);
3884     if (Val >= 0)
3885       break;
3886   }
3887   assert(Val - i > 0 && "PALIGNR imm should be positive");
3888   return (Val - i) * EltSize;
3889 }
3890
3891 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3892 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3893 /// instructions.
3894 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3895   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3896     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3897
3898   uint64_t Index =
3899     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3900
3901   EVT VecVT = N->getOperand(0).getValueType();
3902   EVT ElVT = VecVT.getVectorElementType();
3903
3904   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3905   return Index / NumElemsPerChunk;
3906 }
3907
3908 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3909 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3910 /// instructions.
3911 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3912   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3913     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3914
3915   uint64_t Index =
3916     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3917
3918   EVT VecVT = N->getValueType(0);
3919   EVT ElVT = VecVT.getVectorElementType();
3920
3921   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3922   return Index / NumElemsPerChunk;
3923 }
3924
3925 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3926 /// constant +0.0.
3927 bool X86::isZeroNode(SDValue Elt) {
3928   return ((isa<ConstantSDNode>(Elt) &&
3929            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3930           (isa<ConstantFPSDNode>(Elt) &&
3931            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3932 }
3933
3934 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3935 /// their permute mask.
3936 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3937                                     SelectionDAG &DAG) {
3938   EVT VT = SVOp->getValueType(0);
3939   unsigned NumElems = VT.getVectorNumElements();
3940   SmallVector<int, 8> MaskVec;
3941
3942   for (unsigned i = 0; i != NumElems; ++i) {
3943     int idx = SVOp->getMaskElt(i);
3944     if (idx < 0)
3945       MaskVec.push_back(idx);
3946     else if (idx < (int)NumElems)
3947       MaskVec.push_back(idx + NumElems);
3948     else
3949       MaskVec.push_back(idx - NumElems);
3950   }
3951   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3952                               SVOp->getOperand(0), &MaskVec[0]);
3953 }
3954
3955 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3956 /// the two vector operands have swapped position.
3957 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3958   unsigned NumElems = VT.getVectorNumElements();
3959   for (unsigned i = 0; i != NumElems; ++i) {
3960     int idx = Mask[i];
3961     if (idx < 0)
3962       continue;
3963     else if (idx < (int)NumElems)
3964       Mask[i] = idx + NumElems;
3965     else
3966       Mask[i] = idx - NumElems;
3967   }
3968 }
3969
3970 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3971 /// match movhlps. The lower half elements should come from upper half of
3972 /// V1 (and in order), and the upper half elements should come from the upper
3973 /// half of V2 (and in order).
3974 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3975   EVT VT = Op->getValueType(0);
3976   if (VT.getSizeInBits() != 128)
3977     return false;
3978   if (VT.getVectorNumElements() != 4)
3979     return false;
3980   for (unsigned i = 0, e = 2; i != e; ++i)
3981     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3982       return false;
3983   for (unsigned i = 2; i != 4; ++i)
3984     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3985       return false;
3986   return true;
3987 }
3988
3989 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3990 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3991 /// required.
3992 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3993   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3994     return false;
3995   N = N->getOperand(0).getNode();
3996   if (!ISD::isNON_EXTLoad(N))
3997     return false;
3998   if (LD)
3999     *LD = cast<LoadSDNode>(N);
4000   return true;
4001 }
4002
4003 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4004 /// match movlp{s|d}. The lower half elements should come from lower half of
4005 /// V1 (and in order), and the upper half elements should come from the upper
4006 /// half of V2 (and in order). And since V1 will become the source of the
4007 /// MOVLP, it must be either a vector load or a scalar load to vector.
4008 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4009                                ShuffleVectorSDNode *Op) {
4010   EVT VT = Op->getValueType(0);
4011   if (VT.getSizeInBits() != 128)
4012     return false;
4013
4014   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4015     return false;
4016   // Is V2 is a vector load, don't do this transformation. We will try to use
4017   // load folding shufps op.
4018   if (ISD::isNON_EXTLoad(V2))
4019     return false;
4020
4021   unsigned NumElems = VT.getVectorNumElements();
4022
4023   if (NumElems != 2 && NumElems != 4)
4024     return false;
4025   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4026     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4027       return false;
4028   for (unsigned i = NumElems/2; i != NumElems; ++i)
4029     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4030       return false;
4031   return true;
4032 }
4033
4034 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4035 /// all the same.
4036 static bool isSplatVector(SDNode *N) {
4037   if (N->getOpcode() != ISD::BUILD_VECTOR)
4038     return false;
4039
4040   SDValue SplatValue = N->getOperand(0);
4041   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4042     if (N->getOperand(i) != SplatValue)
4043       return false;
4044   return true;
4045 }
4046
4047 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4048 /// to an zero vector.
4049 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4050 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4051   SDValue V1 = N->getOperand(0);
4052   SDValue V2 = N->getOperand(1);
4053   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4054   for (unsigned i = 0; i != NumElems; ++i) {
4055     int Idx = N->getMaskElt(i);
4056     if (Idx >= (int)NumElems) {
4057       unsigned Opc = V2.getOpcode();
4058       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4059         continue;
4060       if (Opc != ISD::BUILD_VECTOR ||
4061           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4062         return false;
4063     } else if (Idx >= 0) {
4064       unsigned Opc = V1.getOpcode();
4065       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4066         continue;
4067       if (Opc != ISD::BUILD_VECTOR ||
4068           !X86::isZeroNode(V1.getOperand(Idx)))
4069         return false;
4070     }
4071   }
4072   return true;
4073 }
4074
4075 /// getZeroVector - Returns a vector of specified type with all zero elements.
4076 ///
4077 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
4078                              DebugLoc dl) {
4079   assert(VT.isVector() && "Expected a vector type");
4080
4081   // Always build SSE zero vectors as <4 x i32> bitcasted
4082   // to their dest type. This ensures they get CSE'd.
4083   SDValue Vec;
4084   if (VT.getSizeInBits() == 128) {  // SSE
4085     if (HasSSE2) {  // SSE2
4086       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4087       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4088     } else { // SSE1
4089       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4090       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4091     }
4092   } else if (VT.getSizeInBits() == 256) { // AVX
4093     // 256-bit logic and arithmetic instructions in AVX are
4094     // all floating-point, no support for integer ops. Default
4095     // to emitting fp zeroed vectors then.
4096     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4097     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4098     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4099   }
4100   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4101 }
4102
4103 /// getOnesVector - Returns a vector of specified type with all bits set.
4104 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4105 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4106 /// original type, ensuring they get CSE'd.
4107 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4108   assert(VT.isVector() && "Expected a vector type");
4109   assert((VT.is128BitVector() || VT.is256BitVector())
4110          && "Expected a 128-bit or 256-bit vector type");
4111
4112   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4113   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4114                             Cst, Cst, Cst, Cst);
4115
4116   if (VT.is256BitVector()) {
4117     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4118                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4119     Vec = Insert128BitVector(InsV, Vec,
4120                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4121   }
4122
4123   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4124 }
4125
4126 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4127 /// that point to V2 points to its first element.
4128 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4129   EVT VT = SVOp->getValueType(0);
4130   unsigned NumElems = VT.getVectorNumElements();
4131
4132   bool Changed = false;
4133   SmallVector<int, 8> MaskVec;
4134   SVOp->getMask(MaskVec);
4135
4136   for (unsigned i = 0; i != NumElems; ++i) {
4137     if (MaskVec[i] > (int)NumElems) {
4138       MaskVec[i] = NumElems;
4139       Changed = true;
4140     }
4141   }
4142   if (Changed)
4143     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4144                                 SVOp->getOperand(1), &MaskVec[0]);
4145   return SDValue(SVOp, 0);
4146 }
4147
4148 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4149 /// operation of specified width.
4150 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4151                        SDValue V2) {
4152   unsigned NumElems = VT.getVectorNumElements();
4153   SmallVector<int, 8> Mask;
4154   Mask.push_back(NumElems);
4155   for (unsigned i = 1; i != NumElems; ++i)
4156     Mask.push_back(i);
4157   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4158 }
4159
4160 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4161 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4162                           SDValue V2) {
4163   unsigned NumElems = VT.getVectorNumElements();
4164   SmallVector<int, 8> Mask;
4165   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4166     Mask.push_back(i);
4167     Mask.push_back(i + NumElems);
4168   }
4169   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4170 }
4171
4172 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4173 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4174                           SDValue V2) {
4175   unsigned NumElems = VT.getVectorNumElements();
4176   unsigned Half = NumElems/2;
4177   SmallVector<int, 8> Mask;
4178   for (unsigned i = 0; i != Half; ++i) {
4179     Mask.push_back(i + Half);
4180     Mask.push_back(i + NumElems + Half);
4181   }
4182   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4183 }
4184
4185 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4186 // a generic shuffle instruction because the target has no such instructions.
4187 // Generate shuffles which repeat i16 and i8 several times until they can be
4188 // represented by v4f32 and then be manipulated by target suported shuffles.
4189 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4190   EVT VT = V.getValueType();
4191   int NumElems = VT.getVectorNumElements();
4192   DebugLoc dl = V.getDebugLoc();
4193
4194   while (NumElems > 4) {
4195     if (EltNo < NumElems/2) {
4196       V = getUnpackl(DAG, dl, VT, V, V);
4197     } else {
4198       V = getUnpackh(DAG, dl, VT, V, V);
4199       EltNo -= NumElems/2;
4200     }
4201     NumElems >>= 1;
4202   }
4203   return V;
4204 }
4205
4206 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4207 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4208   EVT VT = V.getValueType();
4209   DebugLoc dl = V.getDebugLoc();
4210   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4211          && "Vector size not supported");
4212
4213   if (VT.getSizeInBits() == 128) {
4214     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4215     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4216     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4217                              &SplatMask[0]);
4218   } else {
4219     // To use VPERMILPS to splat scalars, the second half of indicies must
4220     // refer to the higher part, which is a duplication of the lower one,
4221     // because VPERMILPS can only handle in-lane permutations.
4222     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4223                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4224
4225     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4226     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4227                              &SplatMask[0]);
4228   }
4229
4230   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4231 }
4232
4233 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4234 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4235   EVT SrcVT = SV->getValueType(0);
4236   SDValue V1 = SV->getOperand(0);
4237   DebugLoc dl = SV->getDebugLoc();
4238
4239   int EltNo = SV->getSplatIndex();
4240   int NumElems = SrcVT.getVectorNumElements();
4241   unsigned Size = SrcVT.getSizeInBits();
4242
4243   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4244           "Unknown how to promote splat for type");
4245
4246   // Extract the 128-bit part containing the splat element and update
4247   // the splat element index when it refers to the higher register.
4248   if (Size == 256) {
4249     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4250     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4251     if (Idx > 0)
4252       EltNo -= NumElems/2;
4253   }
4254
4255   // All i16 and i8 vector types can't be used directly by a generic shuffle
4256   // instruction because the target has no such instruction. Generate shuffles
4257   // which repeat i16 and i8 several times until they fit in i32, and then can
4258   // be manipulated by target suported shuffles.
4259   EVT EltVT = SrcVT.getVectorElementType();
4260   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4261     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4262
4263   // Recreate the 256-bit vector and place the same 128-bit vector
4264   // into the low and high part. This is necessary because we want
4265   // to use VPERM* to shuffle the vectors
4266   if (Size == 256) {
4267     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4268                          DAG.getConstant(0, MVT::i32), DAG, dl);
4269     V1 = Insert128BitVector(InsV, V1,
4270                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4271   }
4272
4273   return getLegalSplat(DAG, V1, EltNo);
4274 }
4275
4276 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4277 /// vector of zero or undef vector.  This produces a shuffle where the low
4278 /// element of V2 is swizzled into the zero/undef vector, landing at element
4279 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4280 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4281                                              bool isZero, bool HasSSE2,
4282                                              SelectionDAG &DAG) {
4283   EVT VT = V2.getValueType();
4284   SDValue V1 = isZero
4285     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4286   unsigned NumElems = VT.getVectorNumElements();
4287   SmallVector<int, 16> MaskVec;
4288   for (unsigned i = 0; i != NumElems; ++i)
4289     // If this is the insertion idx, put the low elt of V2 here.
4290     MaskVec.push_back(i == Idx ? NumElems : i);
4291   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4292 }
4293
4294 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4295 /// element of the result of the vector shuffle.
4296 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4297                                    unsigned Depth) {
4298   if (Depth == 6)
4299     return SDValue();  // Limit search depth.
4300
4301   SDValue V = SDValue(N, 0);
4302   EVT VT = V.getValueType();
4303   unsigned Opcode = V.getOpcode();
4304
4305   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4306   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4307     Index = SV->getMaskElt(Index);
4308
4309     if (Index < 0)
4310       return DAG.getUNDEF(VT.getVectorElementType());
4311
4312     int NumElems = VT.getVectorNumElements();
4313     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4314     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4315   }
4316
4317   // Recurse into target specific vector shuffles to find scalars.
4318   if (isTargetShuffle(Opcode)) {
4319     int NumElems = VT.getVectorNumElements();
4320     SmallVector<unsigned, 16> ShuffleMask;
4321     SDValue ImmN;
4322
4323     switch(Opcode) {
4324     case X86ISD::SHUFPS:
4325     case X86ISD::SHUFPD:
4326       ImmN = N->getOperand(N->getNumOperands()-1);
4327       DecodeSHUFPSMask(NumElems,
4328                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4329                        ShuffleMask);
4330       break;
4331     case X86ISD::PUNPCKHBW:
4332     case X86ISD::PUNPCKHWD:
4333     case X86ISD::PUNPCKHDQ:
4334     case X86ISD::PUNPCKHQDQ:
4335       DecodePUNPCKHMask(NumElems, ShuffleMask);
4336       break;
4337     case X86ISD::UNPCKHPS:
4338     case X86ISD::UNPCKHPD:
4339     case X86ISD::VUNPCKHPSY:
4340     case X86ISD::VUNPCKHPDY:
4341       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4342       break;
4343     case X86ISD::PUNPCKLBW:
4344     case X86ISD::PUNPCKLWD:
4345     case X86ISD::PUNPCKLDQ:
4346     case X86ISD::PUNPCKLQDQ:
4347       DecodePUNPCKLMask(VT, ShuffleMask);
4348       break;
4349     case X86ISD::UNPCKLPS:
4350     case X86ISD::UNPCKLPD:
4351     case X86ISD::VUNPCKLPSY:
4352     case X86ISD::VUNPCKLPDY:
4353       DecodeUNPCKLPMask(VT, ShuffleMask);
4354       break;
4355     case X86ISD::MOVHLPS:
4356       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4357       break;
4358     case X86ISD::MOVLHPS:
4359       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4360       break;
4361     case X86ISD::PSHUFD:
4362       ImmN = N->getOperand(N->getNumOperands()-1);
4363       DecodePSHUFMask(NumElems,
4364                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4365                       ShuffleMask);
4366       break;
4367     case X86ISD::PSHUFHW:
4368       ImmN = N->getOperand(N->getNumOperands()-1);
4369       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4370                         ShuffleMask);
4371       break;
4372     case X86ISD::PSHUFLW:
4373       ImmN = N->getOperand(N->getNumOperands()-1);
4374       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4375                         ShuffleMask);
4376       break;
4377     case X86ISD::MOVSS:
4378     case X86ISD::MOVSD: {
4379       // The index 0 always comes from the first element of the second source,
4380       // this is why MOVSS and MOVSD are used in the first place. The other
4381       // elements come from the other positions of the first source vector.
4382       unsigned OpNum = (Index == 0) ? 1 : 0;
4383       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4384                                  Depth+1);
4385     }
4386     case X86ISD::VPERMILPS:
4387       ImmN = N->getOperand(N->getNumOperands()-1);
4388       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4389                         ShuffleMask);
4390       break;
4391     case X86ISD::VPERMILPSY:
4392       ImmN = N->getOperand(N->getNumOperands()-1);
4393       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4394                         ShuffleMask);
4395       break;
4396     case X86ISD::VPERMILPD:
4397       ImmN = N->getOperand(N->getNumOperands()-1);
4398       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4399                         ShuffleMask);
4400       break;
4401     case X86ISD::VPERMILPDY:
4402       ImmN = N->getOperand(N->getNumOperands()-1);
4403       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4404                         ShuffleMask);
4405       break;
4406     case X86ISD::VPERM2F128:
4407       ImmN = N->getOperand(N->getNumOperands()-1);
4408       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4409                            ShuffleMask);
4410       break;
4411     default:
4412       assert("not implemented for target shuffle node");
4413       return SDValue();
4414     }
4415
4416     Index = ShuffleMask[Index];
4417     if (Index < 0)
4418       return DAG.getUNDEF(VT.getVectorElementType());
4419
4420     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4421     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4422                                Depth+1);
4423   }
4424
4425   // Actual nodes that may contain scalar elements
4426   if (Opcode == ISD::BITCAST) {
4427     V = V.getOperand(0);
4428     EVT SrcVT = V.getValueType();
4429     unsigned NumElems = VT.getVectorNumElements();
4430
4431     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4432       return SDValue();
4433   }
4434
4435   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4436     return (Index == 0) ? V.getOperand(0)
4437                           : DAG.getUNDEF(VT.getVectorElementType());
4438
4439   if (V.getOpcode() == ISD::BUILD_VECTOR)
4440     return V.getOperand(Index);
4441
4442   return SDValue();
4443 }
4444
4445 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4446 /// shuffle operation which come from a consecutively from a zero. The
4447 /// search can start in two different directions, from left or right.
4448 static
4449 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4450                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4451   int i = 0;
4452
4453   while (i < NumElems) {
4454     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4455     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4456     if (!(Elt.getNode() &&
4457          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4458       break;
4459     ++i;
4460   }
4461
4462   return i;
4463 }
4464
4465 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4466 /// MaskE correspond consecutively to elements from one of the vector operands,
4467 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4468 static
4469 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4470                               int OpIdx, int NumElems, unsigned &OpNum) {
4471   bool SeenV1 = false;
4472   bool SeenV2 = false;
4473
4474   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4475     int Idx = SVOp->getMaskElt(i);
4476     // Ignore undef indicies
4477     if (Idx < 0)
4478       continue;
4479
4480     if (Idx < NumElems)
4481       SeenV1 = true;
4482     else
4483       SeenV2 = true;
4484
4485     // Only accept consecutive elements from the same vector
4486     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4487       return false;
4488   }
4489
4490   OpNum = SeenV1 ? 0 : 1;
4491   return true;
4492 }
4493
4494 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4495 /// logical left shift of a vector.
4496 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4497                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4498   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4499   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4500               false /* check zeros from right */, DAG);
4501   unsigned OpSrc;
4502
4503   if (!NumZeros)
4504     return false;
4505
4506   // Considering the elements in the mask that are not consecutive zeros,
4507   // check if they consecutively come from only one of the source vectors.
4508   //
4509   //               V1 = {X, A, B, C}     0
4510   //                         \  \  \    /
4511   //   vector_shuffle V1, V2 <1, 2, 3, X>
4512   //
4513   if (!isShuffleMaskConsecutive(SVOp,
4514             0,                   // Mask Start Index
4515             NumElems-NumZeros-1, // Mask End Index
4516             NumZeros,            // Where to start looking in the src vector
4517             NumElems,            // Number of elements in vector
4518             OpSrc))              // Which source operand ?
4519     return false;
4520
4521   isLeft = false;
4522   ShAmt = NumZeros;
4523   ShVal = SVOp->getOperand(OpSrc);
4524   return true;
4525 }
4526
4527 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4528 /// logical left shift of a vector.
4529 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4530                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4531   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4532   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4533               true /* check zeros from left */, DAG);
4534   unsigned OpSrc;
4535
4536   if (!NumZeros)
4537     return false;
4538
4539   // Considering the elements in the mask that are not consecutive zeros,
4540   // check if they consecutively come from only one of the source vectors.
4541   //
4542   //                           0    { A, B, X, X } = V2
4543   //                          / \    /  /
4544   //   vector_shuffle V1, V2 <X, X, 4, 5>
4545   //
4546   if (!isShuffleMaskConsecutive(SVOp,
4547             NumZeros,     // Mask Start Index
4548             NumElems-1,   // Mask End Index
4549             0,            // Where to start looking in the src vector
4550             NumElems,     // Number of elements in vector
4551             OpSrc))       // Which source operand ?
4552     return false;
4553
4554   isLeft = true;
4555   ShAmt = NumZeros;
4556   ShVal = SVOp->getOperand(OpSrc);
4557   return true;
4558 }
4559
4560 /// isVectorShift - Returns true if the shuffle can be implemented as a
4561 /// logical left or right shift of a vector.
4562 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4563                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4564   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4565       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4566     return true;
4567
4568   return false;
4569 }
4570
4571 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4572 ///
4573 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4574                                        unsigned NumNonZero, unsigned NumZero,
4575                                        SelectionDAG &DAG,
4576                                        const TargetLowering &TLI) {
4577   if (NumNonZero > 8)
4578     return SDValue();
4579
4580   DebugLoc dl = Op.getDebugLoc();
4581   SDValue V(0, 0);
4582   bool First = true;
4583   for (unsigned i = 0; i < 16; ++i) {
4584     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4585     if (ThisIsNonZero && First) {
4586       if (NumZero)
4587         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4588       else
4589         V = DAG.getUNDEF(MVT::v8i16);
4590       First = false;
4591     }
4592
4593     if ((i & 1) != 0) {
4594       SDValue ThisElt(0, 0), LastElt(0, 0);
4595       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4596       if (LastIsNonZero) {
4597         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4598                               MVT::i16, Op.getOperand(i-1));
4599       }
4600       if (ThisIsNonZero) {
4601         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4602         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4603                               ThisElt, DAG.getConstant(8, MVT::i8));
4604         if (LastIsNonZero)
4605           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4606       } else
4607         ThisElt = LastElt;
4608
4609       if (ThisElt.getNode())
4610         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4611                         DAG.getIntPtrConstant(i/2));
4612     }
4613   }
4614
4615   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4616 }
4617
4618 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4619 ///
4620 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4621                                      unsigned NumNonZero, unsigned NumZero,
4622                                      SelectionDAG &DAG,
4623                                      const TargetLowering &TLI) {
4624   if (NumNonZero > 4)
4625     return SDValue();
4626
4627   DebugLoc dl = Op.getDebugLoc();
4628   SDValue V(0, 0);
4629   bool First = true;
4630   for (unsigned i = 0; i < 8; ++i) {
4631     bool isNonZero = (NonZeros & (1 << i)) != 0;
4632     if (isNonZero) {
4633       if (First) {
4634         if (NumZero)
4635           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4636         else
4637           V = DAG.getUNDEF(MVT::v8i16);
4638         First = false;
4639       }
4640       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4641                       MVT::v8i16, V, Op.getOperand(i),
4642                       DAG.getIntPtrConstant(i));
4643     }
4644   }
4645
4646   return V;
4647 }
4648
4649 /// getVShift - Return a vector logical shift node.
4650 ///
4651 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4652                          unsigned NumBits, SelectionDAG &DAG,
4653                          const TargetLowering &TLI, DebugLoc dl) {
4654   EVT ShVT = MVT::v2i64;
4655   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4656   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4657   return DAG.getNode(ISD::BITCAST, dl, VT,
4658                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4659                              DAG.getConstant(NumBits,
4660                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4661 }
4662
4663 SDValue
4664 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4665                                           SelectionDAG &DAG) const {
4666
4667   // Check if the scalar load can be widened into a vector load. And if
4668   // the address is "base + cst" see if the cst can be "absorbed" into
4669   // the shuffle mask.
4670   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4671     SDValue Ptr = LD->getBasePtr();
4672     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4673       return SDValue();
4674     EVT PVT = LD->getValueType(0);
4675     if (PVT != MVT::i32 && PVT != MVT::f32)
4676       return SDValue();
4677
4678     int FI = -1;
4679     int64_t Offset = 0;
4680     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4681       FI = FINode->getIndex();
4682       Offset = 0;
4683     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4684                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4685       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4686       Offset = Ptr.getConstantOperandVal(1);
4687       Ptr = Ptr.getOperand(0);
4688     } else {
4689       return SDValue();
4690     }
4691
4692     // FIXME: 256-bit vector instructions don't require a strict alignment,
4693     // improve this code to support it better.
4694     unsigned RequiredAlign = VT.getSizeInBits()/8;
4695     SDValue Chain = LD->getChain();
4696     // Make sure the stack object alignment is at least 16 or 32.
4697     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4698     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4699       if (MFI->isFixedObjectIndex(FI)) {
4700         // Can't change the alignment. FIXME: It's possible to compute
4701         // the exact stack offset and reference FI + adjust offset instead.
4702         // If someone *really* cares about this. That's the way to implement it.
4703         return SDValue();
4704       } else {
4705         MFI->setObjectAlignment(FI, RequiredAlign);
4706       }
4707     }
4708
4709     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4710     // Ptr + (Offset & ~15).
4711     if (Offset < 0)
4712       return SDValue();
4713     if ((Offset % RequiredAlign) & 3)
4714       return SDValue();
4715     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4716     if (StartOffset)
4717       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4718                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4719
4720     int EltNo = (Offset - StartOffset) >> 2;
4721     int NumElems = VT.getVectorNumElements();
4722
4723     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4724     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4725     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4726                              LD->getPointerInfo().getWithOffset(StartOffset),
4727                              false, false, 0);
4728
4729     // Canonicalize it to a v4i32 or v8i32 shuffle.
4730     SmallVector<int, 8> Mask;
4731     for (int i = 0; i < NumElems; ++i)
4732       Mask.push_back(EltNo);
4733
4734     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4735     return DAG.getNode(ISD::BITCAST, dl, NVT,
4736                        DAG.getVectorShuffle(CanonVT, dl, V1,
4737                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4738   }
4739
4740   return SDValue();
4741 }
4742
4743 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4744 /// vector of type 'VT', see if the elements can be replaced by a single large
4745 /// load which has the same value as a build_vector whose operands are 'elts'.
4746 ///
4747 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4748 ///
4749 /// FIXME: we'd also like to handle the case where the last elements are zero
4750 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4751 /// There's even a handy isZeroNode for that purpose.
4752 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4753                                         DebugLoc &DL, SelectionDAG &DAG) {
4754   EVT EltVT = VT.getVectorElementType();
4755   unsigned NumElems = Elts.size();
4756
4757   LoadSDNode *LDBase = NULL;
4758   unsigned LastLoadedElt = -1U;
4759
4760   // For each element in the initializer, see if we've found a load or an undef.
4761   // If we don't find an initial load element, or later load elements are
4762   // non-consecutive, bail out.
4763   for (unsigned i = 0; i < NumElems; ++i) {
4764     SDValue Elt = Elts[i];
4765
4766     if (!Elt.getNode() ||
4767         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4768       return SDValue();
4769     if (!LDBase) {
4770       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4771         return SDValue();
4772       LDBase = cast<LoadSDNode>(Elt.getNode());
4773       LastLoadedElt = i;
4774       continue;
4775     }
4776     if (Elt.getOpcode() == ISD::UNDEF)
4777       continue;
4778
4779     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4780     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4781       return SDValue();
4782     LastLoadedElt = i;
4783   }
4784
4785   // If we have found an entire vector of loads and undefs, then return a large
4786   // load of the entire vector width starting at the base pointer.  If we found
4787   // consecutive loads for the low half, generate a vzext_load node.
4788   if (LastLoadedElt == NumElems - 1) {
4789     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4790       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4791                          LDBase->getPointerInfo(),
4792                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4793     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4794                        LDBase->getPointerInfo(),
4795                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4796                        LDBase->getAlignment());
4797   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4798              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4799     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4800     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4801     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4802                                               Ops, 2, MVT::i32,
4803                                               LDBase->getMemOperand());
4804     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4805   }
4806   return SDValue();
4807 }
4808
4809 SDValue
4810 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4811   DebugLoc dl = Op.getDebugLoc();
4812
4813   EVT VT = Op.getValueType();
4814   EVT ExtVT = VT.getVectorElementType();
4815   unsigned NumElems = Op.getNumOperands();
4816
4817   // Vectors containing all zeros can be matched by pxor and xorps later
4818   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
4819     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
4820     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
4821     if (Op.getValueType() == MVT::v4i32 ||
4822         Op.getValueType() == MVT::v8i32)
4823       return Op;
4824
4825     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4826   }
4827
4828   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
4829   // vectors or broken into v4i32 operations on 256-bit vectors.
4830   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
4831     if (Op.getValueType() == MVT::v4i32)
4832       return Op;
4833
4834     return getOnesVector(Op.getValueType(), DAG, dl);
4835   }
4836
4837   unsigned EVTBits = ExtVT.getSizeInBits();
4838
4839   unsigned NumZero  = 0;
4840   unsigned NumNonZero = 0;
4841   unsigned NonZeros = 0;
4842   bool IsAllConstants = true;
4843   SmallSet<SDValue, 8> Values;
4844   for (unsigned i = 0; i < NumElems; ++i) {
4845     SDValue Elt = Op.getOperand(i);
4846     if (Elt.getOpcode() == ISD::UNDEF)
4847       continue;
4848     Values.insert(Elt);
4849     if (Elt.getOpcode() != ISD::Constant &&
4850         Elt.getOpcode() != ISD::ConstantFP)
4851       IsAllConstants = false;
4852     if (X86::isZeroNode(Elt))
4853       NumZero++;
4854     else {
4855       NonZeros |= (1 << i);
4856       NumNonZero++;
4857     }
4858   }
4859
4860   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4861   if (NumNonZero == 0)
4862     return DAG.getUNDEF(VT);
4863
4864   // Special case for single non-zero, non-undef, element.
4865   if (NumNonZero == 1) {
4866     unsigned Idx = CountTrailingZeros_32(NonZeros);
4867     SDValue Item = Op.getOperand(Idx);
4868
4869     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4870     // the value are obviously zero, truncate the value to i32 and do the
4871     // insertion that way.  Only do this if the value is non-constant or if the
4872     // value is a constant being inserted into element 0.  It is cheaper to do
4873     // a constant pool load than it is to do a movd + shuffle.
4874     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4875         (!IsAllConstants || Idx == 0)) {
4876       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4877         // Handle SSE only.
4878         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4879         EVT VecVT = MVT::v4i32;
4880         unsigned VecElts = 4;
4881
4882         // Truncate the value (which may itself be a constant) to i32, and
4883         // convert it to a vector with movd (S2V+shuffle to zero extend).
4884         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4885         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4886         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4887                                            Subtarget->hasSSE2(), DAG);
4888
4889         // Now we have our 32-bit value zero extended in the low element of
4890         // a vector.  If Idx != 0, swizzle it into place.
4891         if (Idx != 0) {
4892           SmallVector<int, 4> Mask;
4893           Mask.push_back(Idx);
4894           for (unsigned i = 1; i != VecElts; ++i)
4895             Mask.push_back(i);
4896           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4897                                       DAG.getUNDEF(Item.getValueType()),
4898                                       &Mask[0]);
4899         }
4900         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4901       }
4902     }
4903
4904     // If we have a constant or non-constant insertion into the low element of
4905     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4906     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4907     // depending on what the source datatype is.
4908     if (Idx == 0) {
4909       if (NumZero == 0) {
4910         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4911       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4912           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4913         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4914         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4915         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4916                                            DAG);
4917       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4918         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4919         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4920         EVT MiddleVT = MVT::v4i32;
4921         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4922         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4923                                            Subtarget->hasSSE2(), DAG);
4924         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4925       }
4926     }
4927
4928     // Is it a vector logical left shift?
4929     if (NumElems == 2 && Idx == 1 &&
4930         X86::isZeroNode(Op.getOperand(0)) &&
4931         !X86::isZeroNode(Op.getOperand(1))) {
4932       unsigned NumBits = VT.getSizeInBits();
4933       return getVShift(true, VT,
4934                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4935                                    VT, Op.getOperand(1)),
4936                        NumBits/2, DAG, *this, dl);
4937     }
4938
4939     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4940       return SDValue();
4941
4942     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4943     // is a non-constant being inserted into an element other than the low one,
4944     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4945     // movd/movss) to move this into the low element, then shuffle it into
4946     // place.
4947     if (EVTBits == 32) {
4948       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4949
4950       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4951       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4952                                          Subtarget->hasSSE2(), DAG);
4953       SmallVector<int, 8> MaskVec;
4954       for (unsigned i = 0; i < NumElems; i++)
4955         MaskVec.push_back(i == Idx ? 0 : 1);
4956       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4957     }
4958   }
4959
4960   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4961   if (Values.size() == 1) {
4962     if (EVTBits == 32) {
4963       // Instead of a shuffle like this:
4964       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4965       // Check if it's possible to issue this instead.
4966       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4967       unsigned Idx = CountTrailingZeros_32(NonZeros);
4968       SDValue Item = Op.getOperand(Idx);
4969       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4970         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4971     }
4972     return SDValue();
4973   }
4974
4975   // A vector full of immediates; various special cases are already
4976   // handled, so this is best done with a single constant-pool load.
4977   if (IsAllConstants)
4978     return SDValue();
4979
4980   // For AVX-length vectors, build the individual 128-bit pieces and use
4981   // shuffles to put them in place.
4982   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
4983     SmallVector<SDValue, 32> V;
4984     for (unsigned i = 0; i < NumElems; ++i)
4985       V.push_back(Op.getOperand(i));
4986
4987     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
4988
4989     // Build both the lower and upper subvector.
4990     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
4991     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
4992                                 NumElems/2);
4993
4994     // Recreate the wider vector with the lower and upper part.
4995     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
4996                                 DAG.getConstant(0, MVT::i32), DAG, dl);
4997     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
4998                               DAG, dl);
4999   }
5000
5001   // Let legalizer expand 2-wide build_vectors.
5002   if (EVTBits == 64) {
5003     if (NumNonZero == 1) {
5004       // One half is zero or undef.
5005       unsigned Idx = CountTrailingZeros_32(NonZeros);
5006       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5007                                  Op.getOperand(Idx));
5008       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5009                                          Subtarget->hasSSE2(), DAG);
5010     }
5011     return SDValue();
5012   }
5013
5014   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5015   if (EVTBits == 8 && NumElems == 16) {
5016     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5017                                         *this);
5018     if (V.getNode()) return V;
5019   }
5020
5021   if (EVTBits == 16 && NumElems == 8) {
5022     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5023                                       *this);
5024     if (V.getNode()) return V;
5025   }
5026
5027   // If element VT is == 32 bits, turn it into a number of shuffles.
5028   SmallVector<SDValue, 8> V;
5029   V.resize(NumElems);
5030   if (NumElems == 4 && NumZero > 0) {
5031     for (unsigned i = 0; i < 4; ++i) {
5032       bool isZero = !(NonZeros & (1 << i));
5033       if (isZero)
5034         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5035       else
5036         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5037     }
5038
5039     for (unsigned i = 0; i < 2; ++i) {
5040       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5041         default: break;
5042         case 0:
5043           V[i] = V[i*2];  // Must be a zero vector.
5044           break;
5045         case 1:
5046           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5047           break;
5048         case 2:
5049           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5050           break;
5051         case 3:
5052           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5053           break;
5054       }
5055     }
5056
5057     SmallVector<int, 8> MaskVec;
5058     bool Reverse = (NonZeros & 0x3) == 2;
5059     for (unsigned i = 0; i < 2; ++i)
5060       MaskVec.push_back(Reverse ? 1-i : i);
5061     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5062     for (unsigned i = 0; i < 2; ++i)
5063       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5064     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5065   }
5066
5067   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5068     // Check for a build vector of consecutive loads.
5069     for (unsigned i = 0; i < NumElems; ++i)
5070       V[i] = Op.getOperand(i);
5071
5072     // Check for elements which are consecutive loads.
5073     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5074     if (LD.getNode())
5075       return LD;
5076
5077     // For SSE 4.1, use insertps to put the high elements into the low element.
5078     if (getSubtarget()->hasSSE41()) {
5079       SDValue Result;
5080       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5081         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5082       else
5083         Result = DAG.getUNDEF(VT);
5084
5085       for (unsigned i = 1; i < NumElems; ++i) {
5086         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5087         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5088                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5089       }
5090       return Result;
5091     }
5092
5093     // Otherwise, expand into a number of unpckl*, start by extending each of
5094     // our (non-undef) elements to the full vector width with the element in the
5095     // bottom slot of the vector (which generates no code for SSE).
5096     for (unsigned i = 0; i < NumElems; ++i) {
5097       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5098         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5099       else
5100         V[i] = DAG.getUNDEF(VT);
5101     }
5102
5103     // Next, we iteratively mix elements, e.g. for v4f32:
5104     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5105     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5106     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5107     unsigned EltStride = NumElems >> 1;
5108     while (EltStride != 0) {
5109       for (unsigned i = 0; i < EltStride; ++i) {
5110         // If V[i+EltStride] is undef and this is the first round of mixing,
5111         // then it is safe to just drop this shuffle: V[i] is already in the
5112         // right place, the one element (since it's the first round) being
5113         // inserted as undef can be dropped.  This isn't safe for successive
5114         // rounds because they will permute elements within both vectors.
5115         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5116             EltStride == NumElems/2)
5117           continue;
5118
5119         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5120       }
5121       EltStride >>= 1;
5122     }
5123     return V[0];
5124   }
5125   return SDValue();
5126 }
5127
5128 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5129 // them in a MMX register.  This is better than doing a stack convert.
5130 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5131   DebugLoc dl = Op.getDebugLoc();
5132   EVT ResVT = Op.getValueType();
5133
5134   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5135          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5136   int Mask[2];
5137   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5138   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5139   InVec = Op.getOperand(1);
5140   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5141     unsigned NumElts = ResVT.getVectorNumElements();
5142     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5143     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5144                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5145   } else {
5146     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5147     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5148     Mask[0] = 0; Mask[1] = 2;
5149     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5150   }
5151   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5152 }
5153
5154 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5155 // to create 256-bit vectors from two other 128-bit ones.
5156 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5157   DebugLoc dl = Op.getDebugLoc();
5158   EVT ResVT = Op.getValueType();
5159
5160   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5161
5162   SDValue V1 = Op.getOperand(0);
5163   SDValue V2 = Op.getOperand(1);
5164   unsigned NumElems = ResVT.getVectorNumElements();
5165
5166   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5167                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5168   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5169                             DAG, dl);
5170 }
5171
5172 SDValue
5173 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5174   EVT ResVT = Op.getValueType();
5175
5176   assert(Op.getNumOperands() == 2);
5177   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5178          "Unsupported CONCAT_VECTORS for value type");
5179
5180   // We support concatenate two MMX registers and place them in a MMX register.
5181   // This is better than doing a stack convert.
5182   if (ResVT.is128BitVector())
5183     return LowerMMXCONCAT_VECTORS(Op, DAG);
5184
5185   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5186   // from two other 128-bit ones.
5187   return LowerAVXCONCAT_VECTORS(Op, DAG);
5188 }
5189
5190 // v8i16 shuffles - Prefer shuffles in the following order:
5191 // 1. [all]   pshuflw, pshufhw, optional move
5192 // 2. [ssse3] 1 x pshufb
5193 // 3. [ssse3] 2 x pshufb + 1 x por
5194 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5195 SDValue
5196 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5197                                             SelectionDAG &DAG) const {
5198   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5199   SDValue V1 = SVOp->getOperand(0);
5200   SDValue V2 = SVOp->getOperand(1);
5201   DebugLoc dl = SVOp->getDebugLoc();
5202   SmallVector<int, 8> MaskVals;
5203
5204   // Determine if more than 1 of the words in each of the low and high quadwords
5205   // of the result come from the same quadword of one of the two inputs.  Undef
5206   // mask values count as coming from any quadword, for better codegen.
5207   SmallVector<unsigned, 4> LoQuad(4);
5208   SmallVector<unsigned, 4> HiQuad(4);
5209   BitVector InputQuads(4);
5210   for (unsigned i = 0; i < 8; ++i) {
5211     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5212     int EltIdx = SVOp->getMaskElt(i);
5213     MaskVals.push_back(EltIdx);
5214     if (EltIdx < 0) {
5215       ++Quad[0];
5216       ++Quad[1];
5217       ++Quad[2];
5218       ++Quad[3];
5219       continue;
5220     }
5221     ++Quad[EltIdx / 4];
5222     InputQuads.set(EltIdx / 4);
5223   }
5224
5225   int BestLoQuad = -1;
5226   unsigned MaxQuad = 1;
5227   for (unsigned i = 0; i < 4; ++i) {
5228     if (LoQuad[i] > MaxQuad) {
5229       BestLoQuad = i;
5230       MaxQuad = LoQuad[i];
5231     }
5232   }
5233
5234   int BestHiQuad = -1;
5235   MaxQuad = 1;
5236   for (unsigned i = 0; i < 4; ++i) {
5237     if (HiQuad[i] > MaxQuad) {
5238       BestHiQuad = i;
5239       MaxQuad = HiQuad[i];
5240     }
5241   }
5242
5243   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5244   // of the two input vectors, shuffle them into one input vector so only a
5245   // single pshufb instruction is necessary. If There are more than 2 input
5246   // quads, disable the next transformation since it does not help SSSE3.
5247   bool V1Used = InputQuads[0] || InputQuads[1];
5248   bool V2Used = InputQuads[2] || InputQuads[3];
5249   if (Subtarget->hasSSSE3()) {
5250     if (InputQuads.count() == 2 && V1Used && V2Used) {
5251       BestLoQuad = InputQuads.find_first();
5252       BestHiQuad = InputQuads.find_next(BestLoQuad);
5253     }
5254     if (InputQuads.count() > 2) {
5255       BestLoQuad = -1;
5256       BestHiQuad = -1;
5257     }
5258   }
5259
5260   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5261   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5262   // words from all 4 input quadwords.
5263   SDValue NewV;
5264   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5265     SmallVector<int, 8> MaskV;
5266     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5267     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5268     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5269                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5270                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5271     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5272
5273     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5274     // source words for the shuffle, to aid later transformations.
5275     bool AllWordsInNewV = true;
5276     bool InOrder[2] = { true, true };
5277     for (unsigned i = 0; i != 8; ++i) {
5278       int idx = MaskVals[i];
5279       if (idx != (int)i)
5280         InOrder[i/4] = false;
5281       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5282         continue;
5283       AllWordsInNewV = false;
5284       break;
5285     }
5286
5287     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5288     if (AllWordsInNewV) {
5289       for (int i = 0; i != 8; ++i) {
5290         int idx = MaskVals[i];
5291         if (idx < 0)
5292           continue;
5293         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5294         if ((idx != i) && idx < 4)
5295           pshufhw = false;
5296         if ((idx != i) && idx > 3)
5297           pshuflw = false;
5298       }
5299       V1 = NewV;
5300       V2Used = false;
5301       BestLoQuad = 0;
5302       BestHiQuad = 1;
5303     }
5304
5305     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5306     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5307     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5308       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5309       unsigned TargetMask = 0;
5310       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5311                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5312       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5313                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5314       V1 = NewV.getOperand(0);
5315       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5316     }
5317   }
5318
5319   // If we have SSSE3, and all words of the result are from 1 input vector,
5320   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5321   // is present, fall back to case 4.
5322   if (Subtarget->hasSSSE3()) {
5323     SmallVector<SDValue,16> pshufbMask;
5324
5325     // If we have elements from both input vectors, set the high bit of the
5326     // shuffle mask element to zero out elements that come from V2 in the V1
5327     // mask, and elements that come from V1 in the V2 mask, so that the two
5328     // results can be OR'd together.
5329     bool TwoInputs = V1Used && V2Used;
5330     for (unsigned i = 0; i != 8; ++i) {
5331       int EltIdx = MaskVals[i] * 2;
5332       if (TwoInputs && (EltIdx >= 16)) {
5333         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5334         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5335         continue;
5336       }
5337       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5338       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5339     }
5340     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5341     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5342                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5343                                  MVT::v16i8, &pshufbMask[0], 16));
5344     if (!TwoInputs)
5345       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5346
5347     // Calculate the shuffle mask for the second input, shuffle it, and
5348     // OR it with the first shuffled input.
5349     pshufbMask.clear();
5350     for (unsigned i = 0; i != 8; ++i) {
5351       int EltIdx = MaskVals[i] * 2;
5352       if (EltIdx < 16) {
5353         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5354         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5355         continue;
5356       }
5357       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5358       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5359     }
5360     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5361     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5362                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5363                                  MVT::v16i8, &pshufbMask[0], 16));
5364     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5365     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5366   }
5367
5368   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5369   // and update MaskVals with new element order.
5370   BitVector InOrder(8);
5371   if (BestLoQuad >= 0) {
5372     SmallVector<int, 8> MaskV;
5373     for (int i = 0; i != 4; ++i) {
5374       int idx = MaskVals[i];
5375       if (idx < 0) {
5376         MaskV.push_back(-1);
5377         InOrder.set(i);
5378       } else if ((idx / 4) == BestLoQuad) {
5379         MaskV.push_back(idx & 3);
5380         InOrder.set(i);
5381       } else {
5382         MaskV.push_back(-1);
5383       }
5384     }
5385     for (unsigned i = 4; i != 8; ++i)
5386       MaskV.push_back(i);
5387     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5388                                 &MaskV[0]);
5389
5390     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5391       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5392                                NewV.getOperand(0),
5393                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5394                                DAG);
5395   }
5396
5397   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5398   // and update MaskVals with the new element order.
5399   if (BestHiQuad >= 0) {
5400     SmallVector<int, 8> MaskV;
5401     for (unsigned i = 0; i != 4; ++i)
5402       MaskV.push_back(i);
5403     for (unsigned i = 4; i != 8; ++i) {
5404       int idx = MaskVals[i];
5405       if (idx < 0) {
5406         MaskV.push_back(-1);
5407         InOrder.set(i);
5408       } else if ((idx / 4) == BestHiQuad) {
5409         MaskV.push_back((idx & 3) + 4);
5410         InOrder.set(i);
5411       } else {
5412         MaskV.push_back(-1);
5413       }
5414     }
5415     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5416                                 &MaskV[0]);
5417
5418     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5419       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5420                               NewV.getOperand(0),
5421                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5422                               DAG);
5423   }
5424
5425   // In case BestHi & BestLo were both -1, which means each quadword has a word
5426   // from each of the four input quadwords, calculate the InOrder bitvector now
5427   // before falling through to the insert/extract cleanup.
5428   if (BestLoQuad == -1 && BestHiQuad == -1) {
5429     NewV = V1;
5430     for (int i = 0; i != 8; ++i)
5431       if (MaskVals[i] < 0 || MaskVals[i] == i)
5432         InOrder.set(i);
5433   }
5434
5435   // The other elements are put in the right place using pextrw and pinsrw.
5436   for (unsigned i = 0; i != 8; ++i) {
5437     if (InOrder[i])
5438       continue;
5439     int EltIdx = MaskVals[i];
5440     if (EltIdx < 0)
5441       continue;
5442     SDValue ExtOp = (EltIdx < 8)
5443     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5444                   DAG.getIntPtrConstant(EltIdx))
5445     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5446                   DAG.getIntPtrConstant(EltIdx - 8));
5447     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5448                        DAG.getIntPtrConstant(i));
5449   }
5450   return NewV;
5451 }
5452
5453 // v16i8 shuffles - Prefer shuffles in the following order:
5454 // 1. [ssse3] 1 x pshufb
5455 // 2. [ssse3] 2 x pshufb + 1 x por
5456 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5457 static
5458 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5459                                  SelectionDAG &DAG,
5460                                  const X86TargetLowering &TLI) {
5461   SDValue V1 = SVOp->getOperand(0);
5462   SDValue V2 = SVOp->getOperand(1);
5463   DebugLoc dl = SVOp->getDebugLoc();
5464   SmallVector<int, 16> MaskVals;
5465   SVOp->getMask(MaskVals);
5466
5467   // If we have SSSE3, case 1 is generated when all result bytes come from
5468   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5469   // present, fall back to case 3.
5470   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5471   bool V1Only = true;
5472   bool V2Only = true;
5473   for (unsigned i = 0; i < 16; ++i) {
5474     int EltIdx = MaskVals[i];
5475     if (EltIdx < 0)
5476       continue;
5477     if (EltIdx < 16)
5478       V2Only = false;
5479     else
5480       V1Only = false;
5481   }
5482
5483   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5484   if (TLI.getSubtarget()->hasSSSE3()) {
5485     SmallVector<SDValue,16> pshufbMask;
5486
5487     // If all result elements are from one input vector, then only translate
5488     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5489     //
5490     // Otherwise, we have elements from both input vectors, and must zero out
5491     // elements that come from V2 in the first mask, and V1 in the second mask
5492     // so that we can OR them together.
5493     bool TwoInputs = !(V1Only || V2Only);
5494     for (unsigned i = 0; i != 16; ++i) {
5495       int EltIdx = MaskVals[i];
5496       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5497         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5498         continue;
5499       }
5500       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5501     }
5502     // If all the elements are from V2, assign it to V1 and return after
5503     // building the first pshufb.
5504     if (V2Only)
5505       V1 = V2;
5506     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5507                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5508                                  MVT::v16i8, &pshufbMask[0], 16));
5509     if (!TwoInputs)
5510       return V1;
5511
5512     // Calculate the shuffle mask for the second input, shuffle it, and
5513     // OR it with the first shuffled input.
5514     pshufbMask.clear();
5515     for (unsigned i = 0; i != 16; ++i) {
5516       int EltIdx = MaskVals[i];
5517       if (EltIdx < 16) {
5518         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5519         continue;
5520       }
5521       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5522     }
5523     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5524                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5525                                  MVT::v16i8, &pshufbMask[0], 16));
5526     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5527   }
5528
5529   // No SSSE3 - Calculate in place words and then fix all out of place words
5530   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5531   // the 16 different words that comprise the two doublequadword input vectors.
5532   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5533   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5534   SDValue NewV = V2Only ? V2 : V1;
5535   for (int i = 0; i != 8; ++i) {
5536     int Elt0 = MaskVals[i*2];
5537     int Elt1 = MaskVals[i*2+1];
5538
5539     // This word of the result is all undef, skip it.
5540     if (Elt0 < 0 && Elt1 < 0)
5541       continue;
5542
5543     // This word of the result is already in the correct place, skip it.
5544     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5545       continue;
5546     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5547       continue;
5548
5549     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5550     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5551     SDValue InsElt;
5552
5553     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5554     // using a single extract together, load it and store it.
5555     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5556       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5557                            DAG.getIntPtrConstant(Elt1 / 2));
5558       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5559                         DAG.getIntPtrConstant(i));
5560       continue;
5561     }
5562
5563     // If Elt1 is defined, extract it from the appropriate source.  If the
5564     // source byte is not also odd, shift the extracted word left 8 bits
5565     // otherwise clear the bottom 8 bits if we need to do an or.
5566     if (Elt1 >= 0) {
5567       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5568                            DAG.getIntPtrConstant(Elt1 / 2));
5569       if ((Elt1 & 1) == 0)
5570         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5571                              DAG.getConstant(8,
5572                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5573       else if (Elt0 >= 0)
5574         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5575                              DAG.getConstant(0xFF00, MVT::i16));
5576     }
5577     // If Elt0 is defined, extract it from the appropriate source.  If the
5578     // source byte is not also even, shift the extracted word right 8 bits. If
5579     // Elt1 was also defined, OR the extracted values together before
5580     // inserting them in the result.
5581     if (Elt0 >= 0) {
5582       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5583                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5584       if ((Elt0 & 1) != 0)
5585         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5586                               DAG.getConstant(8,
5587                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5588       else if (Elt1 >= 0)
5589         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5590                              DAG.getConstant(0x00FF, MVT::i16));
5591       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5592                          : InsElt0;
5593     }
5594     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5595                        DAG.getIntPtrConstant(i));
5596   }
5597   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5598 }
5599
5600 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5601 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5602 /// done when every pair / quad of shuffle mask elements point to elements in
5603 /// the right sequence. e.g.
5604 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5605 static
5606 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5607                                  SelectionDAG &DAG, DebugLoc dl) {
5608   EVT VT = SVOp->getValueType(0);
5609   SDValue V1 = SVOp->getOperand(0);
5610   SDValue V2 = SVOp->getOperand(1);
5611   unsigned NumElems = VT.getVectorNumElements();
5612   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5613   EVT NewVT;
5614   switch (VT.getSimpleVT().SimpleTy) {
5615   default: assert(false && "Unexpected!");
5616   case MVT::v4f32: NewVT = MVT::v2f64; break;
5617   case MVT::v4i32: NewVT = MVT::v2i64; break;
5618   case MVT::v8i16: NewVT = MVT::v4i32; break;
5619   case MVT::v16i8: NewVT = MVT::v4i32; break;
5620   }
5621
5622   int Scale = NumElems / NewWidth;
5623   SmallVector<int, 8> MaskVec;
5624   for (unsigned i = 0; i < NumElems; i += Scale) {
5625     int StartIdx = -1;
5626     for (int j = 0; j < Scale; ++j) {
5627       int EltIdx = SVOp->getMaskElt(i+j);
5628       if (EltIdx < 0)
5629         continue;
5630       if (StartIdx == -1)
5631         StartIdx = EltIdx - (EltIdx % Scale);
5632       if (EltIdx != StartIdx + j)
5633         return SDValue();
5634     }
5635     if (StartIdx == -1)
5636       MaskVec.push_back(-1);
5637     else
5638       MaskVec.push_back(StartIdx / Scale);
5639   }
5640
5641   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5642   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5643   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5644 }
5645
5646 /// getVZextMovL - Return a zero-extending vector move low node.
5647 ///
5648 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5649                             SDValue SrcOp, SelectionDAG &DAG,
5650                             const X86Subtarget *Subtarget, DebugLoc dl) {
5651   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5652     LoadSDNode *LD = NULL;
5653     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5654       LD = dyn_cast<LoadSDNode>(SrcOp);
5655     if (!LD) {
5656       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5657       // instead.
5658       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5659       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5660           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5661           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5662           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5663         // PR2108
5664         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5665         return DAG.getNode(ISD::BITCAST, dl, VT,
5666                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5667                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5668                                                    OpVT,
5669                                                    SrcOp.getOperand(0)
5670                                                           .getOperand(0))));
5671       }
5672     }
5673   }
5674
5675   return DAG.getNode(ISD::BITCAST, dl, VT,
5676                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5677                                  DAG.getNode(ISD::BITCAST, dl,
5678                                              OpVT, SrcOp)));
5679 }
5680
5681 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5682 /// shuffle node referes to only one lane in the sources.
5683 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5684   EVT VT = SVOp->getValueType(0);
5685   int NumElems = VT.getVectorNumElements();
5686   int HalfSize = NumElems/2;
5687   SmallVector<int, 16> M;
5688   SVOp->getMask(M);
5689   bool MatchA = false, MatchB = false;
5690
5691   for (int l = 0; l < NumElems*2; l += HalfSize) {
5692     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5693       MatchA = true;
5694       break;
5695     }
5696   }
5697
5698   for (int l = 0; l < NumElems*2; l += HalfSize) {
5699     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5700       MatchB = true;
5701       break;
5702     }
5703   }
5704
5705   return MatchA && MatchB;
5706 }
5707
5708 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5709 /// which could not be matched by any known target speficic shuffle
5710 static SDValue
5711 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5712   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5713     // If each half of a vector shuffle node referes to only one lane in the
5714     // source vectors, extract each used 128-bit lane and shuffle them using
5715     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5716     // the work to the legalizer.
5717     DebugLoc dl = SVOp->getDebugLoc();
5718     EVT VT = SVOp->getValueType(0);
5719     int NumElems = VT.getVectorNumElements();
5720     int HalfSize = NumElems/2;
5721
5722     // Extract the reference for each half
5723     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5724     int FstVecOpNum = 0, SndVecOpNum = 0;
5725     for (int i = 0; i < HalfSize; ++i) {
5726       int Elt = SVOp->getMaskElt(i);
5727       if (SVOp->getMaskElt(i) < 0)
5728         continue;
5729       FstVecOpNum = Elt/NumElems;
5730       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5731       break;
5732     }
5733     for (int i = HalfSize; i < NumElems; ++i) {
5734       int Elt = SVOp->getMaskElt(i);
5735       if (SVOp->getMaskElt(i) < 0)
5736         continue;
5737       SndVecOpNum = Elt/NumElems;
5738       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5739       break;
5740     }
5741
5742     // Extract the subvectors
5743     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5744                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5745     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5746                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5747
5748     // Generate 128-bit shuffles
5749     SmallVector<int, 16> MaskV1, MaskV2;
5750     for (int i = 0; i < HalfSize; ++i) {
5751       int Elt = SVOp->getMaskElt(i);
5752       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5753     }
5754     for (int i = HalfSize; i < NumElems; ++i) {
5755       int Elt = SVOp->getMaskElt(i);
5756       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5757     }
5758
5759     EVT NVT = V1.getValueType();
5760     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5761     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5762
5763     // Concatenate the result back
5764     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
5765                                    DAG.getConstant(0, MVT::i32), DAG, dl);
5766     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5767                               DAG, dl);
5768   }
5769
5770   return SDValue();
5771 }
5772
5773 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
5774 /// 4 elements, and match them with several different shuffle types.
5775 static SDValue
5776 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5777   SDValue V1 = SVOp->getOperand(0);
5778   SDValue V2 = SVOp->getOperand(1);
5779   DebugLoc dl = SVOp->getDebugLoc();
5780   EVT VT = SVOp->getValueType(0);
5781
5782   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
5783
5784   SmallVector<std::pair<int, int>, 8> Locs;
5785   Locs.resize(4);
5786   SmallVector<int, 8> Mask1(4U, -1);
5787   SmallVector<int, 8> PermMask;
5788   SVOp->getMask(PermMask);
5789
5790   unsigned NumHi = 0;
5791   unsigned NumLo = 0;
5792   for (unsigned i = 0; i != 4; ++i) {
5793     int Idx = PermMask[i];
5794     if (Idx < 0) {
5795       Locs[i] = std::make_pair(-1, -1);
5796     } else {
5797       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5798       if (Idx < 4) {
5799         Locs[i] = std::make_pair(0, NumLo);
5800         Mask1[NumLo] = Idx;
5801         NumLo++;
5802       } else {
5803         Locs[i] = std::make_pair(1, NumHi);
5804         if (2+NumHi < 4)
5805           Mask1[2+NumHi] = Idx;
5806         NumHi++;
5807       }
5808     }
5809   }
5810
5811   if (NumLo <= 2 && NumHi <= 2) {
5812     // If no more than two elements come from either vector. This can be
5813     // implemented with two shuffles. First shuffle gather the elements.
5814     // The second shuffle, which takes the first shuffle as both of its
5815     // vector operands, put the elements into the right order.
5816     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5817
5818     SmallVector<int, 8> Mask2(4U, -1);
5819
5820     for (unsigned i = 0; i != 4; ++i) {
5821       if (Locs[i].first == -1)
5822         continue;
5823       else {
5824         unsigned Idx = (i < 2) ? 0 : 4;
5825         Idx += Locs[i].first * 2 + Locs[i].second;
5826         Mask2[i] = Idx;
5827       }
5828     }
5829
5830     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5831   } else if (NumLo == 3 || NumHi == 3) {
5832     // Otherwise, we must have three elements from one vector, call it X, and
5833     // one element from the other, call it Y.  First, use a shufps to build an
5834     // intermediate vector with the one element from Y and the element from X
5835     // that will be in the same half in the final destination (the indexes don't
5836     // matter). Then, use a shufps to build the final vector, taking the half
5837     // containing the element from Y from the intermediate, and the other half
5838     // from X.
5839     if (NumHi == 3) {
5840       // Normalize it so the 3 elements come from V1.
5841       CommuteVectorShuffleMask(PermMask, VT);
5842       std::swap(V1, V2);
5843     }
5844
5845     // Find the element from V2.
5846     unsigned HiIndex;
5847     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5848       int Val = PermMask[HiIndex];
5849       if (Val < 0)
5850         continue;
5851       if (Val >= 4)
5852         break;
5853     }
5854
5855     Mask1[0] = PermMask[HiIndex];
5856     Mask1[1] = -1;
5857     Mask1[2] = PermMask[HiIndex^1];
5858     Mask1[3] = -1;
5859     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5860
5861     if (HiIndex >= 2) {
5862       Mask1[0] = PermMask[0];
5863       Mask1[1] = PermMask[1];
5864       Mask1[2] = HiIndex & 1 ? 6 : 4;
5865       Mask1[3] = HiIndex & 1 ? 4 : 6;
5866       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5867     } else {
5868       Mask1[0] = HiIndex & 1 ? 2 : 0;
5869       Mask1[1] = HiIndex & 1 ? 0 : 2;
5870       Mask1[2] = PermMask[2];
5871       Mask1[3] = PermMask[3];
5872       if (Mask1[2] >= 0)
5873         Mask1[2] += 4;
5874       if (Mask1[3] >= 0)
5875         Mask1[3] += 4;
5876       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5877     }
5878   }
5879
5880   // Break it into (shuffle shuffle_hi, shuffle_lo).
5881   Locs.clear();
5882   Locs.resize(4);
5883   SmallVector<int,8> LoMask(4U, -1);
5884   SmallVector<int,8> HiMask(4U, -1);
5885
5886   SmallVector<int,8> *MaskPtr = &LoMask;
5887   unsigned MaskIdx = 0;
5888   unsigned LoIdx = 0;
5889   unsigned HiIdx = 2;
5890   for (unsigned i = 0; i != 4; ++i) {
5891     if (i == 2) {
5892       MaskPtr = &HiMask;
5893       MaskIdx = 1;
5894       LoIdx = 0;
5895       HiIdx = 2;
5896     }
5897     int Idx = PermMask[i];
5898     if (Idx < 0) {
5899       Locs[i] = std::make_pair(-1, -1);
5900     } else if (Idx < 4) {
5901       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5902       (*MaskPtr)[LoIdx] = Idx;
5903       LoIdx++;
5904     } else {
5905       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5906       (*MaskPtr)[HiIdx] = Idx;
5907       HiIdx++;
5908     }
5909   }
5910
5911   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5912   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5913   SmallVector<int, 8> MaskOps;
5914   for (unsigned i = 0; i != 4; ++i) {
5915     if (Locs[i].first == -1) {
5916       MaskOps.push_back(-1);
5917     } else {
5918       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5919       MaskOps.push_back(Idx);
5920     }
5921   }
5922   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5923 }
5924
5925 static bool MayFoldVectorLoad(SDValue V) {
5926   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5927     V = V.getOperand(0);
5928   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5929     V = V.getOperand(0);
5930   if (MayFoldLoad(V))
5931     return true;
5932   return false;
5933 }
5934
5935 // FIXME: the version above should always be used. Since there's
5936 // a bug where several vector shuffles can't be folded because the
5937 // DAG is not updated during lowering and a node claims to have two
5938 // uses while it only has one, use this version, and let isel match
5939 // another instruction if the load really happens to have more than
5940 // one use. Remove this version after this bug get fixed.
5941 // rdar://8434668, PR8156
5942 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5943   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5944     V = V.getOperand(0);
5945   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5946     V = V.getOperand(0);
5947   if (ISD::isNormalLoad(V.getNode()))
5948     return true;
5949   return false;
5950 }
5951
5952 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5953 /// a vector extract, and if both can be later optimized into a single load.
5954 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5955 /// here because otherwise a target specific shuffle node is going to be
5956 /// emitted for this shuffle, and the optimization not done.
5957 /// FIXME: This is probably not the best approach, but fix the problem
5958 /// until the right path is decided.
5959 static
5960 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5961                                          const TargetLowering &TLI) {
5962   EVT VT = V.getValueType();
5963   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5964
5965   // Be sure that the vector shuffle is present in a pattern like this:
5966   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5967   if (!V.hasOneUse())
5968     return false;
5969
5970   SDNode *N = *V.getNode()->use_begin();
5971   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5972     return false;
5973
5974   SDValue EltNo = N->getOperand(1);
5975   if (!isa<ConstantSDNode>(EltNo))
5976     return false;
5977
5978   // If the bit convert changed the number of elements, it is unsafe
5979   // to examine the mask.
5980   bool HasShuffleIntoBitcast = false;
5981   if (V.getOpcode() == ISD::BITCAST) {
5982     EVT SrcVT = V.getOperand(0).getValueType();
5983     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5984       return false;
5985     V = V.getOperand(0);
5986     HasShuffleIntoBitcast = true;
5987   }
5988
5989   // Select the input vector, guarding against out of range extract vector.
5990   unsigned NumElems = VT.getVectorNumElements();
5991   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5992   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5993   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5994
5995   // Skip one more bit_convert if necessary
5996   if (V.getOpcode() == ISD::BITCAST)
5997     V = V.getOperand(0);
5998
5999   if (ISD::isNormalLoad(V.getNode())) {
6000     // Is the original load suitable?
6001     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6002
6003     // FIXME: avoid the multi-use bug that is preventing lots of
6004     // of foldings to be detected, this is still wrong of course, but
6005     // give the temporary desired behavior, and if it happens that
6006     // the load has real more uses, during isel it will not fold, and
6007     // will generate poor code.
6008     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6009       return false;
6010
6011     if (!HasShuffleIntoBitcast)
6012       return true;
6013
6014     // If there's a bitcast before the shuffle, check if the load type and
6015     // alignment is valid.
6016     unsigned Align = LN0->getAlignment();
6017     unsigned NewAlign =
6018       TLI.getTargetData()->getABITypeAlignment(
6019                                     VT.getTypeForEVT(*DAG.getContext()));
6020
6021     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6022       return false;
6023   }
6024
6025   return true;
6026 }
6027
6028 static
6029 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6030   EVT VT = Op.getValueType();
6031
6032   // Canonizalize to v2f64.
6033   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6034   return DAG.getNode(ISD::BITCAST, dl, VT,
6035                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6036                                           V1, DAG));
6037 }
6038
6039 static
6040 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6041                         bool HasSSE2) {
6042   SDValue V1 = Op.getOperand(0);
6043   SDValue V2 = Op.getOperand(1);
6044   EVT VT = Op.getValueType();
6045
6046   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6047
6048   if (HasSSE2 && VT == MVT::v2f64)
6049     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6050
6051   // v4f32 or v4i32
6052   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
6053 }
6054
6055 static
6056 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6057   SDValue V1 = Op.getOperand(0);
6058   SDValue V2 = Op.getOperand(1);
6059   EVT VT = Op.getValueType();
6060
6061   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6062          "unsupported shuffle type");
6063
6064   if (V2.getOpcode() == ISD::UNDEF)
6065     V2 = V1;
6066
6067   // v4i32 or v4f32
6068   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6069 }
6070
6071 static
6072 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6073   SDValue V1 = Op.getOperand(0);
6074   SDValue V2 = Op.getOperand(1);
6075   EVT VT = Op.getValueType();
6076   unsigned NumElems = VT.getVectorNumElements();
6077
6078   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6079   // operand of these instructions is only memory, so check if there's a
6080   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6081   // same masks.
6082   bool CanFoldLoad = false;
6083
6084   // Trivial case, when V2 comes from a load.
6085   if (MayFoldVectorLoad(V2))
6086     CanFoldLoad = true;
6087
6088   // When V1 is a load, it can be folded later into a store in isel, example:
6089   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6090   //    turns into:
6091   //  (MOVLPSmr addr:$src1, VR128:$src2)
6092   // So, recognize this potential and also use MOVLPS or MOVLPD
6093   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6094     CanFoldLoad = true;
6095
6096   // Both of them can't be memory operations though.
6097   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6098     CanFoldLoad = false;
6099
6100   if (CanFoldLoad) {
6101     if (HasSSE2 && NumElems == 2)
6102       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6103
6104     if (NumElems == 4)
6105       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6106   }
6107
6108   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6109   // movl and movlp will both match v2i64, but v2i64 is never matched by
6110   // movl earlier because we make it strict to avoid messing with the movlp load
6111   // folding logic (see the code above getMOVLP call). Match it here then,
6112   // this is horrible, but will stay like this until we move all shuffle
6113   // matching to x86 specific nodes. Note that for the 1st condition all
6114   // types are matched with movsd.
6115   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
6116     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6117   else if (HasSSE2)
6118     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6119
6120
6121   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6122
6123   // Invert the operand order and use SHUFPS to match it.
6124   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
6125                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6126 }
6127
6128 static inline unsigned getUNPCKLOpcode(EVT VT) {
6129   switch(VT.getSimpleVT().SimpleTy) {
6130   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6131   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6132   case MVT::v4f32: return X86ISD::UNPCKLPS;
6133   case MVT::v2f64: return X86ISD::UNPCKLPD;
6134   case MVT::v8i32: // Use fp unit for int unpack.
6135   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6136   case MVT::v4i64: // Use fp unit for int unpack.
6137   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6138   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6139   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6140   default:
6141     llvm_unreachable("Unknown type for unpckl");
6142   }
6143   return 0;
6144 }
6145
6146 static inline unsigned getUNPCKHOpcode(EVT VT) {
6147   switch(VT.getSimpleVT().SimpleTy) {
6148   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6149   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6150   case MVT::v4f32: return X86ISD::UNPCKHPS;
6151   case MVT::v2f64: return X86ISD::UNPCKHPD;
6152   case MVT::v8i32: // Use fp unit for int unpack.
6153   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6154   case MVT::v4i64: // Use fp unit for int unpack.
6155   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6156   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6157   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6158   default:
6159     llvm_unreachable("Unknown type for unpckh");
6160   }
6161   return 0;
6162 }
6163
6164 static inline unsigned getVPERMILOpcode(EVT VT) {
6165   switch(VT.getSimpleVT().SimpleTy) {
6166   case MVT::v4i32:
6167   case MVT::v4f32: return X86ISD::VPERMILPS;
6168   case MVT::v2i64:
6169   case MVT::v2f64: return X86ISD::VPERMILPD;
6170   case MVT::v8i32:
6171   case MVT::v8f32: return X86ISD::VPERMILPSY;
6172   case MVT::v4i64:
6173   case MVT::v4f64: return X86ISD::VPERMILPDY;
6174   default:
6175     llvm_unreachable("Unknown type for vpermil");
6176   }
6177   return 0;
6178 }
6179
6180 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6181 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6182 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6183 static bool isVectorBroadcast(SDValue &Op) {
6184   EVT VT = Op.getValueType();
6185   bool Is256 = VT.getSizeInBits() == 256;
6186
6187   assert((VT.getSizeInBits() == 128 || Is256) &&
6188          "Unsupported type for vbroadcast node");
6189
6190   SDValue V = Op;
6191   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6192     V = V.getOperand(0);
6193
6194   if (Is256 && !(V.hasOneUse() &&
6195                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6196                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6197     return false;
6198
6199   if (Is256)
6200     V = V.getOperand(1);
6201   if (V.hasOneUse() && V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6202     return false;
6203
6204   // Check the source scalar_to_vector type. 256-bit broadcasts are
6205   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6206   // for 32-bit scalars.
6207   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6208   if (ScalarSize != 32 && ScalarSize != 64)
6209     return false;
6210   if (!Is256 && ScalarSize == 64)
6211     return false;
6212
6213   V = V.getOperand(0);
6214   if (!MayFoldLoad(V))
6215     return false;
6216
6217   // Return the load node
6218   Op = V;
6219   return true;
6220 }
6221
6222 static
6223 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6224                                const TargetLowering &TLI,
6225                                const X86Subtarget *Subtarget) {
6226   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6227   EVT VT = Op.getValueType();
6228   DebugLoc dl = Op.getDebugLoc();
6229   SDValue V1 = Op.getOperand(0);
6230   SDValue V2 = Op.getOperand(1);
6231
6232   if (isZeroShuffle(SVOp))
6233     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
6234
6235   // Handle splat operations
6236   if (SVOp->isSplat()) {
6237     unsigned NumElem = VT.getVectorNumElements();
6238     int Size = VT.getSizeInBits();
6239     // Special case, this is the only place now where it's allowed to return
6240     // a vector_shuffle operation without using a target specific node, because
6241     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6242     // this be moved to DAGCombine instead?
6243     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6244       return Op;
6245
6246     // Use vbroadcast whenever the splat comes from a foldable load
6247     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6248       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6249
6250     // Handle splats by matching through known shuffle masks
6251     if ((Size == 128 && NumElem <= 4) ||
6252         (Size == 256 && NumElem < 8))
6253       return SDValue();
6254
6255     // All remaning splats are promoted to target supported vector shuffles.
6256     return PromoteSplat(SVOp, DAG);
6257   }
6258
6259   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6260   // do it!
6261   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6262     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6263     if (NewOp.getNode())
6264       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6265   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6266     // FIXME: Figure out a cleaner way to do this.
6267     // Try to make use of movq to zero out the top part.
6268     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6269       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6270       if (NewOp.getNode()) {
6271         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6272           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6273                               DAG, Subtarget, dl);
6274       }
6275     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6276       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6277       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6278         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6279                             DAG, Subtarget, dl);
6280     }
6281   }
6282   return SDValue();
6283 }
6284
6285 SDValue
6286 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6287   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6288   SDValue V1 = Op.getOperand(0);
6289   SDValue V2 = Op.getOperand(1);
6290   EVT VT = Op.getValueType();
6291   DebugLoc dl = Op.getDebugLoc();
6292   unsigned NumElems = VT.getVectorNumElements();
6293   bool isMMX = VT.getSizeInBits() == 64;
6294   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6295   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6296   bool V1IsSplat = false;
6297   bool V2IsSplat = false;
6298   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
6299   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
6300   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
6301   MachineFunction &MF = DAG.getMachineFunction();
6302   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6303
6304   // Shuffle operations on MMX not supported.
6305   if (isMMX)
6306     return Op;
6307
6308   // Vector shuffle lowering takes 3 steps:
6309   //
6310   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6311   //    narrowing and commutation of operands should be handled.
6312   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6313   //    shuffle nodes.
6314   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6315   //    so the shuffle can be broken into other shuffles and the legalizer can
6316   //    try the lowering again.
6317   //
6318   // The general ideia is that no vector_shuffle operation should be left to
6319   // be matched during isel, all of them must be converted to a target specific
6320   // node here.
6321
6322   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6323   // narrowing and commutation of operands should be handled. The actual code
6324   // doesn't include all of those, work in progress...
6325   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6326   if (NewOp.getNode())
6327     return NewOp;
6328
6329   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6330   // unpckh_undef). Only use pshufd if speed is more important than size.
6331   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6332     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6333   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6334     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6335
6336   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
6337       RelaxedMayFoldVectorLoad(V1))
6338     return getMOVDDup(Op, dl, V1, DAG);
6339
6340   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6341     return getMOVHighToLow(Op, dl, DAG);
6342
6343   // Use to match splats
6344   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6345       (VT == MVT::v2f64 || VT == MVT::v2i64))
6346     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6347
6348   if (X86::isPSHUFDMask(SVOp)) {
6349     // The actual implementation will match the mask in the if above and then
6350     // during isel it can match several different instructions, not only pshufd
6351     // as its name says, sad but true, emulate the behavior for now...
6352     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6353         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6354
6355     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6356
6357     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6358       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6359
6360     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6361       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
6362                                   TargetMask, DAG);
6363
6364     if (VT == MVT::v4f32)
6365       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
6366                                   TargetMask, DAG);
6367   }
6368
6369   // Check if this can be converted into a logical shift.
6370   bool isLeft = false;
6371   unsigned ShAmt = 0;
6372   SDValue ShVal;
6373   bool isShift = getSubtarget()->hasSSE2() &&
6374     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6375   if (isShift && ShVal.hasOneUse()) {
6376     // If the shifted value has multiple uses, it may be cheaper to use
6377     // v_set0 + movlhps or movhlps, etc.
6378     EVT EltVT = VT.getVectorElementType();
6379     ShAmt *= EltVT.getSizeInBits();
6380     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6381   }
6382
6383   if (X86::isMOVLMask(SVOp)) {
6384     if (V1IsUndef)
6385       return V2;
6386     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6387       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6388     if (!X86::isMOVLPMask(SVOp)) {
6389       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6390         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6391
6392       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6393         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6394     }
6395   }
6396
6397   // FIXME: fold these into legal mask.
6398   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6399     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6400
6401   if (X86::isMOVHLPSMask(SVOp))
6402     return getMOVHighToLow(Op, dl, DAG);
6403
6404   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6405     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6406
6407   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6408     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6409
6410   if (X86::isMOVLPMask(SVOp))
6411     return getMOVLP(Op, dl, DAG, HasSSE2);
6412
6413   if (ShouldXformToMOVHLPS(SVOp) ||
6414       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6415     return CommuteVectorShuffle(SVOp, DAG);
6416
6417   if (isShift) {
6418     // No better options. Use a vshl / vsrl.
6419     EVT EltVT = VT.getVectorElementType();
6420     ShAmt *= EltVT.getSizeInBits();
6421     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6422   }
6423
6424   bool Commuted = false;
6425   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6426   // 1,1,1,1 -> v8i16 though.
6427   V1IsSplat = isSplatVector(V1.getNode());
6428   V2IsSplat = isSplatVector(V2.getNode());
6429
6430   // Canonicalize the splat or undef, if present, to be on the RHS.
6431   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6432     Op = CommuteVectorShuffle(SVOp, DAG);
6433     SVOp = cast<ShuffleVectorSDNode>(Op);
6434     V1 = SVOp->getOperand(0);
6435     V2 = SVOp->getOperand(1);
6436     std::swap(V1IsSplat, V2IsSplat);
6437     std::swap(V1IsUndef, V2IsUndef);
6438     Commuted = true;
6439   }
6440
6441   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6442     // Shuffling low element of v1 into undef, just return v1.
6443     if (V2IsUndef)
6444       return V1;
6445     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6446     // the instruction selector will not match, so get a canonical MOVL with
6447     // swapped operands to undo the commute.
6448     return getMOVL(DAG, dl, VT, V2, V1);
6449   }
6450
6451   if (X86::isUNPCKLMask(SVOp))
6452     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6453
6454   if (X86::isUNPCKHMask(SVOp))
6455     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6456
6457   if (V2IsSplat) {
6458     // Normalize mask so all entries that point to V2 points to its first
6459     // element then try to match unpck{h|l} again. If match, return a
6460     // new vector_shuffle with the corrected mask.
6461     SDValue NewMask = NormalizeMask(SVOp, DAG);
6462     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6463     if (NSVOp != SVOp) {
6464       if (X86::isUNPCKLMask(NSVOp, true)) {
6465         return NewMask;
6466       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6467         return NewMask;
6468       }
6469     }
6470   }
6471
6472   if (Commuted) {
6473     // Commute is back and try unpck* again.
6474     // FIXME: this seems wrong.
6475     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6476     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6477
6478     if (X86::isUNPCKLMask(NewSVOp))
6479       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6480
6481     if (X86::isUNPCKHMask(NewSVOp))
6482       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6483   }
6484
6485   // Normalize the node to match x86 shuffle ops if needed
6486   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6487     return CommuteVectorShuffle(SVOp, DAG);
6488
6489   // The checks below are all present in isShuffleMaskLegal, but they are
6490   // inlined here right now to enable us to directly emit target specific
6491   // nodes, and remove one by one until they don't return Op anymore.
6492   SmallVector<int, 16> M;
6493   SVOp->getMask(M);
6494
6495   if (isPALIGNRMask(M, VT, HasSSSE3))
6496     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6497                                 X86::getShufflePALIGNRImmediate(SVOp),
6498                                 DAG);
6499
6500   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6501       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6502     if (VT == MVT::v2f64)
6503       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6504     if (VT == MVT::v2i64)
6505       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6506   }
6507
6508   if (isPSHUFHWMask(M, VT))
6509     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6510                                 X86::getShufflePSHUFHWImmediate(SVOp),
6511                                 DAG);
6512
6513   if (isPSHUFLWMask(M, VT))
6514     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6515                                 X86::getShufflePSHUFLWImmediate(SVOp),
6516                                 DAG);
6517
6518   if (isSHUFPMask(M, VT)) {
6519     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6520     if (VT == MVT::v4f32 || VT == MVT::v4i32)
6521       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
6522                                   TargetMask, DAG);
6523     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6524       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
6525                                   TargetMask, DAG);
6526   }
6527
6528   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6529     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6530   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6531     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6532
6533   //===--------------------------------------------------------------------===//
6534   // Generate target specific nodes for 128 or 256-bit shuffles only
6535   // supported in the AVX instruction set.
6536   //
6537
6538   // Handle VPERMILPS* permutations
6539   if (isVPERMILPSMask(M, VT, Subtarget))
6540     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6541                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6542
6543   // Handle VPERMILPD* permutations
6544   if (isVPERMILPDMask(M, VT, Subtarget))
6545     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6546                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6547
6548   // Handle VPERM2F128 permutations
6549   if (isVPERM2F128Mask(M, VT, Subtarget))
6550     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6551                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6552
6553   //===--------------------------------------------------------------------===//
6554   // Since no target specific shuffle was selected for this generic one,
6555   // lower it into other known shuffles. FIXME: this isn't true yet, but
6556   // this is the plan.
6557   //
6558
6559   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6560   if (VT == MVT::v8i16) {
6561     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6562     if (NewOp.getNode())
6563       return NewOp;
6564   }
6565
6566   if (VT == MVT::v16i8) {
6567     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6568     if (NewOp.getNode())
6569       return NewOp;
6570   }
6571
6572   // Handle all 128-bit wide vectors with 4 elements, and match them with
6573   // several different shuffle types.
6574   if (NumElems == 4 && VT.getSizeInBits() == 128)
6575     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6576
6577   // Handle general 256-bit shuffles
6578   if (VT.is256BitVector())
6579     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6580
6581   return SDValue();
6582 }
6583
6584 SDValue
6585 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6586                                                 SelectionDAG &DAG) const {
6587   EVT VT = Op.getValueType();
6588   DebugLoc dl = Op.getDebugLoc();
6589
6590   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6591     return SDValue();
6592
6593   if (VT.getSizeInBits() == 8) {
6594     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6595                                     Op.getOperand(0), Op.getOperand(1));
6596     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6597                                     DAG.getValueType(VT));
6598     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6599   } else if (VT.getSizeInBits() == 16) {
6600     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6601     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6602     if (Idx == 0)
6603       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6604                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6605                                      DAG.getNode(ISD::BITCAST, dl,
6606                                                  MVT::v4i32,
6607                                                  Op.getOperand(0)),
6608                                      Op.getOperand(1)));
6609     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6610                                     Op.getOperand(0), Op.getOperand(1));
6611     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6612                                     DAG.getValueType(VT));
6613     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6614   } else if (VT == MVT::f32) {
6615     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6616     // the result back to FR32 register. It's only worth matching if the
6617     // result has a single use which is a store or a bitcast to i32.  And in
6618     // the case of a store, it's not worth it if the index is a constant 0,
6619     // because a MOVSSmr can be used instead, which is smaller and faster.
6620     if (!Op.hasOneUse())
6621       return SDValue();
6622     SDNode *User = *Op.getNode()->use_begin();
6623     if ((User->getOpcode() != ISD::STORE ||
6624          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6625           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6626         (User->getOpcode() != ISD::BITCAST ||
6627          User->getValueType(0) != MVT::i32))
6628       return SDValue();
6629     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6630                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6631                                               Op.getOperand(0)),
6632                                               Op.getOperand(1));
6633     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6634   } else if (VT == MVT::i32) {
6635     // ExtractPS works with constant index.
6636     if (isa<ConstantSDNode>(Op.getOperand(1)))
6637       return Op;
6638   }
6639   return SDValue();
6640 }
6641
6642
6643 SDValue
6644 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6645                                            SelectionDAG &DAG) const {
6646   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6647     return SDValue();
6648
6649   SDValue Vec = Op.getOperand(0);
6650   EVT VecVT = Vec.getValueType();
6651
6652   // If this is a 256-bit vector result, first extract the 128-bit vector and
6653   // then extract the element from the 128-bit vector.
6654   if (VecVT.getSizeInBits() == 256) {
6655     DebugLoc dl = Op.getNode()->getDebugLoc();
6656     unsigned NumElems = VecVT.getVectorNumElements();
6657     SDValue Idx = Op.getOperand(1);
6658     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6659
6660     // Get the 128-bit vector.
6661     bool Upper = IdxVal >= NumElems/2;
6662     Vec = Extract128BitVector(Vec,
6663                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6664
6665     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6666                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6667   }
6668
6669   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6670
6671   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6672     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6673     if (Res.getNode())
6674       return Res;
6675   }
6676
6677   EVT VT = Op.getValueType();
6678   DebugLoc dl = Op.getDebugLoc();
6679   // TODO: handle v16i8.
6680   if (VT.getSizeInBits() == 16) {
6681     SDValue Vec = Op.getOperand(0);
6682     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6683     if (Idx == 0)
6684       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6685                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6686                                      DAG.getNode(ISD::BITCAST, dl,
6687                                                  MVT::v4i32, Vec),
6688                                      Op.getOperand(1)));
6689     // Transform it so it match pextrw which produces a 32-bit result.
6690     EVT EltVT = MVT::i32;
6691     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6692                                     Op.getOperand(0), Op.getOperand(1));
6693     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6694                                     DAG.getValueType(VT));
6695     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6696   } else if (VT.getSizeInBits() == 32) {
6697     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6698     if (Idx == 0)
6699       return Op;
6700
6701     // SHUFPS the element to the lowest double word, then movss.
6702     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6703     EVT VVT = Op.getOperand(0).getValueType();
6704     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6705                                        DAG.getUNDEF(VVT), Mask);
6706     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6707                        DAG.getIntPtrConstant(0));
6708   } else if (VT.getSizeInBits() == 64) {
6709     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6710     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6711     //        to match extract_elt for f64.
6712     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6713     if (Idx == 0)
6714       return Op;
6715
6716     // UNPCKHPD the element to the lowest double word, then movsd.
6717     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6718     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6719     int Mask[2] = { 1, -1 };
6720     EVT VVT = Op.getOperand(0).getValueType();
6721     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6722                                        DAG.getUNDEF(VVT), Mask);
6723     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6724                        DAG.getIntPtrConstant(0));
6725   }
6726
6727   return SDValue();
6728 }
6729
6730 SDValue
6731 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6732                                                SelectionDAG &DAG) const {
6733   EVT VT = Op.getValueType();
6734   EVT EltVT = VT.getVectorElementType();
6735   DebugLoc dl = Op.getDebugLoc();
6736
6737   SDValue N0 = Op.getOperand(0);
6738   SDValue N1 = Op.getOperand(1);
6739   SDValue N2 = Op.getOperand(2);
6740
6741   if (VT.getSizeInBits() == 256)
6742     return SDValue();
6743
6744   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6745       isa<ConstantSDNode>(N2)) {
6746     unsigned Opc;
6747     if (VT == MVT::v8i16)
6748       Opc = X86ISD::PINSRW;
6749     else if (VT == MVT::v16i8)
6750       Opc = X86ISD::PINSRB;
6751     else
6752       Opc = X86ISD::PINSRB;
6753
6754     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6755     // argument.
6756     if (N1.getValueType() != MVT::i32)
6757       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6758     if (N2.getValueType() != MVT::i32)
6759       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6760     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6761   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6762     // Bits [7:6] of the constant are the source select.  This will always be
6763     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6764     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6765     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6766     // Bits [5:4] of the constant are the destination select.  This is the
6767     //  value of the incoming immediate.
6768     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6769     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6770     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6771     // Create this as a scalar to vector..
6772     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6773     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6774   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
6775     // PINSR* works with constant index.
6776     return Op;
6777   }
6778   return SDValue();
6779 }
6780
6781 SDValue
6782 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6783   EVT VT = Op.getValueType();
6784   EVT EltVT = VT.getVectorElementType();
6785
6786   DebugLoc dl = Op.getDebugLoc();
6787   SDValue N0 = Op.getOperand(0);
6788   SDValue N1 = Op.getOperand(1);
6789   SDValue N2 = Op.getOperand(2);
6790
6791   // If this is a 256-bit vector result, first extract the 128-bit vector,
6792   // insert the element into the extracted half and then place it back.
6793   if (VT.getSizeInBits() == 256) {
6794     if (!isa<ConstantSDNode>(N2))
6795       return SDValue();
6796
6797     // Get the desired 128-bit vector half.
6798     unsigned NumElems = VT.getVectorNumElements();
6799     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6800     bool Upper = IdxVal >= NumElems/2;
6801     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6802     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6803
6804     // Insert the element into the desired half.
6805     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6806                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6807
6808     // Insert the changed part back to the 256-bit vector
6809     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6810   }
6811
6812   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
6813     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6814
6815   if (EltVT == MVT::i8)
6816     return SDValue();
6817
6818   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6819     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6820     // as its second argument.
6821     if (N1.getValueType() != MVT::i32)
6822       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6823     if (N2.getValueType() != MVT::i32)
6824       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6825     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6826   }
6827   return SDValue();
6828 }
6829
6830 SDValue
6831 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6832   LLVMContext *Context = DAG.getContext();
6833   DebugLoc dl = Op.getDebugLoc();
6834   EVT OpVT = Op.getValueType();
6835
6836   // If this is a 256-bit vector result, first insert into a 128-bit
6837   // vector and then insert into the 256-bit vector.
6838   if (OpVT.getSizeInBits() > 128) {
6839     // Insert into a 128-bit vector.
6840     EVT VT128 = EVT::getVectorVT(*Context,
6841                                  OpVT.getVectorElementType(),
6842                                  OpVT.getVectorNumElements() / 2);
6843
6844     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6845
6846     // Insert the 128-bit vector.
6847     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
6848                               DAG.getConstant(0, MVT::i32),
6849                               DAG, dl);
6850   }
6851
6852   if (Op.getValueType() == MVT::v1i64 &&
6853       Op.getOperand(0).getValueType() == MVT::i64)
6854     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6855
6856   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6857   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6858          "Expected an SSE type!");
6859   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6860                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6861 }
6862
6863 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6864 // a simple subregister reference or explicit instructions to grab
6865 // upper bits of a vector.
6866 SDValue
6867 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6868   if (Subtarget->hasAVX()) {
6869     DebugLoc dl = Op.getNode()->getDebugLoc();
6870     SDValue Vec = Op.getNode()->getOperand(0);
6871     SDValue Idx = Op.getNode()->getOperand(1);
6872
6873     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
6874         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
6875         return Extract128BitVector(Vec, Idx, DAG, dl);
6876     }
6877   }
6878   return SDValue();
6879 }
6880
6881 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6882 // simple superregister reference or explicit instructions to insert
6883 // the upper bits of a vector.
6884 SDValue
6885 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6886   if (Subtarget->hasAVX()) {
6887     DebugLoc dl = Op.getNode()->getDebugLoc();
6888     SDValue Vec = Op.getNode()->getOperand(0);
6889     SDValue SubVec = Op.getNode()->getOperand(1);
6890     SDValue Idx = Op.getNode()->getOperand(2);
6891
6892     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
6893         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
6894       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
6895     }
6896   }
6897   return SDValue();
6898 }
6899
6900 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
6901 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
6902 // one of the above mentioned nodes. It has to be wrapped because otherwise
6903 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
6904 // be used to form addressing mode. These wrapped nodes will be selected
6905 // into MOV32ri.
6906 SDValue
6907 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
6908   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6909
6910   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6911   // global base reg.
6912   unsigned char OpFlag = 0;
6913   unsigned WrapperKind = X86ISD::Wrapper;
6914   CodeModel::Model M = getTargetMachine().getCodeModel();
6915
6916   if (Subtarget->isPICStyleRIPRel() &&
6917       (M == CodeModel::Small || M == CodeModel::Kernel))
6918     WrapperKind = X86ISD::WrapperRIP;
6919   else if (Subtarget->isPICStyleGOT())
6920     OpFlag = X86II::MO_GOTOFF;
6921   else if (Subtarget->isPICStyleStubPIC())
6922     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6923
6924   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
6925                                              CP->getAlignment(),
6926                                              CP->getOffset(), OpFlag);
6927   DebugLoc DL = CP->getDebugLoc();
6928   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6929   // With PIC, the address is actually $g + Offset.
6930   if (OpFlag) {
6931     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6932                          DAG.getNode(X86ISD::GlobalBaseReg,
6933                                      DebugLoc(), getPointerTy()),
6934                          Result);
6935   }
6936
6937   return Result;
6938 }
6939
6940 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
6941   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6942
6943   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6944   // global base reg.
6945   unsigned char OpFlag = 0;
6946   unsigned WrapperKind = X86ISD::Wrapper;
6947   CodeModel::Model M = getTargetMachine().getCodeModel();
6948
6949   if (Subtarget->isPICStyleRIPRel() &&
6950       (M == CodeModel::Small || M == CodeModel::Kernel))
6951     WrapperKind = X86ISD::WrapperRIP;
6952   else if (Subtarget->isPICStyleGOT())
6953     OpFlag = X86II::MO_GOTOFF;
6954   else if (Subtarget->isPICStyleStubPIC())
6955     OpFlag = X86II::MO_PIC_BASE_OFFSET;
6956
6957   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
6958                                           OpFlag);
6959   DebugLoc DL = JT->getDebugLoc();
6960   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6961
6962   // With PIC, the address is actually $g + Offset.
6963   if (OpFlag)
6964     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6965                          DAG.getNode(X86ISD::GlobalBaseReg,
6966                                      DebugLoc(), getPointerTy()),
6967                          Result);
6968
6969   return Result;
6970 }
6971
6972 SDValue
6973 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
6974   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
6975
6976   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6977   // global base reg.
6978   unsigned char OpFlag = 0;
6979   unsigned WrapperKind = X86ISD::Wrapper;
6980   CodeModel::Model M = getTargetMachine().getCodeModel();
6981
6982   if (Subtarget->isPICStyleRIPRel() &&
6983       (M == CodeModel::Small || M == CodeModel::Kernel)) {
6984     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
6985       OpFlag = X86II::MO_GOTPCREL;
6986     WrapperKind = X86ISD::WrapperRIP;
6987   } else if (Subtarget->isPICStyleGOT()) {
6988     OpFlag = X86II::MO_GOT;
6989   } else if (Subtarget->isPICStyleStubPIC()) {
6990     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
6991   } else if (Subtarget->isPICStyleStubNoDynamic()) {
6992     OpFlag = X86II::MO_DARWIN_NONLAZY;
6993   }
6994
6995   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6996
6997   DebugLoc DL = Op.getDebugLoc();
6998   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6999
7000
7001   // With PIC, the address is actually $g + Offset.
7002   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7003       !Subtarget->is64Bit()) {
7004     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7005                          DAG.getNode(X86ISD::GlobalBaseReg,
7006                                      DebugLoc(), getPointerTy()),
7007                          Result);
7008   }
7009
7010   // For symbols that require a load from a stub to get the address, emit the
7011   // load.
7012   if (isGlobalStubReference(OpFlag))
7013     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7014                          MachinePointerInfo::getGOT(), false, false, 0);
7015
7016   return Result;
7017 }
7018
7019 SDValue
7020 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7021   // Create the TargetBlockAddressAddress node.
7022   unsigned char OpFlags =
7023     Subtarget->ClassifyBlockAddressReference();
7024   CodeModel::Model M = getTargetMachine().getCodeModel();
7025   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7026   DebugLoc dl = Op.getDebugLoc();
7027   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7028                                        /*isTarget=*/true, OpFlags);
7029
7030   if (Subtarget->isPICStyleRIPRel() &&
7031       (M == CodeModel::Small || M == CodeModel::Kernel))
7032     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7033   else
7034     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7035
7036   // With PIC, the address is actually $g + Offset.
7037   if (isGlobalRelativeToPICBase(OpFlags)) {
7038     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7039                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7040                          Result);
7041   }
7042
7043   return Result;
7044 }
7045
7046 SDValue
7047 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7048                                       int64_t Offset,
7049                                       SelectionDAG &DAG) const {
7050   // Create the TargetGlobalAddress node, folding in the constant
7051   // offset if it is legal.
7052   unsigned char OpFlags =
7053     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7054   CodeModel::Model M = getTargetMachine().getCodeModel();
7055   SDValue Result;
7056   if (OpFlags == X86II::MO_NO_FLAG &&
7057       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7058     // A direct static reference to a global.
7059     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7060     Offset = 0;
7061   } else {
7062     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7063   }
7064
7065   if (Subtarget->isPICStyleRIPRel() &&
7066       (M == CodeModel::Small || M == CodeModel::Kernel))
7067     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7068   else
7069     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7070
7071   // With PIC, the address is actually $g + Offset.
7072   if (isGlobalRelativeToPICBase(OpFlags)) {
7073     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7074                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7075                          Result);
7076   }
7077
7078   // For globals that require a load from a stub to get the address, emit the
7079   // load.
7080   if (isGlobalStubReference(OpFlags))
7081     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7082                          MachinePointerInfo::getGOT(), false, false, 0);
7083
7084   // If there was a non-zero offset that we didn't fold, create an explicit
7085   // addition for it.
7086   if (Offset != 0)
7087     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7088                          DAG.getConstant(Offset, getPointerTy()));
7089
7090   return Result;
7091 }
7092
7093 SDValue
7094 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7095   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7096   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7097   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7098 }
7099
7100 static SDValue
7101 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7102            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7103            unsigned char OperandFlags) {
7104   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7105   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7106   DebugLoc dl = GA->getDebugLoc();
7107   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7108                                            GA->getValueType(0),
7109                                            GA->getOffset(),
7110                                            OperandFlags);
7111   if (InFlag) {
7112     SDValue Ops[] = { Chain,  TGA, *InFlag };
7113     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7114   } else {
7115     SDValue Ops[]  = { Chain, TGA };
7116     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7117   }
7118
7119   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7120   MFI->setAdjustsStack(true);
7121
7122   SDValue Flag = Chain.getValue(1);
7123   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7124 }
7125
7126 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7127 static SDValue
7128 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7129                                 const EVT PtrVT) {
7130   SDValue InFlag;
7131   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7132   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7133                                      DAG.getNode(X86ISD::GlobalBaseReg,
7134                                                  DebugLoc(), PtrVT), InFlag);
7135   InFlag = Chain.getValue(1);
7136
7137   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7138 }
7139
7140 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7141 static SDValue
7142 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7143                                 const EVT PtrVT) {
7144   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7145                     X86::RAX, X86II::MO_TLSGD);
7146 }
7147
7148 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7149 // "local exec" model.
7150 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7151                                    const EVT PtrVT, TLSModel::Model model,
7152                                    bool is64Bit) {
7153   DebugLoc dl = GA->getDebugLoc();
7154
7155   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7156   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7157                                                          is64Bit ? 257 : 256));
7158
7159   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7160                                       DAG.getIntPtrConstant(0),
7161                                       MachinePointerInfo(Ptr), false, false, 0);
7162
7163   unsigned char OperandFlags = 0;
7164   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7165   // initialexec.
7166   unsigned WrapperKind = X86ISD::Wrapper;
7167   if (model == TLSModel::LocalExec) {
7168     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7169   } else if (is64Bit) {
7170     assert(model == TLSModel::InitialExec);
7171     OperandFlags = X86II::MO_GOTTPOFF;
7172     WrapperKind = X86ISD::WrapperRIP;
7173   } else {
7174     assert(model == TLSModel::InitialExec);
7175     OperandFlags = X86II::MO_INDNTPOFF;
7176   }
7177
7178   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7179   // exec)
7180   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7181                                            GA->getValueType(0),
7182                                            GA->getOffset(), OperandFlags);
7183   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7184
7185   if (model == TLSModel::InitialExec)
7186     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7187                          MachinePointerInfo::getGOT(), false, false, 0);
7188
7189   // The address of the thread local variable is the add of the thread
7190   // pointer with the offset of the variable.
7191   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7192 }
7193
7194 SDValue
7195 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7196
7197   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7198   const GlobalValue *GV = GA->getGlobal();
7199
7200   if (Subtarget->isTargetELF()) {
7201     // TODO: implement the "local dynamic" model
7202     // TODO: implement the "initial exec"model for pic executables
7203
7204     // If GV is an alias then use the aliasee for determining
7205     // thread-localness.
7206     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7207       GV = GA->resolveAliasedGlobal(false);
7208
7209     TLSModel::Model model
7210       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7211
7212     switch (model) {
7213       case TLSModel::GeneralDynamic:
7214       case TLSModel::LocalDynamic: // not implemented
7215         if (Subtarget->is64Bit())
7216           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7217         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7218
7219       case TLSModel::InitialExec:
7220       case TLSModel::LocalExec:
7221         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7222                                    Subtarget->is64Bit());
7223     }
7224   } else if (Subtarget->isTargetDarwin()) {
7225     // Darwin only has one model of TLS.  Lower to that.
7226     unsigned char OpFlag = 0;
7227     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7228                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7229
7230     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7231     // global base reg.
7232     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7233                   !Subtarget->is64Bit();
7234     if (PIC32)
7235       OpFlag = X86II::MO_TLVP_PIC_BASE;
7236     else
7237       OpFlag = X86II::MO_TLVP;
7238     DebugLoc DL = Op.getDebugLoc();
7239     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7240                                                 GA->getValueType(0),
7241                                                 GA->getOffset(), OpFlag);
7242     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7243
7244     // With PIC32, the address is actually $g + Offset.
7245     if (PIC32)
7246       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7247                            DAG.getNode(X86ISD::GlobalBaseReg,
7248                                        DebugLoc(), getPointerTy()),
7249                            Offset);
7250
7251     // Lowering the machine isd will make sure everything is in the right
7252     // location.
7253     SDValue Chain = DAG.getEntryNode();
7254     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7255     SDValue Args[] = { Chain, Offset };
7256     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7257
7258     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7259     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7260     MFI->setAdjustsStack(true);
7261
7262     // And our return value (tls address) is in the standard call return value
7263     // location.
7264     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7265     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7266   }
7267
7268   assert(false &&
7269          "TLS not implemented for this target.");
7270
7271   llvm_unreachable("Unreachable");
7272   return SDValue();
7273 }
7274
7275
7276 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7277 /// take a 2 x i32 value to shift plus a shift amount.
7278 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7279   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7280   EVT VT = Op.getValueType();
7281   unsigned VTBits = VT.getSizeInBits();
7282   DebugLoc dl = Op.getDebugLoc();
7283   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7284   SDValue ShOpLo = Op.getOperand(0);
7285   SDValue ShOpHi = Op.getOperand(1);
7286   SDValue ShAmt  = Op.getOperand(2);
7287   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7288                                      DAG.getConstant(VTBits - 1, MVT::i8))
7289                        : DAG.getConstant(0, VT);
7290
7291   SDValue Tmp2, Tmp3;
7292   if (Op.getOpcode() == ISD::SHL_PARTS) {
7293     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7294     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7295   } else {
7296     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7297     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7298   }
7299
7300   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7301                                 DAG.getConstant(VTBits, MVT::i8));
7302   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7303                              AndNode, DAG.getConstant(0, MVT::i8));
7304
7305   SDValue Hi, Lo;
7306   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7307   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7308   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7309
7310   if (Op.getOpcode() == ISD::SHL_PARTS) {
7311     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7312     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7313   } else {
7314     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7315     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7316   }
7317
7318   SDValue Ops[2] = { Lo, Hi };
7319   return DAG.getMergeValues(Ops, 2, dl);
7320 }
7321
7322 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7323                                            SelectionDAG &DAG) const {
7324   EVT SrcVT = Op.getOperand(0).getValueType();
7325
7326   if (SrcVT.isVector())
7327     return SDValue();
7328
7329   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7330          "Unknown SINT_TO_FP to lower!");
7331
7332   // These are really Legal; return the operand so the caller accepts it as
7333   // Legal.
7334   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7335     return Op;
7336   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7337       Subtarget->is64Bit()) {
7338     return Op;
7339   }
7340
7341   DebugLoc dl = Op.getDebugLoc();
7342   unsigned Size = SrcVT.getSizeInBits()/8;
7343   MachineFunction &MF = DAG.getMachineFunction();
7344   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7345   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7346   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7347                                StackSlot,
7348                                MachinePointerInfo::getFixedStack(SSFI),
7349                                false, false, 0);
7350   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7351 }
7352
7353 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7354                                      SDValue StackSlot,
7355                                      SelectionDAG &DAG) const {
7356   // Build the FILD
7357   DebugLoc DL = Op.getDebugLoc();
7358   SDVTList Tys;
7359   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7360   if (useSSE)
7361     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7362   else
7363     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7364
7365   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7366
7367   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7368   MachineMemOperand *MMO;
7369   if (FI) {
7370     int SSFI = FI->getIndex();
7371     MMO =
7372       DAG.getMachineFunction()
7373       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7374                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7375   } else {
7376     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7377     StackSlot = StackSlot.getOperand(1);
7378   }
7379   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7380   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7381                                            X86ISD::FILD, DL,
7382                                            Tys, Ops, array_lengthof(Ops),
7383                                            SrcVT, MMO);
7384
7385   if (useSSE) {
7386     Chain = Result.getValue(1);
7387     SDValue InFlag = Result.getValue(2);
7388
7389     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7390     // shouldn't be necessary except that RFP cannot be live across
7391     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7392     MachineFunction &MF = DAG.getMachineFunction();
7393     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7394     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7395     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7396     Tys = DAG.getVTList(MVT::Other);
7397     SDValue Ops[] = {
7398       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7399     };
7400     MachineMemOperand *MMO =
7401       DAG.getMachineFunction()
7402       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7403                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7404
7405     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7406                                     Ops, array_lengthof(Ops),
7407                                     Op.getValueType(), MMO);
7408     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7409                          MachinePointerInfo::getFixedStack(SSFI),
7410                          false, false, 0);
7411   }
7412
7413   return Result;
7414 }
7415
7416 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7417 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7418                                                SelectionDAG &DAG) const {
7419   // This algorithm is not obvious. Here it is in C code, more or less:
7420   /*
7421     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7422       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7423       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7424
7425       // Copy ints to xmm registers.
7426       __m128i xh = _mm_cvtsi32_si128( hi );
7427       __m128i xl = _mm_cvtsi32_si128( lo );
7428
7429       // Combine into low half of a single xmm register.
7430       __m128i x = _mm_unpacklo_epi32( xh, xl );
7431       __m128d d;
7432       double sd;
7433
7434       // Merge in appropriate exponents to give the integer bits the right
7435       // magnitude.
7436       x = _mm_unpacklo_epi32( x, exp );
7437
7438       // Subtract away the biases to deal with the IEEE-754 double precision
7439       // implicit 1.
7440       d = _mm_sub_pd( (__m128d) x, bias );
7441
7442       // All conversions up to here are exact. The correctly rounded result is
7443       // calculated using the current rounding mode using the following
7444       // horizontal add.
7445       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7446       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7447                                 // store doesn't really need to be here (except
7448                                 // maybe to zero the other double)
7449       return sd;
7450     }
7451   */
7452
7453   DebugLoc dl = Op.getDebugLoc();
7454   LLVMContext *Context = DAG.getContext();
7455
7456   // Build some magic constants.
7457   std::vector<Constant*> CV0;
7458   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7459   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7460   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7461   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7462   Constant *C0 = ConstantVector::get(CV0);
7463   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7464
7465   std::vector<Constant*> CV1;
7466   CV1.push_back(
7467     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7468   CV1.push_back(
7469     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7470   Constant *C1 = ConstantVector::get(CV1);
7471   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7472
7473   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7474                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7475                                         Op.getOperand(0),
7476                                         DAG.getIntPtrConstant(1)));
7477   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7478                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7479                                         Op.getOperand(0),
7480                                         DAG.getIntPtrConstant(0)));
7481   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7482   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7483                               MachinePointerInfo::getConstantPool(),
7484                               false, false, 16);
7485   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7486   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7487   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7488                               MachinePointerInfo::getConstantPool(),
7489                               false, false, 16);
7490   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7491
7492   // Add the halves; easiest way is to swap them into another reg first.
7493   int ShufMask[2] = { 1, -1 };
7494   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7495                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7496   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7497   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7498                      DAG.getIntPtrConstant(0));
7499 }
7500
7501 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7502 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7503                                                SelectionDAG &DAG) const {
7504   DebugLoc dl = Op.getDebugLoc();
7505   // FP constant to bias correct the final result.
7506   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7507                                    MVT::f64);
7508
7509   // Load the 32-bit value into an XMM register.
7510   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7511                              Op.getOperand(0));
7512
7513   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7514                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7515                      DAG.getIntPtrConstant(0));
7516
7517   // Or the load with the bias.
7518   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7519                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7520                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7521                                                    MVT::v2f64, Load)),
7522                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7523                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7524                                                    MVT::v2f64, Bias)));
7525   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7526                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7527                    DAG.getIntPtrConstant(0));
7528
7529   // Subtract the bias.
7530   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7531
7532   // Handle final rounding.
7533   EVT DestVT = Op.getValueType();
7534
7535   if (DestVT.bitsLT(MVT::f64)) {
7536     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7537                        DAG.getIntPtrConstant(0));
7538   } else if (DestVT.bitsGT(MVT::f64)) {
7539     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7540   }
7541
7542   // Handle final rounding.
7543   return Sub;
7544 }
7545
7546 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7547                                            SelectionDAG &DAG) const {
7548   SDValue N0 = Op.getOperand(0);
7549   DebugLoc dl = Op.getDebugLoc();
7550
7551   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7552   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7553   // the optimization here.
7554   if (DAG.SignBitIsZero(N0))
7555     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7556
7557   EVT SrcVT = N0.getValueType();
7558   EVT DstVT = Op.getValueType();
7559   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7560     return LowerUINT_TO_FP_i64(Op, DAG);
7561   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7562     return LowerUINT_TO_FP_i32(Op, DAG);
7563
7564   // Make a 64-bit buffer, and use it to build an FILD.
7565   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7566   if (SrcVT == MVT::i32) {
7567     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7568     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7569                                      getPointerTy(), StackSlot, WordOff);
7570     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7571                                   StackSlot, MachinePointerInfo(),
7572                                   false, false, 0);
7573     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7574                                   OffsetSlot, MachinePointerInfo(),
7575                                   false, false, 0);
7576     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7577     return Fild;
7578   }
7579
7580   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7581   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7582                                 StackSlot, MachinePointerInfo(),
7583                                false, false, 0);
7584   // For i64 source, we need to add the appropriate power of 2 if the input
7585   // was negative.  This is the same as the optimization in
7586   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7587   // we must be careful to do the computation in x87 extended precision, not
7588   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7589   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7590   MachineMemOperand *MMO =
7591     DAG.getMachineFunction()
7592     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7593                           MachineMemOperand::MOLoad, 8, 8);
7594
7595   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7596   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7597   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7598                                          MVT::i64, MMO);
7599
7600   APInt FF(32, 0x5F800000ULL);
7601
7602   // Check whether the sign bit is set.
7603   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7604                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7605                                  ISD::SETLT);
7606
7607   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7608   SDValue FudgePtr = DAG.getConstantPool(
7609                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7610                                          getPointerTy());
7611
7612   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7613   SDValue Zero = DAG.getIntPtrConstant(0);
7614   SDValue Four = DAG.getIntPtrConstant(4);
7615   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7616                                Zero, Four);
7617   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7618
7619   // Load the value out, extending it from f32 to f80.
7620   // FIXME: Avoid the extend by constructing the right constant pool?
7621   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7622                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7623                                  MVT::f32, false, false, 4);
7624   // Extend everything to 80 bits to force it to be done on x87.
7625   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7626   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7627 }
7628
7629 std::pair<SDValue,SDValue> X86TargetLowering::
7630 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7631   DebugLoc DL = Op.getDebugLoc();
7632
7633   EVT DstTy = Op.getValueType();
7634
7635   if (!IsSigned) {
7636     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7637     DstTy = MVT::i64;
7638   }
7639
7640   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7641          DstTy.getSimpleVT() >= MVT::i16 &&
7642          "Unknown FP_TO_SINT to lower!");
7643
7644   // These are really Legal.
7645   if (DstTy == MVT::i32 &&
7646       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7647     return std::make_pair(SDValue(), SDValue());
7648   if (Subtarget->is64Bit() &&
7649       DstTy == MVT::i64 &&
7650       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7651     return std::make_pair(SDValue(), SDValue());
7652
7653   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7654   // stack slot.
7655   MachineFunction &MF = DAG.getMachineFunction();
7656   unsigned MemSize = DstTy.getSizeInBits()/8;
7657   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7658   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7659
7660
7661
7662   unsigned Opc;
7663   switch (DstTy.getSimpleVT().SimpleTy) {
7664   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7665   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7666   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7667   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7668   }
7669
7670   SDValue Chain = DAG.getEntryNode();
7671   SDValue Value = Op.getOperand(0);
7672   EVT TheVT = Op.getOperand(0).getValueType();
7673   if (isScalarFPTypeInSSEReg(TheVT)) {
7674     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7675     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7676                          MachinePointerInfo::getFixedStack(SSFI),
7677                          false, false, 0);
7678     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7679     SDValue Ops[] = {
7680       Chain, StackSlot, DAG.getValueType(TheVT)
7681     };
7682
7683     MachineMemOperand *MMO =
7684       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7685                               MachineMemOperand::MOLoad, MemSize, MemSize);
7686     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7687                                     DstTy, MMO);
7688     Chain = Value.getValue(1);
7689     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7690     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7691   }
7692
7693   MachineMemOperand *MMO =
7694     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7695                             MachineMemOperand::MOStore, MemSize, MemSize);
7696
7697   // Build the FP_TO_INT*_IN_MEM
7698   SDValue Ops[] = { Chain, Value, StackSlot };
7699   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7700                                          Ops, 3, DstTy, MMO);
7701
7702   return std::make_pair(FIST, StackSlot);
7703 }
7704
7705 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7706                                            SelectionDAG &DAG) const {
7707   if (Op.getValueType().isVector())
7708     return SDValue();
7709
7710   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7711   SDValue FIST = Vals.first, StackSlot = Vals.second;
7712   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7713   if (FIST.getNode() == 0) return Op;
7714
7715   // Load the result.
7716   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7717                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7718 }
7719
7720 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7721                                            SelectionDAG &DAG) const {
7722   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7723   SDValue FIST = Vals.first, StackSlot = Vals.second;
7724   assert(FIST.getNode() && "Unexpected failure");
7725
7726   // Load the result.
7727   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7728                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7729 }
7730
7731 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7732                                      SelectionDAG &DAG) const {
7733   LLVMContext *Context = DAG.getContext();
7734   DebugLoc dl = Op.getDebugLoc();
7735   EVT VT = Op.getValueType();
7736   EVT EltVT = VT;
7737   if (VT.isVector())
7738     EltVT = VT.getVectorElementType();
7739   std::vector<Constant*> CV;
7740   if (EltVT == MVT::f64) {
7741     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
7742     CV.push_back(C);
7743     CV.push_back(C);
7744   } else {
7745     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
7746     CV.push_back(C);
7747     CV.push_back(C);
7748     CV.push_back(C);
7749     CV.push_back(C);
7750   }
7751   Constant *C = ConstantVector::get(CV);
7752   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7753   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7754                              MachinePointerInfo::getConstantPool(),
7755                              false, false, 16);
7756   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7757 }
7758
7759 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7760   LLVMContext *Context = DAG.getContext();
7761   DebugLoc dl = Op.getDebugLoc();
7762   EVT VT = Op.getValueType();
7763   EVT EltVT = VT;
7764   if (VT.isVector())
7765     EltVT = VT.getVectorElementType();
7766   std::vector<Constant*> CV;
7767   if (EltVT == MVT::f64) {
7768     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7769     CV.push_back(C);
7770     CV.push_back(C);
7771   } else {
7772     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7773     CV.push_back(C);
7774     CV.push_back(C);
7775     CV.push_back(C);
7776     CV.push_back(C);
7777   }
7778   Constant *C = ConstantVector::get(CV);
7779   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7780   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7781                              MachinePointerInfo::getConstantPool(),
7782                              false, false, 16);
7783   if (VT.isVector()) {
7784     return DAG.getNode(ISD::BITCAST, dl, VT,
7785                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
7786                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7787                                 Op.getOperand(0)),
7788                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
7789   } else {
7790     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7791   }
7792 }
7793
7794 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7795   LLVMContext *Context = DAG.getContext();
7796   SDValue Op0 = Op.getOperand(0);
7797   SDValue Op1 = Op.getOperand(1);
7798   DebugLoc dl = Op.getDebugLoc();
7799   EVT VT = Op.getValueType();
7800   EVT SrcVT = Op1.getValueType();
7801
7802   // If second operand is smaller, extend it first.
7803   if (SrcVT.bitsLT(VT)) {
7804     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7805     SrcVT = VT;
7806   }
7807   // And if it is bigger, shrink it first.
7808   if (SrcVT.bitsGT(VT)) {
7809     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7810     SrcVT = VT;
7811   }
7812
7813   // At this point the operands and the result should have the same
7814   // type, and that won't be f80 since that is not custom lowered.
7815
7816   // First get the sign bit of second operand.
7817   std::vector<Constant*> CV;
7818   if (SrcVT == MVT::f64) {
7819     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7820     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7821   } else {
7822     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7823     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7824     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7825     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7826   }
7827   Constant *C = ConstantVector::get(CV);
7828   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7829   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7830                               MachinePointerInfo::getConstantPool(),
7831                               false, false, 16);
7832   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7833
7834   // Shift sign bit right or left if the two operands have different types.
7835   if (SrcVT.bitsGT(VT)) {
7836     // Op0 is MVT::f32, Op1 is MVT::f64.
7837     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7838     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7839                           DAG.getConstant(32, MVT::i32));
7840     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7841     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7842                           DAG.getIntPtrConstant(0));
7843   }
7844
7845   // Clear first operand sign bit.
7846   CV.clear();
7847   if (VT == MVT::f64) {
7848     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7849     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7850   } else {
7851     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7852     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7853     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7854     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7855   }
7856   C = ConstantVector::get(CV);
7857   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7858   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7859                               MachinePointerInfo::getConstantPool(),
7860                               false, false, 16);
7861   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7862
7863   // Or the value with the sign bit.
7864   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7865 }
7866
7867 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
7868   SDValue N0 = Op.getOperand(0);
7869   DebugLoc dl = Op.getDebugLoc();
7870   EVT VT = Op.getValueType();
7871
7872   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
7873   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
7874                                   DAG.getConstant(1, VT));
7875   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
7876 }
7877
7878 /// Emit nodes that will be selected as "test Op0,Op0", or something
7879 /// equivalent.
7880 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
7881                                     SelectionDAG &DAG) const {
7882   DebugLoc dl = Op.getDebugLoc();
7883
7884   // CF and OF aren't always set the way we want. Determine which
7885   // of these we need.
7886   bool NeedCF = false;
7887   bool NeedOF = false;
7888   switch (X86CC) {
7889   default: break;
7890   case X86::COND_A: case X86::COND_AE:
7891   case X86::COND_B: case X86::COND_BE:
7892     NeedCF = true;
7893     break;
7894   case X86::COND_G: case X86::COND_GE:
7895   case X86::COND_L: case X86::COND_LE:
7896   case X86::COND_O: case X86::COND_NO:
7897     NeedOF = true;
7898     break;
7899   }
7900
7901   // See if we can use the EFLAGS value from the operand instead of
7902   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
7903   // we prove that the arithmetic won't overflow, we can't use OF or CF.
7904   if (Op.getResNo() != 0 || NeedOF || NeedCF)
7905     // Emit a CMP with 0, which is the TEST pattern.
7906     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7907                        DAG.getConstant(0, Op.getValueType()));
7908
7909   unsigned Opcode = 0;
7910   unsigned NumOperands = 0;
7911   switch (Op.getNode()->getOpcode()) {
7912   case ISD::ADD:
7913     // Due to an isel shortcoming, be conservative if this add is likely to be
7914     // selected as part of a load-modify-store instruction. When the root node
7915     // in a match is a store, isel doesn't know how to remap non-chain non-flag
7916     // uses of other nodes in the match, such as the ADD in this case. This
7917     // leads to the ADD being left around and reselected, with the result being
7918     // two adds in the output.  Alas, even if none our users are stores, that
7919     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
7920     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
7921     // climbing the DAG back to the root, and it doesn't seem to be worth the
7922     // effort.
7923     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7924            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7925       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
7926         goto default_case;
7927
7928     if (ConstantSDNode *C =
7929         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
7930       // An add of one will be selected as an INC.
7931       if (C->getAPIntValue() == 1) {
7932         Opcode = X86ISD::INC;
7933         NumOperands = 1;
7934         break;
7935       }
7936
7937       // An add of negative one (subtract of one) will be selected as a DEC.
7938       if (C->getAPIntValue().isAllOnesValue()) {
7939         Opcode = X86ISD::DEC;
7940         NumOperands = 1;
7941         break;
7942       }
7943     }
7944
7945     // Otherwise use a regular EFLAGS-setting add.
7946     Opcode = X86ISD::ADD;
7947     NumOperands = 2;
7948     break;
7949   case ISD::AND: {
7950     // If the primary and result isn't used, don't bother using X86ISD::AND,
7951     // because a TEST instruction will be better.
7952     bool NonFlagUse = false;
7953     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7954            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
7955       SDNode *User = *UI;
7956       unsigned UOpNo = UI.getOperandNo();
7957       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
7958         // Look pass truncate.
7959         UOpNo = User->use_begin().getOperandNo();
7960         User = *User->use_begin();
7961       }
7962
7963       if (User->getOpcode() != ISD::BRCOND &&
7964           User->getOpcode() != ISD::SETCC &&
7965           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
7966         NonFlagUse = true;
7967         break;
7968       }
7969     }
7970
7971     if (!NonFlagUse)
7972       break;
7973   }
7974     // FALL THROUGH
7975   case ISD::SUB:
7976   case ISD::OR:
7977   case ISD::XOR:
7978     // Due to the ISEL shortcoming noted above, be conservative if this op is
7979     // likely to be selected as part of a load-modify-store instruction.
7980     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
7981            UE = Op.getNode()->use_end(); UI != UE; ++UI)
7982       if (UI->getOpcode() == ISD::STORE)
7983         goto default_case;
7984
7985     // Otherwise use a regular EFLAGS-setting instruction.
7986     switch (Op.getNode()->getOpcode()) {
7987     default: llvm_unreachable("unexpected operator!");
7988     case ISD::SUB: Opcode = X86ISD::SUB; break;
7989     case ISD::OR:  Opcode = X86ISD::OR;  break;
7990     case ISD::XOR: Opcode = X86ISD::XOR; break;
7991     case ISD::AND: Opcode = X86ISD::AND; break;
7992     }
7993
7994     NumOperands = 2;
7995     break;
7996   case X86ISD::ADD:
7997   case X86ISD::SUB:
7998   case X86ISD::INC:
7999   case X86ISD::DEC:
8000   case X86ISD::OR:
8001   case X86ISD::XOR:
8002   case X86ISD::AND:
8003     return SDValue(Op.getNode(), 1);
8004   default:
8005   default_case:
8006     break;
8007   }
8008
8009   if (Opcode == 0)
8010     // Emit a CMP with 0, which is the TEST pattern.
8011     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8012                        DAG.getConstant(0, Op.getValueType()));
8013
8014   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8015   SmallVector<SDValue, 4> Ops;
8016   for (unsigned i = 0; i != NumOperands; ++i)
8017     Ops.push_back(Op.getOperand(i));
8018
8019   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8020   DAG.ReplaceAllUsesWith(Op, New);
8021   return SDValue(New.getNode(), 1);
8022 }
8023
8024 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8025 /// equivalent.
8026 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8027                                    SelectionDAG &DAG) const {
8028   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8029     if (C->getAPIntValue() == 0)
8030       return EmitTest(Op0, X86CC, DAG);
8031
8032   DebugLoc dl = Op0.getDebugLoc();
8033   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8034 }
8035
8036 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8037 /// if it's possible.
8038 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8039                                      DebugLoc dl, SelectionDAG &DAG) const {
8040   SDValue Op0 = And.getOperand(0);
8041   SDValue Op1 = And.getOperand(1);
8042   if (Op0.getOpcode() == ISD::TRUNCATE)
8043     Op0 = Op0.getOperand(0);
8044   if (Op1.getOpcode() == ISD::TRUNCATE)
8045     Op1 = Op1.getOperand(0);
8046
8047   SDValue LHS, RHS;
8048   if (Op1.getOpcode() == ISD::SHL)
8049     std::swap(Op0, Op1);
8050   if (Op0.getOpcode() == ISD::SHL) {
8051     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8052       if (And00C->getZExtValue() == 1) {
8053         // If we looked past a truncate, check that it's only truncating away
8054         // known zeros.
8055         unsigned BitWidth = Op0.getValueSizeInBits();
8056         unsigned AndBitWidth = And.getValueSizeInBits();
8057         if (BitWidth > AndBitWidth) {
8058           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8059           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8060           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8061             return SDValue();
8062         }
8063         LHS = Op1;
8064         RHS = Op0.getOperand(1);
8065       }
8066   } else if (Op1.getOpcode() == ISD::Constant) {
8067     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8068     SDValue AndLHS = Op0;
8069     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8070       LHS = AndLHS.getOperand(0);
8071       RHS = AndLHS.getOperand(1);
8072     }
8073   }
8074
8075   if (LHS.getNode()) {
8076     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8077     // instruction.  Since the shift amount is in-range-or-undefined, we know
8078     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8079     // the encoding for the i16 version is larger than the i32 version.
8080     // Also promote i16 to i32 for performance / code size reason.
8081     if (LHS.getValueType() == MVT::i8 ||
8082         LHS.getValueType() == MVT::i16)
8083       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8084
8085     // If the operand types disagree, extend the shift amount to match.  Since
8086     // BT ignores high bits (like shifts) we can use anyextend.
8087     if (LHS.getValueType() != RHS.getValueType())
8088       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8089
8090     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8091     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8092     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8093                        DAG.getConstant(Cond, MVT::i8), BT);
8094   }
8095
8096   return SDValue();
8097 }
8098
8099 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8100   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8101   SDValue Op0 = Op.getOperand(0);
8102   SDValue Op1 = Op.getOperand(1);
8103   DebugLoc dl = Op.getDebugLoc();
8104   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8105
8106   // Optimize to BT if possible.
8107   // Lower (X & (1 << N)) == 0 to BT(X, N).
8108   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8109   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8110   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8111       Op1.getOpcode() == ISD::Constant &&
8112       cast<ConstantSDNode>(Op1)->isNullValue() &&
8113       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8114     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8115     if (NewSetCC.getNode())
8116       return NewSetCC;
8117   }
8118
8119   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8120   // these.
8121   if (Op1.getOpcode() == ISD::Constant &&
8122       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8123        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8124       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8125
8126     // If the input is a setcc, then reuse the input setcc or use a new one with
8127     // the inverted condition.
8128     if (Op0.getOpcode() == X86ISD::SETCC) {
8129       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8130       bool Invert = (CC == ISD::SETNE) ^
8131         cast<ConstantSDNode>(Op1)->isNullValue();
8132       if (!Invert) return Op0;
8133
8134       CCode = X86::GetOppositeBranchCondition(CCode);
8135       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8136                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8137     }
8138   }
8139
8140   bool isFP = Op1.getValueType().isFloatingPoint();
8141   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8142   if (X86CC == X86::COND_INVALID)
8143     return SDValue();
8144
8145   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8146   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8147                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8148 }
8149
8150 // Lower256IntVETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8151 // ones, and then concatenate the result back.
8152 static SDValue Lower256IntVETCC(SDValue Op, SelectionDAG &DAG) {
8153   EVT VT = Op.getValueType();
8154
8155   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::VSETCC &&
8156          "Unsupported value type for operation");
8157
8158   int NumElems = VT.getVectorNumElements();
8159   DebugLoc dl = Op.getDebugLoc();
8160   SDValue CC = Op.getOperand(2);
8161   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8162   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8163
8164   // Extract the LHS vectors
8165   SDValue LHS = Op.getOperand(0);
8166   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8167   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8168
8169   // Extract the RHS vectors
8170   SDValue RHS = Op.getOperand(1);
8171   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8172   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8173
8174   // Issue the operation on the smaller types and concatenate the result back
8175   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8176   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8177   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8178                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8179                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8180 }
8181
8182
8183 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8184   SDValue Cond;
8185   SDValue Op0 = Op.getOperand(0);
8186   SDValue Op1 = Op.getOperand(1);
8187   SDValue CC = Op.getOperand(2);
8188   EVT VT = Op.getValueType();
8189   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8190   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8191   DebugLoc dl = Op.getDebugLoc();
8192
8193   if (isFP) {
8194     unsigned SSECC = 8;
8195     EVT EltVT = Op0.getValueType().getVectorElementType();
8196     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8197
8198     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8199     bool Swap = false;
8200
8201     switch (SetCCOpcode) {
8202     default: break;
8203     case ISD::SETOEQ:
8204     case ISD::SETEQ:  SSECC = 0; break;
8205     case ISD::SETOGT:
8206     case ISD::SETGT: Swap = true; // Fallthrough
8207     case ISD::SETLT:
8208     case ISD::SETOLT: SSECC = 1; break;
8209     case ISD::SETOGE:
8210     case ISD::SETGE: Swap = true; // Fallthrough
8211     case ISD::SETLE:
8212     case ISD::SETOLE: SSECC = 2; break;
8213     case ISD::SETUO:  SSECC = 3; break;
8214     case ISD::SETUNE:
8215     case ISD::SETNE:  SSECC = 4; break;
8216     case ISD::SETULE: Swap = true;
8217     case ISD::SETUGE: SSECC = 5; break;
8218     case ISD::SETULT: Swap = true;
8219     case ISD::SETUGT: SSECC = 6; break;
8220     case ISD::SETO:   SSECC = 7; break;
8221     }
8222     if (Swap)
8223       std::swap(Op0, Op1);
8224
8225     // In the two special cases we can't handle, emit two comparisons.
8226     if (SSECC == 8) {
8227       if (SetCCOpcode == ISD::SETUEQ) {
8228         SDValue UNORD, EQ;
8229         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8230         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8231         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8232       }
8233       else if (SetCCOpcode == ISD::SETONE) {
8234         SDValue ORD, NEQ;
8235         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8236         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8237         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8238       }
8239       llvm_unreachable("Illegal FP comparison");
8240     }
8241     // Handle all other FP comparisons here.
8242     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8243   }
8244
8245   // Break 256-bit integer vector compare into smaller ones.
8246   if (!isFP && VT.getSizeInBits() == 256)
8247     return Lower256IntVETCC(Op, DAG);
8248
8249   // We are handling one of the integer comparisons here.  Since SSE only has
8250   // GT and EQ comparisons for integer, swapping operands and multiple
8251   // operations may be required for some comparisons.
8252   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8253   bool Swap = false, Invert = false, FlipSigns = false;
8254
8255   switch (VT.getSimpleVT().SimpleTy) {
8256   default: break;
8257   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8258   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8259   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8260   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8261   }
8262
8263   switch (SetCCOpcode) {
8264   default: break;
8265   case ISD::SETNE:  Invert = true;
8266   case ISD::SETEQ:  Opc = EQOpc; break;
8267   case ISD::SETLT:  Swap = true;
8268   case ISD::SETGT:  Opc = GTOpc; break;
8269   case ISD::SETGE:  Swap = true;
8270   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8271   case ISD::SETULT: Swap = true;
8272   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8273   case ISD::SETUGE: Swap = true;
8274   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8275   }
8276   if (Swap)
8277     std::swap(Op0, Op1);
8278
8279   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8280   // bits of the inputs before performing those operations.
8281   if (FlipSigns) {
8282     EVT EltVT = VT.getVectorElementType();
8283     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8284                                       EltVT);
8285     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8286     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8287                                     SignBits.size());
8288     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8289     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8290   }
8291
8292   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8293
8294   // If the logical-not of the result is required, perform that now.
8295   if (Invert)
8296     Result = DAG.getNOT(dl, Result, VT);
8297
8298   return Result;
8299 }
8300
8301 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8302 static bool isX86LogicalCmp(SDValue Op) {
8303   unsigned Opc = Op.getNode()->getOpcode();
8304   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8305     return true;
8306   if (Op.getResNo() == 1 &&
8307       (Opc == X86ISD::ADD ||
8308        Opc == X86ISD::SUB ||
8309        Opc == X86ISD::ADC ||
8310        Opc == X86ISD::SBB ||
8311        Opc == X86ISD::SMUL ||
8312        Opc == X86ISD::UMUL ||
8313        Opc == X86ISD::INC ||
8314        Opc == X86ISD::DEC ||
8315        Opc == X86ISD::OR ||
8316        Opc == X86ISD::XOR ||
8317        Opc == X86ISD::AND))
8318     return true;
8319
8320   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8321     return true;
8322
8323   return false;
8324 }
8325
8326 static bool isZero(SDValue V) {
8327   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8328   return C && C->isNullValue();
8329 }
8330
8331 static bool isAllOnes(SDValue V) {
8332   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8333   return C && C->isAllOnesValue();
8334 }
8335
8336 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8337   bool addTest = true;
8338   SDValue Cond  = Op.getOperand(0);
8339   SDValue Op1 = Op.getOperand(1);
8340   SDValue Op2 = Op.getOperand(2);
8341   DebugLoc DL = Op.getDebugLoc();
8342   SDValue CC;
8343
8344   if (Cond.getOpcode() == ISD::SETCC) {
8345     SDValue NewCond = LowerSETCC(Cond, DAG);
8346     if (NewCond.getNode())
8347       Cond = NewCond;
8348   }
8349
8350   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8351   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8352   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8353   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8354   if (Cond.getOpcode() == X86ISD::SETCC &&
8355       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8356       isZero(Cond.getOperand(1).getOperand(1))) {
8357     SDValue Cmp = Cond.getOperand(1);
8358
8359     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8360
8361     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8362         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8363       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8364
8365       SDValue CmpOp0 = Cmp.getOperand(0);
8366       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8367                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8368
8369       SDValue Res =   // Res = 0 or -1.
8370         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8371                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8372
8373       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8374         Res = DAG.getNOT(DL, Res, Res.getValueType());
8375
8376       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8377       if (N2C == 0 || !N2C->isNullValue())
8378         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8379       return Res;
8380     }
8381   }
8382
8383   // Look past (and (setcc_carry (cmp ...)), 1).
8384   if (Cond.getOpcode() == ISD::AND &&
8385       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8386     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8387     if (C && C->getAPIntValue() == 1)
8388       Cond = Cond.getOperand(0);
8389   }
8390
8391   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8392   // setting operand in place of the X86ISD::SETCC.
8393   if (Cond.getOpcode() == X86ISD::SETCC ||
8394       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8395     CC = Cond.getOperand(0);
8396
8397     SDValue Cmp = Cond.getOperand(1);
8398     unsigned Opc = Cmp.getOpcode();
8399     EVT VT = Op.getValueType();
8400
8401     bool IllegalFPCMov = false;
8402     if (VT.isFloatingPoint() && !VT.isVector() &&
8403         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8404       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8405
8406     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8407         Opc == X86ISD::BT) { // FIXME
8408       Cond = Cmp;
8409       addTest = false;
8410     }
8411   }
8412
8413   if (addTest) {
8414     // Look pass the truncate.
8415     if (Cond.getOpcode() == ISD::TRUNCATE)
8416       Cond = Cond.getOperand(0);
8417
8418     // We know the result of AND is compared against zero. Try to match
8419     // it to BT.
8420     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8421       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8422       if (NewSetCC.getNode()) {
8423         CC = NewSetCC.getOperand(0);
8424         Cond = NewSetCC.getOperand(1);
8425         addTest = false;
8426       }
8427     }
8428   }
8429
8430   if (addTest) {
8431     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8432     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8433   }
8434
8435   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8436   // a <  b ?  0 : -1 -> RES = setcc_carry
8437   // a >= b ? -1 :  0 -> RES = setcc_carry
8438   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8439   if (Cond.getOpcode() == X86ISD::CMP) {
8440     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8441
8442     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8443         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8444       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8445                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8446       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8447         return DAG.getNOT(DL, Res, Res.getValueType());
8448       return Res;
8449     }
8450   }
8451
8452   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8453   // condition is true.
8454   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8455   SDValue Ops[] = { Op2, Op1, CC, Cond };
8456   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8457 }
8458
8459 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8460 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8461 // from the AND / OR.
8462 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8463   Opc = Op.getOpcode();
8464   if (Opc != ISD::OR && Opc != ISD::AND)
8465     return false;
8466   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8467           Op.getOperand(0).hasOneUse() &&
8468           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8469           Op.getOperand(1).hasOneUse());
8470 }
8471
8472 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8473 // 1 and that the SETCC node has a single use.
8474 static bool isXor1OfSetCC(SDValue Op) {
8475   if (Op.getOpcode() != ISD::XOR)
8476     return false;
8477   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8478   if (N1C && N1C->getAPIntValue() == 1) {
8479     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8480       Op.getOperand(0).hasOneUse();
8481   }
8482   return false;
8483 }
8484
8485 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8486   bool addTest = true;
8487   SDValue Chain = Op.getOperand(0);
8488   SDValue Cond  = Op.getOperand(1);
8489   SDValue Dest  = Op.getOperand(2);
8490   DebugLoc dl = Op.getDebugLoc();
8491   SDValue CC;
8492
8493   if (Cond.getOpcode() == ISD::SETCC) {
8494     SDValue NewCond = LowerSETCC(Cond, DAG);
8495     if (NewCond.getNode())
8496       Cond = NewCond;
8497   }
8498 #if 0
8499   // FIXME: LowerXALUO doesn't handle these!!
8500   else if (Cond.getOpcode() == X86ISD::ADD  ||
8501            Cond.getOpcode() == X86ISD::SUB  ||
8502            Cond.getOpcode() == X86ISD::SMUL ||
8503            Cond.getOpcode() == X86ISD::UMUL)
8504     Cond = LowerXALUO(Cond, DAG);
8505 #endif
8506
8507   // Look pass (and (setcc_carry (cmp ...)), 1).
8508   if (Cond.getOpcode() == ISD::AND &&
8509       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8510     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8511     if (C && C->getAPIntValue() == 1)
8512       Cond = Cond.getOperand(0);
8513   }
8514
8515   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8516   // setting operand in place of the X86ISD::SETCC.
8517   if (Cond.getOpcode() == X86ISD::SETCC ||
8518       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8519     CC = Cond.getOperand(0);
8520
8521     SDValue Cmp = Cond.getOperand(1);
8522     unsigned Opc = Cmp.getOpcode();
8523     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8524     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8525       Cond = Cmp;
8526       addTest = false;
8527     } else {
8528       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8529       default: break;
8530       case X86::COND_O:
8531       case X86::COND_B:
8532         // These can only come from an arithmetic instruction with overflow,
8533         // e.g. SADDO, UADDO.
8534         Cond = Cond.getNode()->getOperand(1);
8535         addTest = false;
8536         break;
8537       }
8538     }
8539   } else {
8540     unsigned CondOpc;
8541     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8542       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8543       if (CondOpc == ISD::OR) {
8544         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8545         // two branches instead of an explicit OR instruction with a
8546         // separate test.
8547         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8548             isX86LogicalCmp(Cmp)) {
8549           CC = Cond.getOperand(0).getOperand(0);
8550           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8551                               Chain, Dest, CC, Cmp);
8552           CC = Cond.getOperand(1).getOperand(0);
8553           Cond = Cmp;
8554           addTest = false;
8555         }
8556       } else { // ISD::AND
8557         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8558         // two branches instead of an explicit AND instruction with a
8559         // separate test. However, we only do this if this block doesn't
8560         // have a fall-through edge, because this requires an explicit
8561         // jmp when the condition is false.
8562         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8563             isX86LogicalCmp(Cmp) &&
8564             Op.getNode()->hasOneUse()) {
8565           X86::CondCode CCode =
8566             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8567           CCode = X86::GetOppositeBranchCondition(CCode);
8568           CC = DAG.getConstant(CCode, MVT::i8);
8569           SDNode *User = *Op.getNode()->use_begin();
8570           // Look for an unconditional branch following this conditional branch.
8571           // We need this because we need to reverse the successors in order
8572           // to implement FCMP_OEQ.
8573           if (User->getOpcode() == ISD::BR) {
8574             SDValue FalseBB = User->getOperand(1);
8575             SDNode *NewBR =
8576               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8577             assert(NewBR == User);
8578             (void)NewBR;
8579             Dest = FalseBB;
8580
8581             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8582                                 Chain, Dest, CC, Cmp);
8583             X86::CondCode CCode =
8584               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8585             CCode = X86::GetOppositeBranchCondition(CCode);
8586             CC = DAG.getConstant(CCode, MVT::i8);
8587             Cond = Cmp;
8588             addTest = false;
8589           }
8590         }
8591       }
8592     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8593       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8594       // It should be transformed during dag combiner except when the condition
8595       // is set by a arithmetics with overflow node.
8596       X86::CondCode CCode =
8597         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8598       CCode = X86::GetOppositeBranchCondition(CCode);
8599       CC = DAG.getConstant(CCode, MVT::i8);
8600       Cond = Cond.getOperand(0).getOperand(1);
8601       addTest = false;
8602     }
8603   }
8604
8605   if (addTest) {
8606     // Look pass the truncate.
8607     if (Cond.getOpcode() == ISD::TRUNCATE)
8608       Cond = Cond.getOperand(0);
8609
8610     // We know the result of AND is compared against zero. Try to match
8611     // it to BT.
8612     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8613       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8614       if (NewSetCC.getNode()) {
8615         CC = NewSetCC.getOperand(0);
8616         Cond = NewSetCC.getOperand(1);
8617         addTest = false;
8618       }
8619     }
8620   }
8621
8622   if (addTest) {
8623     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8624     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8625   }
8626   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8627                      Chain, Dest, CC, Cond);
8628 }
8629
8630
8631 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8632 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8633 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8634 // that the guard pages used by the OS virtual memory manager are allocated in
8635 // correct sequence.
8636 SDValue
8637 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8638                                            SelectionDAG &DAG) const {
8639   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
8640          "This should be used only on Windows targets");
8641   assert(!Subtarget->isTargetEnvMacho());
8642   DebugLoc dl = Op.getDebugLoc();
8643
8644   // Get the inputs.
8645   SDValue Chain = Op.getOperand(0);
8646   SDValue Size  = Op.getOperand(1);
8647   // FIXME: Ensure alignment here
8648
8649   SDValue Flag;
8650
8651   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
8652   unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8653
8654   Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8655   Flag = Chain.getValue(1);
8656
8657   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8658
8659   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8660   Flag = Chain.getValue(1);
8661
8662   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8663
8664   SDValue Ops1[2] = { Chain.getValue(0), Chain };
8665   return DAG.getMergeValues(Ops1, 2, dl);
8666 }
8667
8668 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8669   MachineFunction &MF = DAG.getMachineFunction();
8670   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8671
8672   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8673   DebugLoc DL = Op.getDebugLoc();
8674
8675   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8676     // vastart just stores the address of the VarArgsFrameIndex slot into the
8677     // memory location argument.
8678     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8679                                    getPointerTy());
8680     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8681                         MachinePointerInfo(SV), false, false, 0);
8682   }
8683
8684   // __va_list_tag:
8685   //   gp_offset         (0 - 6 * 8)
8686   //   fp_offset         (48 - 48 + 8 * 16)
8687   //   overflow_arg_area (point to parameters coming in memory).
8688   //   reg_save_area
8689   SmallVector<SDValue, 8> MemOps;
8690   SDValue FIN = Op.getOperand(1);
8691   // Store gp_offset
8692   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
8693                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
8694                                                MVT::i32),
8695                                FIN, MachinePointerInfo(SV), false, false, 0);
8696   MemOps.push_back(Store);
8697
8698   // Store fp_offset
8699   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8700                     FIN, DAG.getIntPtrConstant(4));
8701   Store = DAG.getStore(Op.getOperand(0), DL,
8702                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
8703                                        MVT::i32),
8704                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
8705   MemOps.push_back(Store);
8706
8707   // Store ptr to overflow_arg_area
8708   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8709                     FIN, DAG.getIntPtrConstant(4));
8710   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8711                                     getPointerTy());
8712   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
8713                        MachinePointerInfo(SV, 8),
8714                        false, false, 0);
8715   MemOps.push_back(Store);
8716
8717   // Store ptr to reg_save_area.
8718   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8719                     FIN, DAG.getIntPtrConstant(8));
8720   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
8721                                     getPointerTy());
8722   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
8723                        MachinePointerInfo(SV, 16), false, false, 0);
8724   MemOps.push_back(Store);
8725   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8726                      &MemOps[0], MemOps.size());
8727 }
8728
8729 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8730   assert(Subtarget->is64Bit() &&
8731          "LowerVAARG only handles 64-bit va_arg!");
8732   assert((Subtarget->isTargetLinux() ||
8733           Subtarget->isTargetDarwin()) &&
8734           "Unhandled target in LowerVAARG");
8735   assert(Op.getNode()->getNumOperands() == 4);
8736   SDValue Chain = Op.getOperand(0);
8737   SDValue SrcPtr = Op.getOperand(1);
8738   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8739   unsigned Align = Op.getConstantOperandVal(3);
8740   DebugLoc dl = Op.getDebugLoc();
8741
8742   EVT ArgVT = Op.getNode()->getValueType(0);
8743   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8744   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
8745   uint8_t ArgMode;
8746
8747   // Decide which area this value should be read from.
8748   // TODO: Implement the AMD64 ABI in its entirety. This simple
8749   // selection mechanism works only for the basic types.
8750   if (ArgVT == MVT::f80) {
8751     llvm_unreachable("va_arg for f80 not yet implemented");
8752   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
8753     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
8754   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
8755     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
8756   } else {
8757     llvm_unreachable("Unhandled argument type in LowerVAARG");
8758   }
8759
8760   if (ArgMode == 2) {
8761     // Sanity Check: Make sure using fp_offset makes sense.
8762     assert(!UseSoftFloat &&
8763            !(DAG.getMachineFunction()
8764                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
8765            Subtarget->hasXMM());
8766   }
8767
8768   // Insert VAARG_64 node into the DAG
8769   // VAARG_64 returns two values: Variable Argument Address, Chain
8770   SmallVector<SDValue, 11> InstOps;
8771   InstOps.push_back(Chain);
8772   InstOps.push_back(SrcPtr);
8773   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
8774   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
8775   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
8776   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
8777   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
8778                                           VTs, &InstOps[0], InstOps.size(),
8779                                           MVT::i64,
8780                                           MachinePointerInfo(SV),
8781                                           /*Align=*/0,
8782                                           /*Volatile=*/false,
8783                                           /*ReadMem=*/true,
8784                                           /*WriteMem=*/true);
8785   Chain = VAARG.getValue(1);
8786
8787   // Load the next argument and return it
8788   return DAG.getLoad(ArgVT, dl,
8789                      Chain,
8790                      VAARG,
8791                      MachinePointerInfo(),
8792                      false, false, 0);
8793 }
8794
8795 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
8796   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
8797   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
8798   SDValue Chain = Op.getOperand(0);
8799   SDValue DstPtr = Op.getOperand(1);
8800   SDValue SrcPtr = Op.getOperand(2);
8801   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8802   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8803   DebugLoc DL = Op.getDebugLoc();
8804
8805   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
8806                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
8807                        false,
8808                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
8809 }
8810
8811 SDValue
8812 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
8813   DebugLoc dl = Op.getDebugLoc();
8814   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8815   switch (IntNo) {
8816   default: return SDValue();    // Don't custom lower most intrinsics.
8817   // Comparison intrinsics.
8818   case Intrinsic::x86_sse_comieq_ss:
8819   case Intrinsic::x86_sse_comilt_ss:
8820   case Intrinsic::x86_sse_comile_ss:
8821   case Intrinsic::x86_sse_comigt_ss:
8822   case Intrinsic::x86_sse_comige_ss:
8823   case Intrinsic::x86_sse_comineq_ss:
8824   case Intrinsic::x86_sse_ucomieq_ss:
8825   case Intrinsic::x86_sse_ucomilt_ss:
8826   case Intrinsic::x86_sse_ucomile_ss:
8827   case Intrinsic::x86_sse_ucomigt_ss:
8828   case Intrinsic::x86_sse_ucomige_ss:
8829   case Intrinsic::x86_sse_ucomineq_ss:
8830   case Intrinsic::x86_sse2_comieq_sd:
8831   case Intrinsic::x86_sse2_comilt_sd:
8832   case Intrinsic::x86_sse2_comile_sd:
8833   case Intrinsic::x86_sse2_comigt_sd:
8834   case Intrinsic::x86_sse2_comige_sd:
8835   case Intrinsic::x86_sse2_comineq_sd:
8836   case Intrinsic::x86_sse2_ucomieq_sd:
8837   case Intrinsic::x86_sse2_ucomilt_sd:
8838   case Intrinsic::x86_sse2_ucomile_sd:
8839   case Intrinsic::x86_sse2_ucomigt_sd:
8840   case Intrinsic::x86_sse2_ucomige_sd:
8841   case Intrinsic::x86_sse2_ucomineq_sd: {
8842     unsigned Opc = 0;
8843     ISD::CondCode CC = ISD::SETCC_INVALID;
8844     switch (IntNo) {
8845     default: break;
8846     case Intrinsic::x86_sse_comieq_ss:
8847     case Intrinsic::x86_sse2_comieq_sd:
8848       Opc = X86ISD::COMI;
8849       CC = ISD::SETEQ;
8850       break;
8851     case Intrinsic::x86_sse_comilt_ss:
8852     case Intrinsic::x86_sse2_comilt_sd:
8853       Opc = X86ISD::COMI;
8854       CC = ISD::SETLT;
8855       break;
8856     case Intrinsic::x86_sse_comile_ss:
8857     case Intrinsic::x86_sse2_comile_sd:
8858       Opc = X86ISD::COMI;
8859       CC = ISD::SETLE;
8860       break;
8861     case Intrinsic::x86_sse_comigt_ss:
8862     case Intrinsic::x86_sse2_comigt_sd:
8863       Opc = X86ISD::COMI;
8864       CC = ISD::SETGT;
8865       break;
8866     case Intrinsic::x86_sse_comige_ss:
8867     case Intrinsic::x86_sse2_comige_sd:
8868       Opc = X86ISD::COMI;
8869       CC = ISD::SETGE;
8870       break;
8871     case Intrinsic::x86_sse_comineq_ss:
8872     case Intrinsic::x86_sse2_comineq_sd:
8873       Opc = X86ISD::COMI;
8874       CC = ISD::SETNE;
8875       break;
8876     case Intrinsic::x86_sse_ucomieq_ss:
8877     case Intrinsic::x86_sse2_ucomieq_sd:
8878       Opc = X86ISD::UCOMI;
8879       CC = ISD::SETEQ;
8880       break;
8881     case Intrinsic::x86_sse_ucomilt_ss:
8882     case Intrinsic::x86_sse2_ucomilt_sd:
8883       Opc = X86ISD::UCOMI;
8884       CC = ISD::SETLT;
8885       break;
8886     case Intrinsic::x86_sse_ucomile_ss:
8887     case Intrinsic::x86_sse2_ucomile_sd:
8888       Opc = X86ISD::UCOMI;
8889       CC = ISD::SETLE;
8890       break;
8891     case Intrinsic::x86_sse_ucomigt_ss:
8892     case Intrinsic::x86_sse2_ucomigt_sd:
8893       Opc = X86ISD::UCOMI;
8894       CC = ISD::SETGT;
8895       break;
8896     case Intrinsic::x86_sse_ucomige_ss:
8897     case Intrinsic::x86_sse2_ucomige_sd:
8898       Opc = X86ISD::UCOMI;
8899       CC = ISD::SETGE;
8900       break;
8901     case Intrinsic::x86_sse_ucomineq_ss:
8902     case Intrinsic::x86_sse2_ucomineq_sd:
8903       Opc = X86ISD::UCOMI;
8904       CC = ISD::SETNE;
8905       break;
8906     }
8907
8908     SDValue LHS = Op.getOperand(1);
8909     SDValue RHS = Op.getOperand(2);
8910     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
8911     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
8912     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
8913     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8914                                 DAG.getConstant(X86CC, MVT::i8), Cond);
8915     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8916   }
8917   // ptest and testp intrinsics. The intrinsic these come from are designed to
8918   // return an integer value, not just an instruction so lower it to the ptest
8919   // or testp pattern and a setcc for the result.
8920   case Intrinsic::x86_sse41_ptestz:
8921   case Intrinsic::x86_sse41_ptestc:
8922   case Intrinsic::x86_sse41_ptestnzc:
8923   case Intrinsic::x86_avx_ptestz_256:
8924   case Intrinsic::x86_avx_ptestc_256:
8925   case Intrinsic::x86_avx_ptestnzc_256:
8926   case Intrinsic::x86_avx_vtestz_ps:
8927   case Intrinsic::x86_avx_vtestc_ps:
8928   case Intrinsic::x86_avx_vtestnzc_ps:
8929   case Intrinsic::x86_avx_vtestz_pd:
8930   case Intrinsic::x86_avx_vtestc_pd:
8931   case Intrinsic::x86_avx_vtestnzc_pd:
8932   case Intrinsic::x86_avx_vtestz_ps_256:
8933   case Intrinsic::x86_avx_vtestc_ps_256:
8934   case Intrinsic::x86_avx_vtestnzc_ps_256:
8935   case Intrinsic::x86_avx_vtestz_pd_256:
8936   case Intrinsic::x86_avx_vtestc_pd_256:
8937   case Intrinsic::x86_avx_vtestnzc_pd_256: {
8938     bool IsTestPacked = false;
8939     unsigned X86CC = 0;
8940     switch (IntNo) {
8941     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
8942     case Intrinsic::x86_avx_vtestz_ps:
8943     case Intrinsic::x86_avx_vtestz_pd:
8944     case Intrinsic::x86_avx_vtestz_ps_256:
8945     case Intrinsic::x86_avx_vtestz_pd_256:
8946       IsTestPacked = true; // Fallthrough
8947     case Intrinsic::x86_sse41_ptestz:
8948     case Intrinsic::x86_avx_ptestz_256:
8949       // ZF = 1
8950       X86CC = X86::COND_E;
8951       break;
8952     case Intrinsic::x86_avx_vtestc_ps:
8953     case Intrinsic::x86_avx_vtestc_pd:
8954     case Intrinsic::x86_avx_vtestc_ps_256:
8955     case Intrinsic::x86_avx_vtestc_pd_256:
8956       IsTestPacked = true; // Fallthrough
8957     case Intrinsic::x86_sse41_ptestc:
8958     case Intrinsic::x86_avx_ptestc_256:
8959       // CF = 1
8960       X86CC = X86::COND_B;
8961       break;
8962     case Intrinsic::x86_avx_vtestnzc_ps:
8963     case Intrinsic::x86_avx_vtestnzc_pd:
8964     case Intrinsic::x86_avx_vtestnzc_ps_256:
8965     case Intrinsic::x86_avx_vtestnzc_pd_256:
8966       IsTestPacked = true; // Fallthrough
8967     case Intrinsic::x86_sse41_ptestnzc:
8968     case Intrinsic::x86_avx_ptestnzc_256:
8969       // ZF and CF = 0
8970       X86CC = X86::COND_A;
8971       break;
8972     }
8973
8974     SDValue LHS = Op.getOperand(1);
8975     SDValue RHS = Op.getOperand(2);
8976     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
8977     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
8978     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
8979     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
8980     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
8981   }
8982
8983   // Fix vector shift instructions where the last operand is a non-immediate
8984   // i32 value.
8985   case Intrinsic::x86_sse2_pslli_w:
8986   case Intrinsic::x86_sse2_pslli_d:
8987   case Intrinsic::x86_sse2_pslli_q:
8988   case Intrinsic::x86_sse2_psrli_w:
8989   case Intrinsic::x86_sse2_psrli_d:
8990   case Intrinsic::x86_sse2_psrli_q:
8991   case Intrinsic::x86_sse2_psrai_w:
8992   case Intrinsic::x86_sse2_psrai_d:
8993   case Intrinsic::x86_mmx_pslli_w:
8994   case Intrinsic::x86_mmx_pslli_d:
8995   case Intrinsic::x86_mmx_pslli_q:
8996   case Intrinsic::x86_mmx_psrli_w:
8997   case Intrinsic::x86_mmx_psrli_d:
8998   case Intrinsic::x86_mmx_psrli_q:
8999   case Intrinsic::x86_mmx_psrai_w:
9000   case Intrinsic::x86_mmx_psrai_d: {
9001     SDValue ShAmt = Op.getOperand(2);
9002     if (isa<ConstantSDNode>(ShAmt))
9003       return SDValue();
9004
9005     unsigned NewIntNo = 0;
9006     EVT ShAmtVT = MVT::v4i32;
9007     switch (IntNo) {
9008     case Intrinsic::x86_sse2_pslli_w:
9009       NewIntNo = Intrinsic::x86_sse2_psll_w;
9010       break;
9011     case Intrinsic::x86_sse2_pslli_d:
9012       NewIntNo = Intrinsic::x86_sse2_psll_d;
9013       break;
9014     case Intrinsic::x86_sse2_pslli_q:
9015       NewIntNo = Intrinsic::x86_sse2_psll_q;
9016       break;
9017     case Intrinsic::x86_sse2_psrli_w:
9018       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9019       break;
9020     case Intrinsic::x86_sse2_psrli_d:
9021       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9022       break;
9023     case Intrinsic::x86_sse2_psrli_q:
9024       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9025       break;
9026     case Intrinsic::x86_sse2_psrai_w:
9027       NewIntNo = Intrinsic::x86_sse2_psra_w;
9028       break;
9029     case Intrinsic::x86_sse2_psrai_d:
9030       NewIntNo = Intrinsic::x86_sse2_psra_d;
9031       break;
9032     default: {
9033       ShAmtVT = MVT::v2i32;
9034       switch (IntNo) {
9035       case Intrinsic::x86_mmx_pslli_w:
9036         NewIntNo = Intrinsic::x86_mmx_psll_w;
9037         break;
9038       case Intrinsic::x86_mmx_pslli_d:
9039         NewIntNo = Intrinsic::x86_mmx_psll_d;
9040         break;
9041       case Intrinsic::x86_mmx_pslli_q:
9042         NewIntNo = Intrinsic::x86_mmx_psll_q;
9043         break;
9044       case Intrinsic::x86_mmx_psrli_w:
9045         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9046         break;
9047       case Intrinsic::x86_mmx_psrli_d:
9048         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9049         break;
9050       case Intrinsic::x86_mmx_psrli_q:
9051         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9052         break;
9053       case Intrinsic::x86_mmx_psrai_w:
9054         NewIntNo = Intrinsic::x86_mmx_psra_w;
9055         break;
9056       case Intrinsic::x86_mmx_psrai_d:
9057         NewIntNo = Intrinsic::x86_mmx_psra_d;
9058         break;
9059       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9060       }
9061       break;
9062     }
9063     }
9064
9065     // The vector shift intrinsics with scalars uses 32b shift amounts but
9066     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9067     // to be zero.
9068     SDValue ShOps[4];
9069     ShOps[0] = ShAmt;
9070     ShOps[1] = DAG.getConstant(0, MVT::i32);
9071     if (ShAmtVT == MVT::v4i32) {
9072       ShOps[2] = DAG.getUNDEF(MVT::i32);
9073       ShOps[3] = DAG.getUNDEF(MVT::i32);
9074       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9075     } else {
9076       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9077 // FIXME this must be lowered to get rid of the invalid type.
9078     }
9079
9080     EVT VT = Op.getValueType();
9081     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9082     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9083                        DAG.getConstant(NewIntNo, MVT::i32),
9084                        Op.getOperand(1), ShAmt);
9085   }
9086   }
9087 }
9088
9089 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9090                                            SelectionDAG &DAG) const {
9091   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9092   MFI->setReturnAddressIsTaken(true);
9093
9094   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9095   DebugLoc dl = Op.getDebugLoc();
9096
9097   if (Depth > 0) {
9098     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9099     SDValue Offset =
9100       DAG.getConstant(TD->getPointerSize(),
9101                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9102     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9103                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9104                                    FrameAddr, Offset),
9105                        MachinePointerInfo(), false, false, 0);
9106   }
9107
9108   // Just load the return address.
9109   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9110   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9111                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9112 }
9113
9114 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9115   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9116   MFI->setFrameAddressIsTaken(true);
9117
9118   EVT VT = Op.getValueType();
9119   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9120   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9121   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9122   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9123   while (Depth--)
9124     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9125                             MachinePointerInfo(),
9126                             false, false, 0);
9127   return FrameAddr;
9128 }
9129
9130 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9131                                                      SelectionDAG &DAG) const {
9132   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9133 }
9134
9135 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9136   MachineFunction &MF = DAG.getMachineFunction();
9137   SDValue Chain     = Op.getOperand(0);
9138   SDValue Offset    = Op.getOperand(1);
9139   SDValue Handler   = Op.getOperand(2);
9140   DebugLoc dl       = Op.getDebugLoc();
9141
9142   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9143                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9144                                      getPointerTy());
9145   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9146
9147   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9148                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9149   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9150   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9151                        false, false, 0);
9152   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9153   MF.getRegInfo().addLiveOut(StoreAddrReg);
9154
9155   return DAG.getNode(X86ISD::EH_RETURN, dl,
9156                      MVT::Other,
9157                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9158 }
9159
9160 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
9161                                              SelectionDAG &DAG) const {
9162   SDValue Root = Op.getOperand(0);
9163   SDValue Trmp = Op.getOperand(1); // trampoline
9164   SDValue FPtr = Op.getOperand(2); // nested function
9165   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9166   DebugLoc dl  = Op.getDebugLoc();
9167
9168   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9169
9170   if (Subtarget->is64Bit()) {
9171     SDValue OutChains[6];
9172
9173     // Large code-model.
9174     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9175     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9176
9177     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9178     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9179
9180     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9181
9182     // Load the pointer to the nested function into R11.
9183     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9184     SDValue Addr = Trmp;
9185     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9186                                 Addr, MachinePointerInfo(TrmpAddr),
9187                                 false, false, 0);
9188
9189     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9190                        DAG.getConstant(2, MVT::i64));
9191     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9192                                 MachinePointerInfo(TrmpAddr, 2),
9193                                 false, false, 2);
9194
9195     // Load the 'nest' parameter value into R10.
9196     // R10 is specified in X86CallingConv.td
9197     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9198     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9199                        DAG.getConstant(10, MVT::i64));
9200     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9201                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9202                                 false, false, 0);
9203
9204     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9205                        DAG.getConstant(12, MVT::i64));
9206     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9207                                 MachinePointerInfo(TrmpAddr, 12),
9208                                 false, false, 2);
9209
9210     // Jump to the nested function.
9211     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9212     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9213                        DAG.getConstant(20, MVT::i64));
9214     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9215                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9216                                 false, false, 0);
9217
9218     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9219     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9220                        DAG.getConstant(22, MVT::i64));
9221     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9222                                 MachinePointerInfo(TrmpAddr, 22),
9223                                 false, false, 0);
9224
9225     SDValue Ops[] =
9226       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
9227     return DAG.getMergeValues(Ops, 2, dl);
9228   } else {
9229     const Function *Func =
9230       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9231     CallingConv::ID CC = Func->getCallingConv();
9232     unsigned NestReg;
9233
9234     switch (CC) {
9235     default:
9236       llvm_unreachable("Unsupported calling convention");
9237     case CallingConv::C:
9238     case CallingConv::X86_StdCall: {
9239       // Pass 'nest' parameter in ECX.
9240       // Must be kept in sync with X86CallingConv.td
9241       NestReg = X86::ECX;
9242
9243       // Check that ECX wasn't needed by an 'inreg' parameter.
9244       FunctionType *FTy = Func->getFunctionType();
9245       const AttrListPtr &Attrs = Func->getAttributes();
9246
9247       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9248         unsigned InRegCount = 0;
9249         unsigned Idx = 1;
9250
9251         for (FunctionType::param_iterator I = FTy->param_begin(),
9252              E = FTy->param_end(); I != E; ++I, ++Idx)
9253           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9254             // FIXME: should only count parameters that are lowered to integers.
9255             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9256
9257         if (InRegCount > 2) {
9258           report_fatal_error("Nest register in use - reduce number of inreg"
9259                              " parameters!");
9260         }
9261       }
9262       break;
9263     }
9264     case CallingConv::X86_FastCall:
9265     case CallingConv::X86_ThisCall:
9266     case CallingConv::Fast:
9267       // Pass 'nest' parameter in EAX.
9268       // Must be kept in sync with X86CallingConv.td
9269       NestReg = X86::EAX;
9270       break;
9271     }
9272
9273     SDValue OutChains[4];
9274     SDValue Addr, Disp;
9275
9276     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9277                        DAG.getConstant(10, MVT::i32));
9278     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9279
9280     // This is storing the opcode for MOV32ri.
9281     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9282     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9283     OutChains[0] = DAG.getStore(Root, dl,
9284                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9285                                 Trmp, MachinePointerInfo(TrmpAddr),
9286                                 false, false, 0);
9287
9288     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9289                        DAG.getConstant(1, MVT::i32));
9290     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9291                                 MachinePointerInfo(TrmpAddr, 1),
9292                                 false, false, 1);
9293
9294     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9295     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9296                        DAG.getConstant(5, MVT::i32));
9297     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9298                                 MachinePointerInfo(TrmpAddr, 5),
9299                                 false, false, 1);
9300
9301     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9302                        DAG.getConstant(6, MVT::i32));
9303     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9304                                 MachinePointerInfo(TrmpAddr, 6),
9305                                 false, false, 1);
9306
9307     SDValue Ops[] =
9308       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
9309     return DAG.getMergeValues(Ops, 2, dl);
9310   }
9311 }
9312
9313 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9314                                             SelectionDAG &DAG) const {
9315   /*
9316    The rounding mode is in bits 11:10 of FPSR, and has the following
9317    settings:
9318      00 Round to nearest
9319      01 Round to -inf
9320      10 Round to +inf
9321      11 Round to 0
9322
9323   FLT_ROUNDS, on the other hand, expects the following:
9324     -1 Undefined
9325      0 Round to 0
9326      1 Round to nearest
9327      2 Round to +inf
9328      3 Round to -inf
9329
9330   To perform the conversion, we do:
9331     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9332   */
9333
9334   MachineFunction &MF = DAG.getMachineFunction();
9335   const TargetMachine &TM = MF.getTarget();
9336   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9337   unsigned StackAlignment = TFI.getStackAlignment();
9338   EVT VT = Op.getValueType();
9339   DebugLoc DL = Op.getDebugLoc();
9340
9341   // Save FP Control Word to stack slot
9342   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9343   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9344
9345
9346   MachineMemOperand *MMO =
9347    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9348                            MachineMemOperand::MOStore, 2, 2);
9349
9350   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9351   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9352                                           DAG.getVTList(MVT::Other),
9353                                           Ops, 2, MVT::i16, MMO);
9354
9355   // Load FP Control Word from stack slot
9356   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9357                             MachinePointerInfo(), false, false, 0);
9358
9359   // Transform as necessary
9360   SDValue CWD1 =
9361     DAG.getNode(ISD::SRL, DL, MVT::i16,
9362                 DAG.getNode(ISD::AND, DL, MVT::i16,
9363                             CWD, DAG.getConstant(0x800, MVT::i16)),
9364                 DAG.getConstant(11, MVT::i8));
9365   SDValue CWD2 =
9366     DAG.getNode(ISD::SRL, DL, MVT::i16,
9367                 DAG.getNode(ISD::AND, DL, MVT::i16,
9368                             CWD, DAG.getConstant(0x400, MVT::i16)),
9369                 DAG.getConstant(9, MVT::i8));
9370
9371   SDValue RetVal =
9372     DAG.getNode(ISD::AND, DL, MVT::i16,
9373                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9374                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9375                             DAG.getConstant(1, MVT::i16)),
9376                 DAG.getConstant(3, MVT::i16));
9377
9378
9379   return DAG.getNode((VT.getSizeInBits() < 16 ?
9380                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9381 }
9382
9383 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9384   EVT VT = Op.getValueType();
9385   EVT OpVT = VT;
9386   unsigned NumBits = VT.getSizeInBits();
9387   DebugLoc dl = Op.getDebugLoc();
9388
9389   Op = Op.getOperand(0);
9390   if (VT == MVT::i8) {
9391     // Zero extend to i32 since there is not an i8 bsr.
9392     OpVT = MVT::i32;
9393     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9394   }
9395
9396   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9397   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9398   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9399
9400   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9401   SDValue Ops[] = {
9402     Op,
9403     DAG.getConstant(NumBits+NumBits-1, OpVT),
9404     DAG.getConstant(X86::COND_E, MVT::i8),
9405     Op.getValue(1)
9406   };
9407   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9408
9409   // Finally xor with NumBits-1.
9410   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9411
9412   if (VT == MVT::i8)
9413     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9414   return Op;
9415 }
9416
9417 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9418   EVT VT = Op.getValueType();
9419   EVT OpVT = VT;
9420   unsigned NumBits = VT.getSizeInBits();
9421   DebugLoc dl = Op.getDebugLoc();
9422
9423   Op = Op.getOperand(0);
9424   if (VT == MVT::i8) {
9425     OpVT = MVT::i32;
9426     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9427   }
9428
9429   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9430   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9431   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9432
9433   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9434   SDValue Ops[] = {
9435     Op,
9436     DAG.getConstant(NumBits, OpVT),
9437     DAG.getConstant(X86::COND_E, MVT::i8),
9438     Op.getValue(1)
9439   };
9440   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9441
9442   if (VT == MVT::i8)
9443     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9444   return Op;
9445 }
9446
9447 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9448 // ones, and then concatenate the result back.
9449 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9450   EVT VT = Op.getValueType();
9451
9452   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9453          "Unsupported value type for operation");
9454
9455   int NumElems = VT.getVectorNumElements();
9456   DebugLoc dl = Op.getDebugLoc();
9457   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9458   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9459
9460   // Extract the LHS vectors
9461   SDValue LHS = Op.getOperand(0);
9462   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9463   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9464
9465   // Extract the RHS vectors
9466   SDValue RHS = Op.getOperand(1);
9467   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9468   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9469
9470   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9471   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9472
9473   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9474                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9475                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9476 }
9477
9478 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9479   assert(Op.getValueType().getSizeInBits() == 256 &&
9480          Op.getValueType().isInteger() &&
9481          "Only handle AVX 256-bit vector integer operation");
9482   return Lower256IntArith(Op, DAG);
9483 }
9484
9485 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9486   assert(Op.getValueType().getSizeInBits() == 256 &&
9487          Op.getValueType().isInteger() &&
9488          "Only handle AVX 256-bit vector integer operation");
9489   return Lower256IntArith(Op, DAG);
9490 }
9491
9492 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9493   EVT VT = Op.getValueType();
9494
9495   // Decompose 256-bit ops into smaller 128-bit ops.
9496   if (VT.getSizeInBits() == 256)
9497     return Lower256IntArith(Op, DAG);
9498
9499   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9500   DebugLoc dl = Op.getDebugLoc();
9501
9502   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9503   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9504   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9505   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9506   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9507   //
9508   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9509   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9510   //  return AloBlo + AloBhi + AhiBlo;
9511
9512   SDValue A = Op.getOperand(0);
9513   SDValue B = Op.getOperand(1);
9514
9515   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9516                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9517                        A, DAG.getConstant(32, MVT::i32));
9518   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9519                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9520                        B, DAG.getConstant(32, MVT::i32));
9521   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9522                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9523                        A, B);
9524   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9525                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9526                        A, Bhi);
9527   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9528                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9529                        Ahi, B);
9530   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9531                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9532                        AloBhi, DAG.getConstant(32, MVT::i32));
9533   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9534                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9535                        AhiBlo, DAG.getConstant(32, MVT::i32));
9536   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9537   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9538   return Res;
9539 }
9540
9541 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9542
9543   EVT VT = Op.getValueType();
9544   DebugLoc dl = Op.getDebugLoc();
9545   SDValue R = Op.getOperand(0);
9546   SDValue Amt = Op.getOperand(1);
9547   LLVMContext *Context = DAG.getContext();
9548
9549   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
9550     return SDValue();
9551
9552   // Decompose 256-bit shifts into smaller 128-bit shifts.
9553   if (VT.getSizeInBits() == 256) {
9554     int NumElems = VT.getVectorNumElements();
9555     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9556     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9557
9558     // Extract the two vectors
9559     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9560     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9561                                      DAG, dl);
9562
9563     // Recreate the shift amount vectors
9564     SDValue Amt1, Amt2;
9565     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9566       // Constant shift amount
9567       SmallVector<SDValue, 4> Amt1Csts;
9568       SmallVector<SDValue, 4> Amt2Csts;
9569       for (int i = 0; i < NumElems/2; ++i)
9570         Amt1Csts.push_back(Amt->getOperand(i));
9571       for (int i = NumElems/2; i < NumElems; ++i)
9572         Amt2Csts.push_back(Amt->getOperand(i));
9573
9574       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9575                                  &Amt1Csts[0], NumElems/2);
9576       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9577                                  &Amt2Csts[0], NumElems/2);
9578     } else {
9579       // Variable shift amount
9580       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9581       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9582                                  DAG, dl);
9583     }
9584
9585     // Issue new vector shifts for the smaller types
9586     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9587     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9588
9589     // Concatenate the result back
9590     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9591   }
9592
9593   // Optimize shl/srl/sra with constant shift amount.
9594   if (isSplatVector(Amt.getNode())) {
9595     SDValue SclrAmt = Amt->getOperand(0);
9596     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9597       uint64_t ShiftAmt = C->getZExtValue();
9598
9599       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9600        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9601                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9602                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9603
9604       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9605        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9606                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9607                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9608
9609       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9610        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9611                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9612                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9613
9614       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9615        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9616                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9617                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9618
9619       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9620        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9621                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9622                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9623
9624       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9625        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9626                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9627                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9628
9629       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9630        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9631                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9632                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9633
9634       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9635        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9636                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9637                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9638     }
9639   }
9640
9641   // Lower SHL with variable shift amount.
9642   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9643     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9644                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9645                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9646
9647     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9648
9649     std::vector<Constant*> CV(4, CI);
9650     Constant *C = ConstantVector::get(CV);
9651     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9652     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9653                                  MachinePointerInfo::getConstantPool(),
9654                                  false, false, 16);
9655
9656     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9657     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9658     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9659     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9660   }
9661   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9662     // a = a << 5;
9663     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9664                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9665                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9666
9667     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9668     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9669
9670     std::vector<Constant*> CVM1(16, CM1);
9671     std::vector<Constant*> CVM2(16, CM2);
9672     Constant *C = ConstantVector::get(CVM1);
9673     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9674     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9675                             MachinePointerInfo::getConstantPool(),
9676                             false, false, 16);
9677
9678     // r = pblendv(r, psllw(r & (char16)15, 4), a);
9679     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9680     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9681                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9682                     DAG.getConstant(4, MVT::i32));
9683     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9684     // a += a
9685     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9686
9687     C = ConstantVector::get(CVM2);
9688     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9689     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9690                     MachinePointerInfo::getConstantPool(),
9691                     false, false, 16);
9692
9693     // r = pblendv(r, psllw(r & (char16)63, 2), a);
9694     M = DAG.getNode(ISD::AND, dl, VT, R, M);
9695     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9696                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
9697                     DAG.getConstant(2, MVT::i32));
9698     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
9699     // a += a
9700     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
9701
9702     // return pblendv(r, r+r, a);
9703     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT,
9704                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
9705     return R;
9706   }
9707   return SDValue();
9708 }
9709
9710 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
9711   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
9712   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
9713   // looks for this combo and may remove the "setcc" instruction if the "setcc"
9714   // has only one use.
9715   SDNode *N = Op.getNode();
9716   SDValue LHS = N->getOperand(0);
9717   SDValue RHS = N->getOperand(1);
9718   unsigned BaseOp = 0;
9719   unsigned Cond = 0;
9720   DebugLoc DL = Op.getDebugLoc();
9721   switch (Op.getOpcode()) {
9722   default: llvm_unreachable("Unknown ovf instruction!");
9723   case ISD::SADDO:
9724     // A subtract of one will be selected as a INC. Note that INC doesn't
9725     // set CF, so we can't do this for UADDO.
9726     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9727       if (C->isOne()) {
9728         BaseOp = X86ISD::INC;
9729         Cond = X86::COND_O;
9730         break;
9731       }
9732     BaseOp = X86ISD::ADD;
9733     Cond = X86::COND_O;
9734     break;
9735   case ISD::UADDO:
9736     BaseOp = X86ISD::ADD;
9737     Cond = X86::COND_B;
9738     break;
9739   case ISD::SSUBO:
9740     // A subtract of one will be selected as a DEC. Note that DEC doesn't
9741     // set CF, so we can't do this for USUBO.
9742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
9743       if (C->isOne()) {
9744         BaseOp = X86ISD::DEC;
9745         Cond = X86::COND_O;
9746         break;
9747       }
9748     BaseOp = X86ISD::SUB;
9749     Cond = X86::COND_O;
9750     break;
9751   case ISD::USUBO:
9752     BaseOp = X86ISD::SUB;
9753     Cond = X86::COND_B;
9754     break;
9755   case ISD::SMULO:
9756     BaseOp = X86ISD::SMUL;
9757     Cond = X86::COND_O;
9758     break;
9759   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
9760     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
9761                                  MVT::i32);
9762     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
9763
9764     SDValue SetCC =
9765       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9766                   DAG.getConstant(X86::COND_O, MVT::i32),
9767                   SDValue(Sum.getNode(), 2));
9768
9769     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9770   }
9771   }
9772
9773   // Also sets EFLAGS.
9774   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
9775   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
9776
9777   SDValue SetCC =
9778     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
9779                 DAG.getConstant(Cond, MVT::i32),
9780                 SDValue(Sum.getNode(), 1));
9781
9782   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
9783 }
9784
9785 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
9786   DebugLoc dl = Op.getDebugLoc();
9787   SDNode* Node = Op.getNode();
9788   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9789   EVT VT = Node->getValueType(0);
9790
9791   if (Subtarget->hasSSE2() && VT.isVector()) {
9792     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
9793                         ExtraVT.getScalarType().getSizeInBits();
9794     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
9795
9796     unsigned SHLIntrinsicsID = 0;
9797     unsigned SRAIntrinsicsID = 0;
9798     switch (VT.getSimpleVT().SimpleTy) {
9799       default:
9800         return SDValue();
9801       case MVT::v2i64: {
9802         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_q;
9803         SRAIntrinsicsID = 0;
9804         break;
9805       }
9806       case MVT::v4i32: {
9807         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
9808         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
9809         break;
9810       }
9811       case MVT::v8i16: {
9812         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
9813         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
9814         break;
9815       }
9816     }
9817
9818     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9819                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
9820                          Node->getOperand(0), ShAmt);
9821
9822     // In case of 1 bit sext, no need to shr
9823     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
9824
9825     if (SRAIntrinsicsID) {
9826       Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9827                          DAG.getConstant(SRAIntrinsicsID, MVT::i32),
9828                          Tmp1, ShAmt);
9829     }
9830     return Tmp1;
9831   }
9832
9833   return SDValue();
9834 }
9835
9836
9837 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
9838   DebugLoc dl = Op.getDebugLoc();
9839
9840   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
9841   // There isn't any reason to disable it if the target processor supports it.
9842   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
9843     SDValue Chain = Op.getOperand(0);
9844     SDValue Zero = DAG.getConstant(0, MVT::i32);
9845     SDValue Ops[] = {
9846       DAG.getRegister(X86::ESP, MVT::i32), // Base
9847       DAG.getTargetConstant(1, MVT::i8),   // Scale
9848       DAG.getRegister(0, MVT::i32),        // Index
9849       DAG.getTargetConstant(0, MVT::i32),  // Disp
9850       DAG.getRegister(0, MVT::i32),        // Segment.
9851       Zero,
9852       Chain
9853     };
9854     SDNode *Res =
9855       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9856                           array_lengthof(Ops));
9857     return SDValue(Res, 0);
9858   }
9859
9860   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
9861   if (!isDev)
9862     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9863
9864   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9865   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9866   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
9867   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
9868
9869   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
9870   if (!Op1 && !Op2 && !Op3 && Op4)
9871     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
9872
9873   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
9874   if (Op1 && !Op2 && !Op3 && !Op4)
9875     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
9876
9877   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
9878   //           (MFENCE)>;
9879   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9880 }
9881
9882 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
9883                                              SelectionDAG &DAG) const {
9884   DebugLoc dl = Op.getDebugLoc();
9885   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
9886     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
9887   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
9888     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9889
9890   // The only fence that needs an instruction is a sequentially-consistent
9891   // cross-thread fence.
9892   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
9893     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
9894     // no-sse2). There isn't any reason to disable it if the target processor
9895     // supports it.
9896     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
9897       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
9898
9899     SDValue Chain = Op.getOperand(0);
9900     SDValue Zero = DAG.getConstant(0, MVT::i32);
9901     SDValue Ops[] = {
9902       DAG.getRegister(X86::ESP, MVT::i32), // Base
9903       DAG.getTargetConstant(1, MVT::i8),   // Scale
9904       DAG.getRegister(0, MVT::i32),        // Index
9905       DAG.getTargetConstant(0, MVT::i32),  // Disp
9906       DAG.getRegister(0, MVT::i32),        // Segment.
9907       Zero,
9908       Chain
9909     };
9910     SDNode *Res =
9911       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
9912                          array_lengthof(Ops));
9913     return SDValue(Res, 0);
9914   }
9915
9916   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
9917   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
9918 }
9919
9920
9921 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9922   EVT T = Op.getValueType();
9923   DebugLoc DL = Op.getDebugLoc();
9924   unsigned Reg = 0;
9925   unsigned size = 0;
9926   switch(T.getSimpleVT().SimpleTy) {
9927   default:
9928     assert(false && "Invalid value type!");
9929   case MVT::i8:  Reg = X86::AL;  size = 1; break;
9930   case MVT::i16: Reg = X86::AX;  size = 2; break;
9931   case MVT::i32: Reg = X86::EAX; size = 4; break;
9932   case MVT::i64:
9933     assert(Subtarget->is64Bit() && "Node not type legal!");
9934     Reg = X86::RAX; size = 8;
9935     break;
9936   }
9937   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
9938                                     Op.getOperand(2), SDValue());
9939   SDValue Ops[] = { cpIn.getValue(0),
9940                     Op.getOperand(1),
9941                     Op.getOperand(3),
9942                     DAG.getTargetConstant(size, MVT::i8),
9943                     cpIn.getValue(1) };
9944   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9945   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
9946   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
9947                                            Ops, 5, T, MMO);
9948   SDValue cpOut =
9949     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
9950   return cpOut;
9951 }
9952
9953 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
9954                                                  SelectionDAG &DAG) const {
9955   assert(Subtarget->is64Bit() && "Result not type legalized?");
9956   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
9957   SDValue TheChain = Op.getOperand(0);
9958   DebugLoc dl = Op.getDebugLoc();
9959   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
9960   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
9961   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
9962                                    rax.getValue(2));
9963   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
9964                             DAG.getConstant(32, MVT::i8));
9965   SDValue Ops[] = {
9966     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
9967     rdx.getValue(1)
9968   };
9969   return DAG.getMergeValues(Ops, 2, dl);
9970 }
9971
9972 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
9973                                             SelectionDAG &DAG) const {
9974   EVT SrcVT = Op.getOperand(0).getValueType();
9975   EVT DstVT = Op.getValueType();
9976   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
9977          Subtarget->hasMMX() && "Unexpected custom BITCAST");
9978   assert((DstVT == MVT::i64 ||
9979           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
9980          "Unexpected custom BITCAST");
9981   // i64 <=> MMX conversions are Legal.
9982   if (SrcVT==MVT::i64 && DstVT.isVector())
9983     return Op;
9984   if (DstVT==MVT::i64 && SrcVT.isVector())
9985     return Op;
9986   // MMX <=> MMX conversions are Legal.
9987   if (SrcVT.isVector() && DstVT.isVector())
9988     return Op;
9989   // All other conversions need to be expanded.
9990   return SDValue();
9991 }
9992
9993 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
9994   SDNode *Node = Op.getNode();
9995   DebugLoc dl = Node->getDebugLoc();
9996   EVT T = Node->getValueType(0);
9997   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
9998                               DAG.getConstant(0, T), Node->getOperand(2));
9999   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10000                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10001                        Node->getOperand(0),
10002                        Node->getOperand(1), negOp,
10003                        cast<AtomicSDNode>(Node)->getSrcValue(),
10004                        cast<AtomicSDNode>(Node)->getAlignment(),
10005                        cast<AtomicSDNode>(Node)->getOrdering(),
10006                        cast<AtomicSDNode>(Node)->getSynchScope());
10007 }
10008
10009 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10010   SDNode *Node = Op.getNode();
10011   DebugLoc dl = Node->getDebugLoc();
10012   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10013
10014   // Convert seq_cst store -> xchg
10015   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10016   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10017   //        (The only way to get a 16-byte store is cmpxchg16b)
10018   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10019   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10020       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10021     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10022                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10023                                  Node->getOperand(0),
10024                                  Node->getOperand(1), Node->getOperand(2),
10025                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10026                                  cast<AtomicSDNode>(Node)->getOrdering(),
10027                                  cast<AtomicSDNode>(Node)->getSynchScope());
10028     return Swap.getValue(1);
10029   }
10030   // Other atomic stores have a simple pattern.
10031   return Op;
10032 }
10033
10034 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10035   EVT VT = Op.getNode()->getValueType(0);
10036
10037   // Let legalize expand this if it isn't a legal type yet.
10038   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10039     return SDValue();
10040
10041   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10042
10043   unsigned Opc;
10044   bool ExtraOp = false;
10045   switch (Op.getOpcode()) {
10046   default: assert(0 && "Invalid code");
10047   case ISD::ADDC: Opc = X86ISD::ADD; break;
10048   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10049   case ISD::SUBC: Opc = X86ISD::SUB; break;
10050   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10051   }
10052
10053   if (!ExtraOp)
10054     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10055                        Op.getOperand(1));
10056   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10057                      Op.getOperand(1), Op.getOperand(2));
10058 }
10059
10060 /// LowerOperation - Provide custom lowering hooks for some operations.
10061 ///
10062 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10063   switch (Op.getOpcode()) {
10064   default: llvm_unreachable("Should not custom lower this!");
10065   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10066   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10067   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10068   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10069   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10070   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10071   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10072   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10073   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10074   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10075   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10076   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10077   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10078   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10079   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10080   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10081   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10082   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10083   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10084   case ISD::SHL_PARTS:
10085   case ISD::SRA_PARTS:
10086   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10087   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10088   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10089   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10090   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10091   case ISD::FABS:               return LowerFABS(Op, DAG);
10092   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10093   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10094   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10095   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10096   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
10097   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10098   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10099   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10100   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10101   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10102   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10103   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10104   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10105   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10106   case ISD::FRAME_TO_ARGS_OFFSET:
10107                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10108   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10109   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10110   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
10111   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10112   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10113   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10114   case ISD::MUL:                return LowerMUL(Op, DAG);
10115   case ISD::SRA:
10116   case ISD::SRL:
10117   case ISD::SHL:                return LowerShift(Op, DAG);
10118   case ISD::SADDO:
10119   case ISD::UADDO:
10120   case ISD::SSUBO:
10121   case ISD::USUBO:
10122   case ISD::SMULO:
10123   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10124   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10125   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10126   case ISD::ADDC:
10127   case ISD::ADDE:
10128   case ISD::SUBC:
10129   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10130   case ISD::ADD:                return LowerADD(Op, DAG);
10131   case ISD::SUB:                return LowerSUB(Op, DAG);
10132   }
10133 }
10134
10135 static void ReplaceATOMIC_LOAD(SDNode *Node,
10136                                   SmallVectorImpl<SDValue> &Results,
10137                                   SelectionDAG &DAG) {
10138   DebugLoc dl = Node->getDebugLoc();
10139   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10140
10141   // Convert wide load -> cmpxchg8b/cmpxchg16b
10142   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10143   //        (The only way to get a 16-byte load is cmpxchg16b)
10144   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10145   SDValue Zero = DAG.getConstant(0, cast<AtomicSDNode>(Node)->getMemoryVT());
10146   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
10147                                cast<AtomicSDNode>(Node)->getMemoryVT(),
10148                                Node->getOperand(0),
10149                                Node->getOperand(1), Zero, Zero,
10150                                cast<AtomicSDNode>(Node)->getMemOperand(),
10151                                cast<AtomicSDNode>(Node)->getOrdering(),
10152                                cast<AtomicSDNode>(Node)->getSynchScope());
10153   Results.push_back(Swap.getValue(0));
10154   Results.push_back(Swap.getValue(1));
10155 }
10156
10157 void X86TargetLowering::
10158 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10159                         SelectionDAG &DAG, unsigned NewOp) const {
10160   EVT T = Node->getValueType(0);
10161   DebugLoc dl = Node->getDebugLoc();
10162   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10163
10164   SDValue Chain = Node->getOperand(0);
10165   SDValue In1 = Node->getOperand(1);
10166   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10167                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10168   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10169                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10170   SDValue Ops[] = { Chain, In1, In2L, In2H };
10171   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10172   SDValue Result =
10173     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10174                             cast<MemSDNode>(Node)->getMemOperand());
10175   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10176   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10177   Results.push_back(Result.getValue(2));
10178 }
10179
10180 /// ReplaceNodeResults - Replace a node with an illegal result type
10181 /// with a new node built out of custom code.
10182 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10183                                            SmallVectorImpl<SDValue>&Results,
10184                                            SelectionDAG &DAG) const {
10185   DebugLoc dl = N->getDebugLoc();
10186   switch (N->getOpcode()) {
10187   default:
10188     assert(false && "Do not know how to custom type legalize this operation!");
10189     return;
10190   case ISD::SIGN_EXTEND_INREG:
10191   case ISD::ADDC:
10192   case ISD::ADDE:
10193   case ISD::SUBC:
10194   case ISD::SUBE:
10195     // We don't want to expand or promote these.
10196     return;
10197   case ISD::FP_TO_SINT: {
10198     std::pair<SDValue,SDValue> Vals =
10199         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10200     SDValue FIST = Vals.first, StackSlot = Vals.second;
10201     if (FIST.getNode() != 0) {
10202       EVT VT = N->getValueType(0);
10203       // Return a load from the stack slot.
10204       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10205                                     MachinePointerInfo(), false, false, 0));
10206     }
10207     return;
10208   }
10209   case ISD::READCYCLECOUNTER: {
10210     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10211     SDValue TheChain = N->getOperand(0);
10212     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10213     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10214                                      rd.getValue(1));
10215     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10216                                      eax.getValue(2));
10217     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10218     SDValue Ops[] = { eax, edx };
10219     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10220     Results.push_back(edx.getValue(1));
10221     return;
10222   }
10223   case ISD::ATOMIC_CMP_SWAP: {
10224     EVT T = N->getValueType(0);
10225     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
10226     SDValue cpInL, cpInH;
10227     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
10228                         DAG.getConstant(0, MVT::i32));
10229     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
10230                         DAG.getConstant(1, MVT::i32));
10231     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
10232     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
10233                              cpInL.getValue(1));
10234     SDValue swapInL, swapInH;
10235     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
10236                           DAG.getConstant(0, MVT::i32));
10237     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
10238                           DAG.getConstant(1, MVT::i32));
10239     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
10240                                cpInH.getValue(1));
10241     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
10242                                swapInL.getValue(1));
10243     SDValue Ops[] = { swapInH.getValue(0),
10244                       N->getOperand(1),
10245                       swapInH.getValue(1) };
10246     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10247     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10248     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
10249                                              Ops, 3, T, MMO);
10250     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
10251                                         MVT::i32, Result.getValue(1));
10252     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
10253                                         MVT::i32, cpOutL.getValue(2));
10254     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10255     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10256     Results.push_back(cpOutH.getValue(1));
10257     return;
10258   }
10259   case ISD::ATOMIC_LOAD_ADD:
10260     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10261     return;
10262   case ISD::ATOMIC_LOAD_AND:
10263     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10264     return;
10265   case ISD::ATOMIC_LOAD_NAND:
10266     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10267     return;
10268   case ISD::ATOMIC_LOAD_OR:
10269     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10270     return;
10271   case ISD::ATOMIC_LOAD_SUB:
10272     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10273     return;
10274   case ISD::ATOMIC_LOAD_XOR:
10275     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10276     return;
10277   case ISD::ATOMIC_SWAP:
10278     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10279     return;
10280   case ISD::ATOMIC_LOAD:
10281     ReplaceATOMIC_LOAD(N, Results, DAG);
10282   }
10283 }
10284
10285 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10286   switch (Opcode) {
10287   default: return NULL;
10288   case X86ISD::BSF:                return "X86ISD::BSF";
10289   case X86ISD::BSR:                return "X86ISD::BSR";
10290   case X86ISD::SHLD:               return "X86ISD::SHLD";
10291   case X86ISD::SHRD:               return "X86ISD::SHRD";
10292   case X86ISD::FAND:               return "X86ISD::FAND";
10293   case X86ISD::FOR:                return "X86ISD::FOR";
10294   case X86ISD::FXOR:               return "X86ISD::FXOR";
10295   case X86ISD::FSRL:               return "X86ISD::FSRL";
10296   case X86ISD::FILD:               return "X86ISD::FILD";
10297   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10298   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10299   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10300   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10301   case X86ISD::FLD:                return "X86ISD::FLD";
10302   case X86ISD::FST:                return "X86ISD::FST";
10303   case X86ISD::CALL:               return "X86ISD::CALL";
10304   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10305   case X86ISD::BT:                 return "X86ISD::BT";
10306   case X86ISD::CMP:                return "X86ISD::CMP";
10307   case X86ISD::COMI:               return "X86ISD::COMI";
10308   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10309   case X86ISD::SETCC:              return "X86ISD::SETCC";
10310   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10311   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10312   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10313   case X86ISD::CMOV:               return "X86ISD::CMOV";
10314   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10315   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10316   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10317   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10318   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10319   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10320   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10321   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10322   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10323   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10324   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10325   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10326   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10327   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10328   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10329   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10330   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10331   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
10332   case X86ISD::FMAX:               return "X86ISD::FMAX";
10333   case X86ISD::FMIN:               return "X86ISD::FMIN";
10334   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10335   case X86ISD::FRCP:               return "X86ISD::FRCP";
10336   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10337   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10338   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10339   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10340   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10341   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10342   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10343   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10344   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10345   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10346   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10347   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10348   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10349   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10350   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10351   case X86ISD::VSHL:               return "X86ISD::VSHL";
10352   case X86ISD::VSRL:               return "X86ISD::VSRL";
10353   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10354   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10355   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10356   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10357   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10358   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10359   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10360   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10361   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10362   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10363   case X86ISD::ADD:                return "X86ISD::ADD";
10364   case X86ISD::SUB:                return "X86ISD::SUB";
10365   case X86ISD::ADC:                return "X86ISD::ADC";
10366   case X86ISD::SBB:                return "X86ISD::SBB";
10367   case X86ISD::SMUL:               return "X86ISD::SMUL";
10368   case X86ISD::UMUL:               return "X86ISD::UMUL";
10369   case X86ISD::INC:                return "X86ISD::INC";
10370   case X86ISD::DEC:                return "X86ISD::DEC";
10371   case X86ISD::OR:                 return "X86ISD::OR";
10372   case X86ISD::XOR:                return "X86ISD::XOR";
10373   case X86ISD::AND:                return "X86ISD::AND";
10374   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10375   case X86ISD::PTEST:              return "X86ISD::PTEST";
10376   case X86ISD::TESTP:              return "X86ISD::TESTP";
10377   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10378   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10379   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10380   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10381   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10382   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10383   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10384   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10385   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10386   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10387   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10388   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10389   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10390   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10391   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10392   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10393   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10394   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10395   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10396   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10397   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10398   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10399   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10400   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10401   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10402   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10403   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10404   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10405   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10406   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10407   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10408   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10409   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10410   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10411   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10412   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10413   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10414   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10415   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10416   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10417   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10418   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10419   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10420   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10421   }
10422 }
10423
10424 // isLegalAddressingMode - Return true if the addressing mode represented
10425 // by AM is legal for this target, for a load/store of the specified type.
10426 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10427                                               Type *Ty) const {
10428   // X86 supports extremely general addressing modes.
10429   CodeModel::Model M = getTargetMachine().getCodeModel();
10430   Reloc::Model R = getTargetMachine().getRelocationModel();
10431
10432   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10433   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10434     return false;
10435
10436   if (AM.BaseGV) {
10437     unsigned GVFlags =
10438       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10439
10440     // If a reference to this global requires an extra load, we can't fold it.
10441     if (isGlobalStubReference(GVFlags))
10442       return false;
10443
10444     // If BaseGV requires a register for the PIC base, we cannot also have a
10445     // BaseReg specified.
10446     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10447       return false;
10448
10449     // If lower 4G is not available, then we must use rip-relative addressing.
10450     if ((M != CodeModel::Small || R != Reloc::Static) &&
10451         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10452       return false;
10453   }
10454
10455   switch (AM.Scale) {
10456   case 0:
10457   case 1:
10458   case 2:
10459   case 4:
10460   case 8:
10461     // These scales always work.
10462     break;
10463   case 3:
10464   case 5:
10465   case 9:
10466     // These scales are formed with basereg+scalereg.  Only accept if there is
10467     // no basereg yet.
10468     if (AM.HasBaseReg)
10469       return false;
10470     break;
10471   default:  // Other stuff never works.
10472     return false;
10473   }
10474
10475   return true;
10476 }
10477
10478
10479 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10480   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10481     return false;
10482   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10483   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10484   if (NumBits1 <= NumBits2)
10485     return false;
10486   return true;
10487 }
10488
10489 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10490   if (!VT1.isInteger() || !VT2.isInteger())
10491     return false;
10492   unsigned NumBits1 = VT1.getSizeInBits();
10493   unsigned NumBits2 = VT2.getSizeInBits();
10494   if (NumBits1 <= NumBits2)
10495     return false;
10496   return true;
10497 }
10498
10499 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10500   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10501   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10502 }
10503
10504 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10505   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10506   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10507 }
10508
10509 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10510   // i16 instructions are longer (0x66 prefix) and potentially slower.
10511   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10512 }
10513
10514 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10515 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10516 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10517 /// are assumed to be legal.
10518 bool
10519 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10520                                       EVT VT) const {
10521   // Very little shuffling can be done for 64-bit vectors right now.
10522   if (VT.getSizeInBits() == 64)
10523     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
10524
10525   // FIXME: pshufb, blends, shifts.
10526   return (VT.getVectorNumElements() == 2 ||
10527           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10528           isMOVLMask(M, VT) ||
10529           isSHUFPMask(M, VT) ||
10530           isPSHUFDMask(M, VT) ||
10531           isPSHUFHWMask(M, VT) ||
10532           isPSHUFLWMask(M, VT) ||
10533           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
10534           isUNPCKLMask(M, VT) ||
10535           isUNPCKHMask(M, VT) ||
10536           isUNPCKL_v_undef_Mask(M, VT) ||
10537           isUNPCKH_v_undef_Mask(M, VT));
10538 }
10539
10540 bool
10541 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10542                                           EVT VT) const {
10543   unsigned NumElts = VT.getVectorNumElements();
10544   // FIXME: This collection of masks seems suspect.
10545   if (NumElts == 2)
10546     return true;
10547   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10548     return (isMOVLMask(Mask, VT)  ||
10549             isCommutedMOVLMask(Mask, VT, true) ||
10550             isSHUFPMask(Mask, VT) ||
10551             isCommutedSHUFPMask(Mask, VT));
10552   }
10553   return false;
10554 }
10555
10556 //===----------------------------------------------------------------------===//
10557 //                           X86 Scheduler Hooks
10558 //===----------------------------------------------------------------------===//
10559
10560 // private utility function
10561 MachineBasicBlock *
10562 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10563                                                        MachineBasicBlock *MBB,
10564                                                        unsigned regOpc,
10565                                                        unsigned immOpc,
10566                                                        unsigned LoadOpc,
10567                                                        unsigned CXchgOpc,
10568                                                        unsigned notOpc,
10569                                                        unsigned EAXreg,
10570                                                        TargetRegisterClass *RC,
10571                                                        bool invSrc) const {
10572   // For the atomic bitwise operator, we generate
10573   //   thisMBB:
10574   //   newMBB:
10575   //     ld  t1 = [bitinstr.addr]
10576   //     op  t2 = t1, [bitinstr.val]
10577   //     mov EAX = t1
10578   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10579   //     bz  newMBB
10580   //     fallthrough -->nextMBB
10581   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10582   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10583   MachineFunction::iterator MBBIter = MBB;
10584   ++MBBIter;
10585
10586   /// First build the CFG
10587   MachineFunction *F = MBB->getParent();
10588   MachineBasicBlock *thisMBB = MBB;
10589   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10590   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10591   F->insert(MBBIter, newMBB);
10592   F->insert(MBBIter, nextMBB);
10593
10594   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10595   nextMBB->splice(nextMBB->begin(), thisMBB,
10596                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10597                   thisMBB->end());
10598   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10599
10600   // Update thisMBB to fall through to newMBB
10601   thisMBB->addSuccessor(newMBB);
10602
10603   // newMBB jumps to itself and fall through to nextMBB
10604   newMBB->addSuccessor(nextMBB);
10605   newMBB->addSuccessor(newMBB);
10606
10607   // Insert instructions into newMBB based on incoming instruction
10608   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10609          "unexpected number of operands");
10610   DebugLoc dl = bInstr->getDebugLoc();
10611   MachineOperand& destOper = bInstr->getOperand(0);
10612   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10613   int numArgs = bInstr->getNumOperands() - 1;
10614   for (int i=0; i < numArgs; ++i)
10615     argOpers[i] = &bInstr->getOperand(i+1);
10616
10617   // x86 address has 4 operands: base, index, scale, and displacement
10618   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10619   int valArgIndx = lastAddrIndx + 1;
10620
10621   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10622   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10623   for (int i=0; i <= lastAddrIndx; ++i)
10624     (*MIB).addOperand(*argOpers[i]);
10625
10626   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10627   if (invSrc) {
10628     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10629   }
10630   else
10631     tt = t1;
10632
10633   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10634   assert((argOpers[valArgIndx]->isReg() ||
10635           argOpers[valArgIndx]->isImm()) &&
10636          "invalid operand");
10637   if (argOpers[valArgIndx]->isReg())
10638     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10639   else
10640     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10641   MIB.addReg(tt);
10642   (*MIB).addOperand(*argOpers[valArgIndx]);
10643
10644   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10645   MIB.addReg(t1);
10646
10647   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10648   for (int i=0; i <= lastAddrIndx; ++i)
10649     (*MIB).addOperand(*argOpers[i]);
10650   MIB.addReg(t2);
10651   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10652   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10653                     bInstr->memoperands_end());
10654
10655   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10656   MIB.addReg(EAXreg);
10657
10658   // insert branch
10659   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10660
10661   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10662   return nextMBB;
10663 }
10664
10665 // private utility function:  64 bit atomics on 32 bit host.
10666 MachineBasicBlock *
10667 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
10668                                                        MachineBasicBlock *MBB,
10669                                                        unsigned regOpcL,
10670                                                        unsigned regOpcH,
10671                                                        unsigned immOpcL,
10672                                                        unsigned immOpcH,
10673                                                        bool invSrc) const {
10674   // For the atomic bitwise operator, we generate
10675   //   thisMBB (instructions are in pairs, except cmpxchg8b)
10676   //     ld t1,t2 = [bitinstr.addr]
10677   //   newMBB:
10678   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
10679   //     op  t5, t6 <- out1, out2, [bitinstr.val]
10680   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
10681   //     mov ECX, EBX <- t5, t6
10682   //     mov EAX, EDX <- t1, t2
10683   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
10684   //     mov t3, t4 <- EAX, EDX
10685   //     bz  newMBB
10686   //     result in out1, out2
10687   //     fallthrough -->nextMBB
10688
10689   const TargetRegisterClass *RC = X86::GR32RegisterClass;
10690   const unsigned LoadOpc = X86::MOV32rm;
10691   const unsigned NotOpc = X86::NOT32r;
10692   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10693   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10694   MachineFunction::iterator MBBIter = MBB;
10695   ++MBBIter;
10696
10697   /// First build the CFG
10698   MachineFunction *F = MBB->getParent();
10699   MachineBasicBlock *thisMBB = MBB;
10700   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10701   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10702   F->insert(MBBIter, newMBB);
10703   F->insert(MBBIter, nextMBB);
10704
10705   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10706   nextMBB->splice(nextMBB->begin(), thisMBB,
10707                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10708                   thisMBB->end());
10709   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10710
10711   // Update thisMBB to fall through to newMBB
10712   thisMBB->addSuccessor(newMBB);
10713
10714   // newMBB jumps to itself and fall through to nextMBB
10715   newMBB->addSuccessor(nextMBB);
10716   newMBB->addSuccessor(newMBB);
10717
10718   DebugLoc dl = bInstr->getDebugLoc();
10719   // Insert instructions into newMBB based on incoming instruction
10720   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
10721   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
10722          "unexpected number of operands");
10723   MachineOperand& dest1Oper = bInstr->getOperand(0);
10724   MachineOperand& dest2Oper = bInstr->getOperand(1);
10725   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10726   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
10727     argOpers[i] = &bInstr->getOperand(i+2);
10728
10729     // We use some of the operands multiple times, so conservatively just
10730     // clear any kill flags that might be present.
10731     if (argOpers[i]->isReg() && argOpers[i]->isUse())
10732       argOpers[i]->setIsKill(false);
10733   }
10734
10735   // x86 address has 5 operands: base, index, scale, displacement, and segment.
10736   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10737
10738   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10739   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
10740   for (int i=0; i <= lastAddrIndx; ++i)
10741     (*MIB).addOperand(*argOpers[i]);
10742   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10743   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
10744   // add 4 to displacement.
10745   for (int i=0; i <= lastAddrIndx-2; ++i)
10746     (*MIB).addOperand(*argOpers[i]);
10747   MachineOperand newOp3 = *(argOpers[3]);
10748   if (newOp3.isImm())
10749     newOp3.setImm(newOp3.getImm()+4);
10750   else
10751     newOp3.setOffset(newOp3.getOffset()+4);
10752   (*MIB).addOperand(newOp3);
10753   (*MIB).addOperand(*argOpers[lastAddrIndx]);
10754
10755   // t3/4 are defined later, at the bottom of the loop
10756   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
10757   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
10758   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
10759     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
10760   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
10761     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
10762
10763   // The subsequent operations should be using the destination registers of
10764   //the PHI instructions.
10765   if (invSrc) {
10766     t1 = F->getRegInfo().createVirtualRegister(RC);
10767     t2 = F->getRegInfo().createVirtualRegister(RC);
10768     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
10769     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
10770   } else {
10771     t1 = dest1Oper.getReg();
10772     t2 = dest2Oper.getReg();
10773   }
10774
10775   int valArgIndx = lastAddrIndx + 1;
10776   assert((argOpers[valArgIndx]->isReg() ||
10777           argOpers[valArgIndx]->isImm()) &&
10778          "invalid operand");
10779   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
10780   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
10781   if (argOpers[valArgIndx]->isReg())
10782     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
10783   else
10784     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
10785   if (regOpcL != X86::MOV32rr)
10786     MIB.addReg(t1);
10787   (*MIB).addOperand(*argOpers[valArgIndx]);
10788   assert(argOpers[valArgIndx + 1]->isReg() ==
10789          argOpers[valArgIndx]->isReg());
10790   assert(argOpers[valArgIndx + 1]->isImm() ==
10791          argOpers[valArgIndx]->isImm());
10792   if (argOpers[valArgIndx + 1]->isReg())
10793     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
10794   else
10795     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
10796   if (regOpcH != X86::MOV32rr)
10797     MIB.addReg(t2);
10798   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
10799
10800   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10801   MIB.addReg(t1);
10802   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
10803   MIB.addReg(t2);
10804
10805   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
10806   MIB.addReg(t5);
10807   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
10808   MIB.addReg(t6);
10809
10810   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
10811   for (int i=0; i <= lastAddrIndx; ++i)
10812     (*MIB).addOperand(*argOpers[i]);
10813
10814   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10815   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10816                     bInstr->memoperands_end());
10817
10818   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
10819   MIB.addReg(X86::EAX);
10820   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
10821   MIB.addReg(X86::EDX);
10822
10823   // insert branch
10824   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10825
10826   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10827   return nextMBB;
10828 }
10829
10830 // private utility function
10831 MachineBasicBlock *
10832 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
10833                                                       MachineBasicBlock *MBB,
10834                                                       unsigned cmovOpc) const {
10835   // For the atomic min/max operator, we generate
10836   //   thisMBB:
10837   //   newMBB:
10838   //     ld t1 = [min/max.addr]
10839   //     mov t2 = [min/max.val]
10840   //     cmp  t1, t2
10841   //     cmov[cond] t2 = t1
10842   //     mov EAX = t1
10843   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10844   //     bz   newMBB
10845   //     fallthrough -->nextMBB
10846   //
10847   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10848   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10849   MachineFunction::iterator MBBIter = MBB;
10850   ++MBBIter;
10851
10852   /// First build the CFG
10853   MachineFunction *F = MBB->getParent();
10854   MachineBasicBlock *thisMBB = MBB;
10855   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10856   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10857   F->insert(MBBIter, newMBB);
10858   F->insert(MBBIter, nextMBB);
10859
10860   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10861   nextMBB->splice(nextMBB->begin(), thisMBB,
10862                   llvm::next(MachineBasicBlock::iterator(mInstr)),
10863                   thisMBB->end());
10864   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10865
10866   // Update thisMBB to fall through to newMBB
10867   thisMBB->addSuccessor(newMBB);
10868
10869   // newMBB jumps to newMBB and fall through to nextMBB
10870   newMBB->addSuccessor(nextMBB);
10871   newMBB->addSuccessor(newMBB);
10872
10873   DebugLoc dl = mInstr->getDebugLoc();
10874   // Insert instructions into newMBB based on incoming instruction
10875   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10876          "unexpected number of operands");
10877   MachineOperand& destOper = mInstr->getOperand(0);
10878   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10879   int numArgs = mInstr->getNumOperands() - 1;
10880   for (int i=0; i < numArgs; ++i)
10881     argOpers[i] = &mInstr->getOperand(i+1);
10882
10883   // x86 address has 4 operands: base, index, scale, and displacement
10884   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10885   int valArgIndx = lastAddrIndx + 1;
10886
10887   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10888   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
10889   for (int i=0; i <= lastAddrIndx; ++i)
10890     (*MIB).addOperand(*argOpers[i]);
10891
10892   // We only support register and immediate values
10893   assert((argOpers[valArgIndx]->isReg() ||
10894           argOpers[valArgIndx]->isImm()) &&
10895          "invalid operand");
10896
10897   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10898   if (argOpers[valArgIndx]->isReg())
10899     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
10900   else
10901     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
10902   (*MIB).addOperand(*argOpers[valArgIndx]);
10903
10904   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
10905   MIB.addReg(t1);
10906
10907   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
10908   MIB.addReg(t1);
10909   MIB.addReg(t2);
10910
10911   // Generate movc
10912   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
10913   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
10914   MIB.addReg(t2);
10915   MIB.addReg(t1);
10916
10917   // Cmp and exchange if none has modified the memory location
10918   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
10919   for (int i=0; i <= lastAddrIndx; ++i)
10920     (*MIB).addOperand(*argOpers[i]);
10921   MIB.addReg(t3);
10922   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10923   (*MIB).setMemRefs(mInstr->memoperands_begin(),
10924                     mInstr->memoperands_end());
10925
10926   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10927   MIB.addReg(X86::EAX);
10928
10929   // insert branch
10930   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10931
10932   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
10933   return nextMBB;
10934 }
10935
10936 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
10937 // or XMM0_V32I8 in AVX all of this code can be replaced with that
10938 // in the .td file.
10939 MachineBasicBlock *
10940 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
10941                             unsigned numArgs, bool memArg) const {
10942   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
10943          "Target must have SSE4.2 or AVX features enabled");
10944
10945   DebugLoc dl = MI->getDebugLoc();
10946   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10947   unsigned Opc;
10948   if (!Subtarget->hasAVX()) {
10949     if (memArg)
10950       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
10951     else
10952       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
10953   } else {
10954     if (memArg)
10955       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
10956     else
10957       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
10958   }
10959
10960   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
10961   for (unsigned i = 0; i < numArgs; ++i) {
10962     MachineOperand &Op = MI->getOperand(i+1);
10963     if (!(Op.isReg() && Op.isImplicit()))
10964       MIB.addOperand(Op);
10965   }
10966   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
10967     .addReg(X86::XMM0);
10968
10969   MI->eraseFromParent();
10970   return BB;
10971 }
10972
10973 MachineBasicBlock *
10974 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
10975   DebugLoc dl = MI->getDebugLoc();
10976   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10977
10978   // Address into RAX/EAX, other two args into ECX, EDX.
10979   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
10980   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10981   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
10982   for (int i = 0; i < X86::AddrNumOperands; ++i)
10983     MIB.addOperand(MI->getOperand(i));
10984
10985   unsigned ValOps = X86::AddrNumOperands;
10986   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
10987     .addReg(MI->getOperand(ValOps).getReg());
10988   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
10989     .addReg(MI->getOperand(ValOps+1).getReg());
10990
10991   // The instruction doesn't actually take any operands though.
10992   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
10993
10994   MI->eraseFromParent(); // The pseudo is gone now.
10995   return BB;
10996 }
10997
10998 MachineBasicBlock *
10999 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11000   DebugLoc dl = MI->getDebugLoc();
11001   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11002
11003   // First arg in ECX, the second in EAX.
11004   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11005     .addReg(MI->getOperand(0).getReg());
11006   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11007     .addReg(MI->getOperand(1).getReg());
11008
11009   // The instruction doesn't actually take any operands though.
11010   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11011
11012   MI->eraseFromParent(); // The pseudo is gone now.
11013   return BB;
11014 }
11015
11016 MachineBasicBlock *
11017 X86TargetLowering::EmitVAARG64WithCustomInserter(
11018                    MachineInstr *MI,
11019                    MachineBasicBlock *MBB) const {
11020   // Emit va_arg instruction on X86-64.
11021
11022   // Operands to this pseudo-instruction:
11023   // 0  ) Output        : destination address (reg)
11024   // 1-5) Input         : va_list address (addr, i64mem)
11025   // 6  ) ArgSize       : Size (in bytes) of vararg type
11026   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11027   // 8  ) Align         : Alignment of type
11028   // 9  ) EFLAGS (implicit-def)
11029
11030   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11031   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11032
11033   unsigned DestReg = MI->getOperand(0).getReg();
11034   MachineOperand &Base = MI->getOperand(1);
11035   MachineOperand &Scale = MI->getOperand(2);
11036   MachineOperand &Index = MI->getOperand(3);
11037   MachineOperand &Disp = MI->getOperand(4);
11038   MachineOperand &Segment = MI->getOperand(5);
11039   unsigned ArgSize = MI->getOperand(6).getImm();
11040   unsigned ArgMode = MI->getOperand(7).getImm();
11041   unsigned Align = MI->getOperand(8).getImm();
11042
11043   // Memory Reference
11044   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11045   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11046   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11047
11048   // Machine Information
11049   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11050   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11051   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11052   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11053   DebugLoc DL = MI->getDebugLoc();
11054
11055   // struct va_list {
11056   //   i32   gp_offset
11057   //   i32   fp_offset
11058   //   i64   overflow_area (address)
11059   //   i64   reg_save_area (address)
11060   // }
11061   // sizeof(va_list) = 24
11062   // alignment(va_list) = 8
11063
11064   unsigned TotalNumIntRegs = 6;
11065   unsigned TotalNumXMMRegs = 8;
11066   bool UseGPOffset = (ArgMode == 1);
11067   bool UseFPOffset = (ArgMode == 2);
11068   unsigned MaxOffset = TotalNumIntRegs * 8 +
11069                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11070
11071   /* Align ArgSize to a multiple of 8 */
11072   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11073   bool NeedsAlign = (Align > 8);
11074
11075   MachineBasicBlock *thisMBB = MBB;
11076   MachineBasicBlock *overflowMBB;
11077   MachineBasicBlock *offsetMBB;
11078   MachineBasicBlock *endMBB;
11079
11080   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11081   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11082   unsigned OffsetReg = 0;
11083
11084   if (!UseGPOffset && !UseFPOffset) {
11085     // If we only pull from the overflow region, we don't create a branch.
11086     // We don't need to alter control flow.
11087     OffsetDestReg = 0; // unused
11088     OverflowDestReg = DestReg;
11089
11090     offsetMBB = NULL;
11091     overflowMBB = thisMBB;
11092     endMBB = thisMBB;
11093   } else {
11094     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11095     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11096     // If not, pull from overflow_area. (branch to overflowMBB)
11097     //
11098     //       thisMBB
11099     //         |     .
11100     //         |        .
11101     //     offsetMBB   overflowMBB
11102     //         |        .
11103     //         |     .
11104     //        endMBB
11105
11106     // Registers for the PHI in endMBB
11107     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11108     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11109
11110     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11111     MachineFunction *MF = MBB->getParent();
11112     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11113     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11114     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11115
11116     MachineFunction::iterator MBBIter = MBB;
11117     ++MBBIter;
11118
11119     // Insert the new basic blocks
11120     MF->insert(MBBIter, offsetMBB);
11121     MF->insert(MBBIter, overflowMBB);
11122     MF->insert(MBBIter, endMBB);
11123
11124     // Transfer the remainder of MBB and its successor edges to endMBB.
11125     endMBB->splice(endMBB->begin(), thisMBB,
11126                     llvm::next(MachineBasicBlock::iterator(MI)),
11127                     thisMBB->end());
11128     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11129
11130     // Make offsetMBB and overflowMBB successors of thisMBB
11131     thisMBB->addSuccessor(offsetMBB);
11132     thisMBB->addSuccessor(overflowMBB);
11133
11134     // endMBB is a successor of both offsetMBB and overflowMBB
11135     offsetMBB->addSuccessor(endMBB);
11136     overflowMBB->addSuccessor(endMBB);
11137
11138     // Load the offset value into a register
11139     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11140     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11141       .addOperand(Base)
11142       .addOperand(Scale)
11143       .addOperand(Index)
11144       .addDisp(Disp, UseFPOffset ? 4 : 0)
11145       .addOperand(Segment)
11146       .setMemRefs(MMOBegin, MMOEnd);
11147
11148     // Check if there is enough room left to pull this argument.
11149     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11150       .addReg(OffsetReg)
11151       .addImm(MaxOffset + 8 - ArgSizeA8);
11152
11153     // Branch to "overflowMBB" if offset >= max
11154     // Fall through to "offsetMBB" otherwise
11155     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11156       .addMBB(overflowMBB);
11157   }
11158
11159   // In offsetMBB, emit code to use the reg_save_area.
11160   if (offsetMBB) {
11161     assert(OffsetReg != 0);
11162
11163     // Read the reg_save_area address.
11164     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11165     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11166       .addOperand(Base)
11167       .addOperand(Scale)
11168       .addOperand(Index)
11169       .addDisp(Disp, 16)
11170       .addOperand(Segment)
11171       .setMemRefs(MMOBegin, MMOEnd);
11172
11173     // Zero-extend the offset
11174     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11175       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11176         .addImm(0)
11177         .addReg(OffsetReg)
11178         .addImm(X86::sub_32bit);
11179
11180     // Add the offset to the reg_save_area to get the final address.
11181     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11182       .addReg(OffsetReg64)
11183       .addReg(RegSaveReg);
11184
11185     // Compute the offset for the next argument
11186     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11187     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11188       .addReg(OffsetReg)
11189       .addImm(UseFPOffset ? 16 : 8);
11190
11191     // Store it back into the va_list.
11192     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11193       .addOperand(Base)
11194       .addOperand(Scale)
11195       .addOperand(Index)
11196       .addDisp(Disp, UseFPOffset ? 4 : 0)
11197       .addOperand(Segment)
11198       .addReg(NextOffsetReg)
11199       .setMemRefs(MMOBegin, MMOEnd);
11200
11201     // Jump to endMBB
11202     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11203       .addMBB(endMBB);
11204   }
11205
11206   //
11207   // Emit code to use overflow area
11208   //
11209
11210   // Load the overflow_area address into a register.
11211   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11212   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11213     .addOperand(Base)
11214     .addOperand(Scale)
11215     .addOperand(Index)
11216     .addDisp(Disp, 8)
11217     .addOperand(Segment)
11218     .setMemRefs(MMOBegin, MMOEnd);
11219
11220   // If we need to align it, do so. Otherwise, just copy the address
11221   // to OverflowDestReg.
11222   if (NeedsAlign) {
11223     // Align the overflow address
11224     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11225     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11226
11227     // aligned_addr = (addr + (align-1)) & ~(align-1)
11228     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11229       .addReg(OverflowAddrReg)
11230       .addImm(Align-1);
11231
11232     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11233       .addReg(TmpReg)
11234       .addImm(~(uint64_t)(Align-1));
11235   } else {
11236     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11237       .addReg(OverflowAddrReg);
11238   }
11239
11240   // Compute the next overflow address after this argument.
11241   // (the overflow address should be kept 8-byte aligned)
11242   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11243   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11244     .addReg(OverflowDestReg)
11245     .addImm(ArgSizeA8);
11246
11247   // Store the new overflow address.
11248   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11249     .addOperand(Base)
11250     .addOperand(Scale)
11251     .addOperand(Index)
11252     .addDisp(Disp, 8)
11253     .addOperand(Segment)
11254     .addReg(NextAddrReg)
11255     .setMemRefs(MMOBegin, MMOEnd);
11256
11257   // If we branched, emit the PHI to the front of endMBB.
11258   if (offsetMBB) {
11259     BuildMI(*endMBB, endMBB->begin(), DL,
11260             TII->get(X86::PHI), DestReg)
11261       .addReg(OffsetDestReg).addMBB(offsetMBB)
11262       .addReg(OverflowDestReg).addMBB(overflowMBB);
11263   }
11264
11265   // Erase the pseudo instruction
11266   MI->eraseFromParent();
11267
11268   return endMBB;
11269 }
11270
11271 MachineBasicBlock *
11272 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11273                                                  MachineInstr *MI,
11274                                                  MachineBasicBlock *MBB) const {
11275   // Emit code to save XMM registers to the stack. The ABI says that the
11276   // number of registers to save is given in %al, so it's theoretically
11277   // possible to do an indirect jump trick to avoid saving all of them,
11278   // however this code takes a simpler approach and just executes all
11279   // of the stores if %al is non-zero. It's less code, and it's probably
11280   // easier on the hardware branch predictor, and stores aren't all that
11281   // expensive anyway.
11282
11283   // Create the new basic blocks. One block contains all the XMM stores,
11284   // and one block is the final destination regardless of whether any
11285   // stores were performed.
11286   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11287   MachineFunction *F = MBB->getParent();
11288   MachineFunction::iterator MBBIter = MBB;
11289   ++MBBIter;
11290   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11291   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11292   F->insert(MBBIter, XMMSaveMBB);
11293   F->insert(MBBIter, EndMBB);
11294
11295   // Transfer the remainder of MBB and its successor edges to EndMBB.
11296   EndMBB->splice(EndMBB->begin(), MBB,
11297                  llvm::next(MachineBasicBlock::iterator(MI)),
11298                  MBB->end());
11299   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11300
11301   // The original block will now fall through to the XMM save block.
11302   MBB->addSuccessor(XMMSaveMBB);
11303   // The XMMSaveMBB will fall through to the end block.
11304   XMMSaveMBB->addSuccessor(EndMBB);
11305
11306   // Now add the instructions.
11307   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11308   DebugLoc DL = MI->getDebugLoc();
11309
11310   unsigned CountReg = MI->getOperand(0).getReg();
11311   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11312   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11313
11314   if (!Subtarget->isTargetWin64()) {
11315     // If %al is 0, branch around the XMM save block.
11316     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11317     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11318     MBB->addSuccessor(EndMBB);
11319   }
11320
11321   // In the XMM save block, save all the XMM argument registers.
11322   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11323     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11324     MachineMemOperand *MMO =
11325       F->getMachineMemOperand(
11326           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11327         MachineMemOperand::MOStore,
11328         /*Size=*/16, /*Align=*/16);
11329     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
11330       .addFrameIndex(RegSaveFrameIndex)
11331       .addImm(/*Scale=*/1)
11332       .addReg(/*IndexReg=*/0)
11333       .addImm(/*Disp=*/Offset)
11334       .addReg(/*Segment=*/0)
11335       .addReg(MI->getOperand(i).getReg())
11336       .addMemOperand(MMO);
11337   }
11338
11339   MI->eraseFromParent();   // The pseudo instruction is gone now.
11340
11341   return EndMBB;
11342 }
11343
11344 MachineBasicBlock *
11345 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11346                                      MachineBasicBlock *BB) const {
11347   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11348   DebugLoc DL = MI->getDebugLoc();
11349
11350   // To "insert" a SELECT_CC instruction, we actually have to insert the
11351   // diamond control-flow pattern.  The incoming instruction knows the
11352   // destination vreg to set, the condition code register to branch on, the
11353   // true/false values to select between, and a branch opcode to use.
11354   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11355   MachineFunction::iterator It = BB;
11356   ++It;
11357
11358   //  thisMBB:
11359   //  ...
11360   //   TrueVal = ...
11361   //   cmpTY ccX, r1, r2
11362   //   bCC copy1MBB
11363   //   fallthrough --> copy0MBB
11364   MachineBasicBlock *thisMBB = BB;
11365   MachineFunction *F = BB->getParent();
11366   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11367   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11368   F->insert(It, copy0MBB);
11369   F->insert(It, sinkMBB);
11370
11371   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11372   // live into the sink and copy blocks.
11373   const MachineFunction *MF = BB->getParent();
11374   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
11375   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
11376
11377   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
11378     const MachineOperand &MO = MI->getOperand(I);
11379     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
11380     unsigned Reg = MO.getReg();
11381     if (Reg != X86::EFLAGS) continue;
11382     copy0MBB->addLiveIn(Reg);
11383     sinkMBB->addLiveIn(Reg);
11384   }
11385
11386   // Transfer the remainder of BB and its successor edges to sinkMBB.
11387   sinkMBB->splice(sinkMBB->begin(), BB,
11388                   llvm::next(MachineBasicBlock::iterator(MI)),
11389                   BB->end());
11390   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11391
11392   // Add the true and fallthrough blocks as its successors.
11393   BB->addSuccessor(copy0MBB);
11394   BB->addSuccessor(sinkMBB);
11395
11396   // Create the conditional branch instruction.
11397   unsigned Opc =
11398     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11399   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11400
11401   //  copy0MBB:
11402   //   %FalseValue = ...
11403   //   # fallthrough to sinkMBB
11404   copy0MBB->addSuccessor(sinkMBB);
11405
11406   //  sinkMBB:
11407   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11408   //  ...
11409   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11410           TII->get(X86::PHI), MI->getOperand(0).getReg())
11411     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11412     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11413
11414   MI->eraseFromParent();   // The pseudo instruction is gone now.
11415   return sinkMBB;
11416 }
11417
11418 MachineBasicBlock *
11419 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11420                                           MachineBasicBlock *BB) const {
11421   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11422   DebugLoc DL = MI->getDebugLoc();
11423
11424   assert(!Subtarget->isTargetEnvMacho());
11425
11426   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11427   // non-trivial part is impdef of ESP.
11428
11429   if (Subtarget->isTargetWin64()) {
11430     if (Subtarget->isTargetCygMing()) {
11431       // ___chkstk(Mingw64):
11432       // Clobbers R10, R11, RAX and EFLAGS.
11433       // Updates RSP.
11434       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11435         .addExternalSymbol("___chkstk")
11436         .addReg(X86::RAX, RegState::Implicit)
11437         .addReg(X86::RSP, RegState::Implicit)
11438         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11439         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11440         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11441     } else {
11442       // __chkstk(MSVCRT): does not update stack pointer.
11443       // Clobbers R10, R11 and EFLAGS.
11444       // FIXME: RAX(allocated size) might be reused and not killed.
11445       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11446         .addExternalSymbol("__chkstk")
11447         .addReg(X86::RAX, RegState::Implicit)
11448         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11449       // RAX has the offset to subtracted from RSP.
11450       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11451         .addReg(X86::RSP)
11452         .addReg(X86::RAX);
11453     }
11454   } else {
11455     const char *StackProbeSymbol =
11456       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11457
11458     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11459       .addExternalSymbol(StackProbeSymbol)
11460       .addReg(X86::EAX, RegState::Implicit)
11461       .addReg(X86::ESP, RegState::Implicit)
11462       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11463       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11464       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11465   }
11466
11467   MI->eraseFromParent();   // The pseudo instruction is gone now.
11468   return BB;
11469 }
11470
11471 MachineBasicBlock *
11472 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11473                                       MachineBasicBlock *BB) const {
11474   // This is pretty easy.  We're taking the value that we received from
11475   // our load from the relocation, sticking it in either RDI (x86-64)
11476   // or EAX and doing an indirect call.  The return value will then
11477   // be in the normal return register.
11478   const X86InstrInfo *TII
11479     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11480   DebugLoc DL = MI->getDebugLoc();
11481   MachineFunction *F = BB->getParent();
11482
11483   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11484   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11485
11486   if (Subtarget->is64Bit()) {
11487     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11488                                       TII->get(X86::MOV64rm), X86::RDI)
11489     .addReg(X86::RIP)
11490     .addImm(0).addReg(0)
11491     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11492                       MI->getOperand(3).getTargetFlags())
11493     .addReg(0);
11494     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11495     addDirectMem(MIB, X86::RDI);
11496   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11497     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11498                                       TII->get(X86::MOV32rm), X86::EAX)
11499     .addReg(0)
11500     .addImm(0).addReg(0)
11501     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11502                       MI->getOperand(3).getTargetFlags())
11503     .addReg(0);
11504     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11505     addDirectMem(MIB, X86::EAX);
11506   } else {
11507     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11508                                       TII->get(X86::MOV32rm), X86::EAX)
11509     .addReg(TII->getGlobalBaseReg(F))
11510     .addImm(0).addReg(0)
11511     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11512                       MI->getOperand(3).getTargetFlags())
11513     .addReg(0);
11514     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11515     addDirectMem(MIB, X86::EAX);
11516   }
11517
11518   MI->eraseFromParent(); // The pseudo instruction is gone now.
11519   return BB;
11520 }
11521
11522 MachineBasicBlock *
11523 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11524                                                MachineBasicBlock *BB) const {
11525   switch (MI->getOpcode()) {
11526   default: assert(false && "Unexpected instr type to insert");
11527   case X86::TAILJMPd64:
11528   case X86::TAILJMPr64:
11529   case X86::TAILJMPm64:
11530     assert(!"TAILJMP64 would not be touched here.");
11531   case X86::TCRETURNdi64:
11532   case X86::TCRETURNri64:
11533   case X86::TCRETURNmi64:
11534     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11535     // On AMD64, additional defs should be added before register allocation.
11536     if (!Subtarget->isTargetWin64()) {
11537       MI->addRegisterDefined(X86::RSI);
11538       MI->addRegisterDefined(X86::RDI);
11539       MI->addRegisterDefined(X86::XMM6);
11540       MI->addRegisterDefined(X86::XMM7);
11541       MI->addRegisterDefined(X86::XMM8);
11542       MI->addRegisterDefined(X86::XMM9);
11543       MI->addRegisterDefined(X86::XMM10);
11544       MI->addRegisterDefined(X86::XMM11);
11545       MI->addRegisterDefined(X86::XMM12);
11546       MI->addRegisterDefined(X86::XMM13);
11547       MI->addRegisterDefined(X86::XMM14);
11548       MI->addRegisterDefined(X86::XMM15);
11549     }
11550     return BB;
11551   case X86::WIN_ALLOCA:
11552     return EmitLoweredWinAlloca(MI, BB);
11553   case X86::TLSCall_32:
11554   case X86::TLSCall_64:
11555     return EmitLoweredTLSCall(MI, BB);
11556   case X86::CMOV_GR8:
11557   case X86::CMOV_FR32:
11558   case X86::CMOV_FR64:
11559   case X86::CMOV_V4F32:
11560   case X86::CMOV_V2F64:
11561   case X86::CMOV_V2I64:
11562   case X86::CMOV_V8F32:
11563   case X86::CMOV_V4F64:
11564   case X86::CMOV_V4I64:
11565   case X86::CMOV_GR16:
11566   case X86::CMOV_GR32:
11567   case X86::CMOV_RFP32:
11568   case X86::CMOV_RFP64:
11569   case X86::CMOV_RFP80:
11570     return EmitLoweredSelect(MI, BB);
11571
11572   case X86::FP32_TO_INT16_IN_MEM:
11573   case X86::FP32_TO_INT32_IN_MEM:
11574   case X86::FP32_TO_INT64_IN_MEM:
11575   case X86::FP64_TO_INT16_IN_MEM:
11576   case X86::FP64_TO_INT32_IN_MEM:
11577   case X86::FP64_TO_INT64_IN_MEM:
11578   case X86::FP80_TO_INT16_IN_MEM:
11579   case X86::FP80_TO_INT32_IN_MEM:
11580   case X86::FP80_TO_INT64_IN_MEM: {
11581     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11582     DebugLoc DL = MI->getDebugLoc();
11583
11584     // Change the floating point control register to use "round towards zero"
11585     // mode when truncating to an integer value.
11586     MachineFunction *F = BB->getParent();
11587     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
11588     addFrameReference(BuildMI(*BB, MI, DL,
11589                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
11590
11591     // Load the old value of the high byte of the control word...
11592     unsigned OldCW =
11593       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
11594     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
11595                       CWFrameIdx);
11596
11597     // Set the high part to be round to zero...
11598     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
11599       .addImm(0xC7F);
11600
11601     // Reload the modified control word now...
11602     addFrameReference(BuildMI(*BB, MI, DL,
11603                               TII->get(X86::FLDCW16m)), CWFrameIdx);
11604
11605     // Restore the memory image of control word to original value
11606     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
11607       .addReg(OldCW);
11608
11609     // Get the X86 opcode to use.
11610     unsigned Opc;
11611     switch (MI->getOpcode()) {
11612     default: llvm_unreachable("illegal opcode!");
11613     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
11614     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
11615     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
11616     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
11617     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
11618     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
11619     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
11620     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
11621     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
11622     }
11623
11624     X86AddressMode AM;
11625     MachineOperand &Op = MI->getOperand(0);
11626     if (Op.isReg()) {
11627       AM.BaseType = X86AddressMode::RegBase;
11628       AM.Base.Reg = Op.getReg();
11629     } else {
11630       AM.BaseType = X86AddressMode::FrameIndexBase;
11631       AM.Base.FrameIndex = Op.getIndex();
11632     }
11633     Op = MI->getOperand(1);
11634     if (Op.isImm())
11635       AM.Scale = Op.getImm();
11636     Op = MI->getOperand(2);
11637     if (Op.isImm())
11638       AM.IndexReg = Op.getImm();
11639     Op = MI->getOperand(3);
11640     if (Op.isGlobal()) {
11641       AM.GV = Op.getGlobal();
11642     } else {
11643       AM.Disp = Op.getImm();
11644     }
11645     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
11646                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
11647
11648     // Reload the original control word now.
11649     addFrameReference(BuildMI(*BB, MI, DL,
11650                               TII->get(X86::FLDCW16m)), CWFrameIdx);
11651
11652     MI->eraseFromParent();   // The pseudo instruction is gone now.
11653     return BB;
11654   }
11655     // String/text processing lowering.
11656   case X86::PCMPISTRM128REG:
11657   case X86::VPCMPISTRM128REG:
11658     return EmitPCMP(MI, BB, 3, false /* in-mem */);
11659   case X86::PCMPISTRM128MEM:
11660   case X86::VPCMPISTRM128MEM:
11661     return EmitPCMP(MI, BB, 3, true /* in-mem */);
11662   case X86::PCMPESTRM128REG:
11663   case X86::VPCMPESTRM128REG:
11664     return EmitPCMP(MI, BB, 5, false /* in mem */);
11665   case X86::PCMPESTRM128MEM:
11666   case X86::VPCMPESTRM128MEM:
11667     return EmitPCMP(MI, BB, 5, true /* in mem */);
11668
11669     // Thread synchronization.
11670   case X86::MONITOR:
11671     return EmitMonitor(MI, BB);
11672   case X86::MWAIT:
11673     return EmitMwait(MI, BB);
11674
11675     // Atomic Lowering.
11676   case X86::ATOMAND32:
11677     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11678                                                X86::AND32ri, X86::MOV32rm,
11679                                                X86::LCMPXCHG32,
11680                                                X86::NOT32r, X86::EAX,
11681                                                X86::GR32RegisterClass);
11682   case X86::ATOMOR32:
11683     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
11684                                                X86::OR32ri, X86::MOV32rm,
11685                                                X86::LCMPXCHG32,
11686                                                X86::NOT32r, X86::EAX,
11687                                                X86::GR32RegisterClass);
11688   case X86::ATOMXOR32:
11689     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
11690                                                X86::XOR32ri, X86::MOV32rm,
11691                                                X86::LCMPXCHG32,
11692                                                X86::NOT32r, X86::EAX,
11693                                                X86::GR32RegisterClass);
11694   case X86::ATOMNAND32:
11695     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
11696                                                X86::AND32ri, X86::MOV32rm,
11697                                                X86::LCMPXCHG32,
11698                                                X86::NOT32r, X86::EAX,
11699                                                X86::GR32RegisterClass, true);
11700   case X86::ATOMMIN32:
11701     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
11702   case X86::ATOMMAX32:
11703     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
11704   case X86::ATOMUMIN32:
11705     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
11706   case X86::ATOMUMAX32:
11707     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
11708
11709   case X86::ATOMAND16:
11710     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11711                                                X86::AND16ri, X86::MOV16rm,
11712                                                X86::LCMPXCHG16,
11713                                                X86::NOT16r, X86::AX,
11714                                                X86::GR16RegisterClass);
11715   case X86::ATOMOR16:
11716     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
11717                                                X86::OR16ri, X86::MOV16rm,
11718                                                X86::LCMPXCHG16,
11719                                                X86::NOT16r, X86::AX,
11720                                                X86::GR16RegisterClass);
11721   case X86::ATOMXOR16:
11722     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
11723                                                X86::XOR16ri, X86::MOV16rm,
11724                                                X86::LCMPXCHG16,
11725                                                X86::NOT16r, X86::AX,
11726                                                X86::GR16RegisterClass);
11727   case X86::ATOMNAND16:
11728     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
11729                                                X86::AND16ri, X86::MOV16rm,
11730                                                X86::LCMPXCHG16,
11731                                                X86::NOT16r, X86::AX,
11732                                                X86::GR16RegisterClass, true);
11733   case X86::ATOMMIN16:
11734     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
11735   case X86::ATOMMAX16:
11736     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
11737   case X86::ATOMUMIN16:
11738     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
11739   case X86::ATOMUMAX16:
11740     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
11741
11742   case X86::ATOMAND8:
11743     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11744                                                X86::AND8ri, X86::MOV8rm,
11745                                                X86::LCMPXCHG8,
11746                                                X86::NOT8r, X86::AL,
11747                                                X86::GR8RegisterClass);
11748   case X86::ATOMOR8:
11749     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
11750                                                X86::OR8ri, X86::MOV8rm,
11751                                                X86::LCMPXCHG8,
11752                                                X86::NOT8r, X86::AL,
11753                                                X86::GR8RegisterClass);
11754   case X86::ATOMXOR8:
11755     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
11756                                                X86::XOR8ri, X86::MOV8rm,
11757                                                X86::LCMPXCHG8,
11758                                                X86::NOT8r, X86::AL,
11759                                                X86::GR8RegisterClass);
11760   case X86::ATOMNAND8:
11761     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
11762                                                X86::AND8ri, X86::MOV8rm,
11763                                                X86::LCMPXCHG8,
11764                                                X86::NOT8r, X86::AL,
11765                                                X86::GR8RegisterClass, true);
11766   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
11767   // This group is for 64-bit host.
11768   case X86::ATOMAND64:
11769     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11770                                                X86::AND64ri32, X86::MOV64rm,
11771                                                X86::LCMPXCHG64,
11772                                                X86::NOT64r, X86::RAX,
11773                                                X86::GR64RegisterClass);
11774   case X86::ATOMOR64:
11775     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
11776                                                X86::OR64ri32, X86::MOV64rm,
11777                                                X86::LCMPXCHG64,
11778                                                X86::NOT64r, X86::RAX,
11779                                                X86::GR64RegisterClass);
11780   case X86::ATOMXOR64:
11781     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
11782                                                X86::XOR64ri32, X86::MOV64rm,
11783                                                X86::LCMPXCHG64,
11784                                                X86::NOT64r, X86::RAX,
11785                                                X86::GR64RegisterClass);
11786   case X86::ATOMNAND64:
11787     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
11788                                                X86::AND64ri32, X86::MOV64rm,
11789                                                X86::LCMPXCHG64,
11790                                                X86::NOT64r, X86::RAX,
11791                                                X86::GR64RegisterClass, true);
11792   case X86::ATOMMIN64:
11793     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
11794   case X86::ATOMMAX64:
11795     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
11796   case X86::ATOMUMIN64:
11797     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
11798   case X86::ATOMUMAX64:
11799     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
11800
11801   // This group does 64-bit operations on a 32-bit host.
11802   case X86::ATOMAND6432:
11803     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11804                                                X86::AND32rr, X86::AND32rr,
11805                                                X86::AND32ri, X86::AND32ri,
11806                                                false);
11807   case X86::ATOMOR6432:
11808     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11809                                                X86::OR32rr, X86::OR32rr,
11810                                                X86::OR32ri, X86::OR32ri,
11811                                                false);
11812   case X86::ATOMXOR6432:
11813     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11814                                                X86::XOR32rr, X86::XOR32rr,
11815                                                X86::XOR32ri, X86::XOR32ri,
11816                                                false);
11817   case X86::ATOMNAND6432:
11818     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11819                                                X86::AND32rr, X86::AND32rr,
11820                                                X86::AND32ri, X86::AND32ri,
11821                                                true);
11822   case X86::ATOMADD6432:
11823     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11824                                                X86::ADD32rr, X86::ADC32rr,
11825                                                X86::ADD32ri, X86::ADC32ri,
11826                                                false);
11827   case X86::ATOMSUB6432:
11828     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11829                                                X86::SUB32rr, X86::SBB32rr,
11830                                                X86::SUB32ri, X86::SBB32ri,
11831                                                false);
11832   case X86::ATOMSWAP6432:
11833     return EmitAtomicBit6432WithCustomInserter(MI, BB,
11834                                                X86::MOV32rr, X86::MOV32rr,
11835                                                X86::MOV32ri, X86::MOV32ri,
11836                                                false);
11837   case X86::VASTART_SAVE_XMM_REGS:
11838     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
11839
11840   case X86::VAARG_64:
11841     return EmitVAARG64WithCustomInserter(MI, BB);
11842   }
11843 }
11844
11845 //===----------------------------------------------------------------------===//
11846 //                           X86 Optimization Hooks
11847 //===----------------------------------------------------------------------===//
11848
11849 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11850                                                        const APInt &Mask,
11851                                                        APInt &KnownZero,
11852                                                        APInt &KnownOne,
11853                                                        const SelectionDAG &DAG,
11854                                                        unsigned Depth) const {
11855   unsigned Opc = Op.getOpcode();
11856   assert((Opc >= ISD::BUILTIN_OP_END ||
11857           Opc == ISD::INTRINSIC_WO_CHAIN ||
11858           Opc == ISD::INTRINSIC_W_CHAIN ||
11859           Opc == ISD::INTRINSIC_VOID) &&
11860          "Should use MaskedValueIsZero if you don't know whether Op"
11861          " is a target node!");
11862
11863   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
11864   switch (Opc) {
11865   default: break;
11866   case X86ISD::ADD:
11867   case X86ISD::SUB:
11868   case X86ISD::ADC:
11869   case X86ISD::SBB:
11870   case X86ISD::SMUL:
11871   case X86ISD::UMUL:
11872   case X86ISD::INC:
11873   case X86ISD::DEC:
11874   case X86ISD::OR:
11875   case X86ISD::XOR:
11876   case X86ISD::AND:
11877     // These nodes' second result is a boolean.
11878     if (Op.getResNo() == 0)
11879       break;
11880     // Fallthrough
11881   case X86ISD::SETCC:
11882     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
11883                                        Mask.getBitWidth() - 1);
11884     break;
11885   }
11886 }
11887
11888 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
11889                                                          unsigned Depth) const {
11890   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
11891   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
11892     return Op.getValueType().getScalarType().getSizeInBits();
11893
11894   // Fallback case.
11895   return 1;
11896 }
11897
11898 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
11899 /// node is a GlobalAddress + offset.
11900 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
11901                                        const GlobalValue* &GA,
11902                                        int64_t &Offset) const {
11903   if (N->getOpcode() == X86ISD::Wrapper) {
11904     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
11905       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
11906       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
11907       return true;
11908     }
11909   }
11910   return TargetLowering::isGAPlusOffset(N, GA, Offset);
11911 }
11912
11913 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
11914 /// same as extracting the high 128-bit part of 256-bit vector and then
11915 /// inserting the result into the low part of a new 256-bit vector
11916 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
11917   EVT VT = SVOp->getValueType(0);
11918   int NumElems = VT.getVectorNumElements();
11919
11920   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
11921   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
11922     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
11923         SVOp->getMaskElt(j) >= 0)
11924       return false;
11925
11926   return true;
11927 }
11928
11929 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
11930 /// same as extracting the low 128-bit part of 256-bit vector and then
11931 /// inserting the result into the high part of a new 256-bit vector
11932 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
11933   EVT VT = SVOp->getValueType(0);
11934   int NumElems = VT.getVectorNumElements();
11935
11936   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
11937   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
11938     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
11939         SVOp->getMaskElt(j) >= 0)
11940       return false;
11941
11942   return true;
11943 }
11944
11945 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
11946 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
11947                                         TargetLowering::DAGCombinerInfo &DCI) {
11948   DebugLoc dl = N->getDebugLoc();
11949   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
11950   SDValue V1 = SVOp->getOperand(0);
11951   SDValue V2 = SVOp->getOperand(1);
11952   EVT VT = SVOp->getValueType(0);
11953   int NumElems = VT.getVectorNumElements();
11954
11955   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
11956       V2.getOpcode() == ISD::CONCAT_VECTORS) {
11957     //
11958     //                   0,0,0,...
11959     //                      |
11960     //    V      UNDEF    BUILD_VECTOR    UNDEF
11961     //     \      /           \           /
11962     //  CONCAT_VECTOR         CONCAT_VECTOR
11963     //         \                  /
11964     //          \                /
11965     //          RESULT: V + zero extended
11966     //
11967     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
11968         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
11969         V1.getOperand(1).getOpcode() != ISD::UNDEF)
11970       return SDValue();
11971
11972     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
11973       return SDValue();
11974
11975     // To match the shuffle mask, the first half of the mask should
11976     // be exactly the first vector, and all the rest a splat with the
11977     // first element of the second one.
11978     for (int i = 0; i < NumElems/2; ++i)
11979       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
11980           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
11981         return SDValue();
11982
11983     // Emit a zeroed vector and insert the desired subvector on its
11984     // first half.
11985     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, DAG, dl);
11986     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
11987                          DAG.getConstant(0, MVT::i32), DAG, dl);
11988     return DCI.CombineTo(N, InsV);
11989   }
11990
11991   //===--------------------------------------------------------------------===//
11992   // Combine some shuffles into subvector extracts and inserts:
11993   //
11994
11995   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
11996   if (isShuffleHigh128VectorInsertLow(SVOp)) {
11997     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
11998                                     DAG, dl);
11999     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12000                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12001     return DCI.CombineTo(N, InsV);
12002   }
12003
12004   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12005   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12006     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12007     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12008                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12009     return DCI.CombineTo(N, InsV);
12010   }
12011
12012   return SDValue();
12013 }
12014
12015 /// PerformShuffleCombine - Performs several different shuffle combines.
12016 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12017                                      TargetLowering::DAGCombinerInfo &DCI,
12018                                      const X86Subtarget *Subtarget) {
12019   DebugLoc dl = N->getDebugLoc();
12020   EVT VT = N->getValueType(0);
12021
12022   // Don't create instructions with illegal types after legalize types has run.
12023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12024   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12025     return SDValue();
12026
12027   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12028   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12029       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12030     return PerformShuffleCombine256(N, DAG, DCI);
12031
12032   // Only handle 128 wide vector from here on.
12033   if (VT.getSizeInBits() != 128)
12034     return SDValue();
12035
12036   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12037   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12038   // consecutive, non-overlapping, and in the right order.
12039   SmallVector<SDValue, 16> Elts;
12040   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12041     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12042
12043   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12044 }
12045
12046 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12047 /// generation and convert it from being a bunch of shuffles and extracts
12048 /// to a simple store and scalar loads to extract the elements.
12049 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12050                                                 const TargetLowering &TLI) {
12051   SDValue InputVector = N->getOperand(0);
12052
12053   // Only operate on vectors of 4 elements, where the alternative shuffling
12054   // gets to be more expensive.
12055   if (InputVector.getValueType() != MVT::v4i32)
12056     return SDValue();
12057
12058   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12059   // single use which is a sign-extend or zero-extend, and all elements are
12060   // used.
12061   SmallVector<SDNode *, 4> Uses;
12062   unsigned ExtractedElements = 0;
12063   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12064        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12065     if (UI.getUse().getResNo() != InputVector.getResNo())
12066       return SDValue();
12067
12068     SDNode *Extract = *UI;
12069     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12070       return SDValue();
12071
12072     if (Extract->getValueType(0) != MVT::i32)
12073       return SDValue();
12074     if (!Extract->hasOneUse())
12075       return SDValue();
12076     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12077         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12078       return SDValue();
12079     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12080       return SDValue();
12081
12082     // Record which element was extracted.
12083     ExtractedElements |=
12084       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12085
12086     Uses.push_back(Extract);
12087   }
12088
12089   // If not all the elements were used, this may not be worthwhile.
12090   if (ExtractedElements != 15)
12091     return SDValue();
12092
12093   // Ok, we've now decided to do the transformation.
12094   DebugLoc dl = InputVector.getDebugLoc();
12095
12096   // Store the value to a temporary stack slot.
12097   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12098   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12099                             MachinePointerInfo(), false, false, 0);
12100
12101   // Replace each use (extract) with a load of the appropriate element.
12102   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12103        UE = Uses.end(); UI != UE; ++UI) {
12104     SDNode *Extract = *UI;
12105
12106     // cOMpute the element's address.
12107     SDValue Idx = Extract->getOperand(1);
12108     unsigned EltSize =
12109         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12110     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12111     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12112
12113     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12114                                      StackPtr, OffsetVal);
12115
12116     // Load the scalar.
12117     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12118                                      ScalarAddr, MachinePointerInfo(),
12119                                      false, false, 0);
12120
12121     // Replace the exact with the load.
12122     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12123   }
12124
12125   // The replacement was made in place; don't return anything.
12126   return SDValue();
12127 }
12128
12129 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
12130 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12131                                     const X86Subtarget *Subtarget) {
12132   DebugLoc DL = N->getDebugLoc();
12133   SDValue Cond = N->getOperand(0);
12134   // Get the LHS/RHS of the select.
12135   SDValue LHS = N->getOperand(1);
12136   SDValue RHS = N->getOperand(2);
12137
12138   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12139   // instructions match the semantics of the common C idiom x<y?x:y but not
12140   // x<=y?x:y, because of how they handle negative zero (which can be
12141   // ignored in unsafe-math mode).
12142   if (Subtarget->hasSSE2() &&
12143       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
12144       Cond.getOpcode() == ISD::SETCC) {
12145     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12146
12147     unsigned Opcode = 0;
12148     // Check for x CC y ? x : y.
12149     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12150         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12151       switch (CC) {
12152       default: break;
12153       case ISD::SETULT:
12154         // Converting this to a min would handle NaNs incorrectly, and swapping
12155         // the operands would cause it to handle comparisons between positive
12156         // and negative zero incorrectly.
12157         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12158           if (!UnsafeFPMath &&
12159               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12160             break;
12161           std::swap(LHS, RHS);
12162         }
12163         Opcode = X86ISD::FMIN;
12164         break;
12165       case ISD::SETOLE:
12166         // Converting this to a min would handle comparisons between positive
12167         // and negative zero incorrectly.
12168         if (!UnsafeFPMath &&
12169             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12170           break;
12171         Opcode = X86ISD::FMIN;
12172         break;
12173       case ISD::SETULE:
12174         // Converting this to a min would handle both negative zeros and NaNs
12175         // incorrectly, but we can swap the operands to fix both.
12176         std::swap(LHS, RHS);
12177       case ISD::SETOLT:
12178       case ISD::SETLT:
12179       case ISD::SETLE:
12180         Opcode = X86ISD::FMIN;
12181         break;
12182
12183       case ISD::SETOGE:
12184         // Converting this to a max would handle comparisons between positive
12185         // and negative zero incorrectly.
12186         if (!UnsafeFPMath &&
12187             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12188           break;
12189         Opcode = X86ISD::FMAX;
12190         break;
12191       case ISD::SETUGT:
12192         // Converting this to a max would handle NaNs incorrectly, and swapping
12193         // the operands would cause it to handle comparisons between positive
12194         // and negative zero incorrectly.
12195         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12196           if (!UnsafeFPMath &&
12197               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12198             break;
12199           std::swap(LHS, RHS);
12200         }
12201         Opcode = X86ISD::FMAX;
12202         break;
12203       case ISD::SETUGE:
12204         // Converting this to a max would handle both negative zeros and NaNs
12205         // incorrectly, but we can swap the operands to fix both.
12206         std::swap(LHS, RHS);
12207       case ISD::SETOGT:
12208       case ISD::SETGT:
12209       case ISD::SETGE:
12210         Opcode = X86ISD::FMAX;
12211         break;
12212       }
12213     // Check for x CC y ? y : x -- a min/max with reversed arms.
12214     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12215                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12216       switch (CC) {
12217       default: break;
12218       case ISD::SETOGE:
12219         // Converting this to a min would handle comparisons between positive
12220         // and negative zero incorrectly, and swapping the operands would
12221         // cause it to handle NaNs incorrectly.
12222         if (!UnsafeFPMath &&
12223             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12224           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12225             break;
12226           std::swap(LHS, RHS);
12227         }
12228         Opcode = X86ISD::FMIN;
12229         break;
12230       case ISD::SETUGT:
12231         // Converting this to a min would handle NaNs incorrectly.
12232         if (!UnsafeFPMath &&
12233             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12234           break;
12235         Opcode = X86ISD::FMIN;
12236         break;
12237       case ISD::SETUGE:
12238         // Converting this to a min would handle both negative zeros and NaNs
12239         // incorrectly, but we can swap the operands to fix both.
12240         std::swap(LHS, RHS);
12241       case ISD::SETOGT:
12242       case ISD::SETGT:
12243       case ISD::SETGE:
12244         Opcode = X86ISD::FMIN;
12245         break;
12246
12247       case ISD::SETULT:
12248         // Converting this to a max would handle NaNs incorrectly.
12249         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12250           break;
12251         Opcode = X86ISD::FMAX;
12252         break;
12253       case ISD::SETOLE:
12254         // Converting this to a max would handle comparisons between positive
12255         // and negative zero incorrectly, and swapping the operands would
12256         // cause it to handle NaNs incorrectly.
12257         if (!UnsafeFPMath &&
12258             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12259           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12260             break;
12261           std::swap(LHS, RHS);
12262         }
12263         Opcode = X86ISD::FMAX;
12264         break;
12265       case ISD::SETULE:
12266         // Converting this to a max would handle both negative zeros and NaNs
12267         // incorrectly, but we can swap the operands to fix both.
12268         std::swap(LHS, RHS);
12269       case ISD::SETOLT:
12270       case ISD::SETLT:
12271       case ISD::SETLE:
12272         Opcode = X86ISD::FMAX;
12273         break;
12274       }
12275     }
12276
12277     if (Opcode)
12278       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12279   }
12280
12281   // If this is a select between two integer constants, try to do some
12282   // optimizations.
12283   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12284     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12285       // Don't do this for crazy integer types.
12286       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12287         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12288         // so that TrueC (the true value) is larger than FalseC.
12289         bool NeedsCondInvert = false;
12290
12291         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12292             // Efficiently invertible.
12293             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12294              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12295               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12296           NeedsCondInvert = true;
12297           std::swap(TrueC, FalseC);
12298         }
12299
12300         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12301         if (FalseC->getAPIntValue() == 0 &&
12302             TrueC->getAPIntValue().isPowerOf2()) {
12303           if (NeedsCondInvert) // Invert the condition if needed.
12304             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12305                                DAG.getConstant(1, Cond.getValueType()));
12306
12307           // Zero extend the condition if needed.
12308           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12309
12310           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12311           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12312                              DAG.getConstant(ShAmt, MVT::i8));
12313         }
12314
12315         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12316         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12317           if (NeedsCondInvert) // Invert the condition if needed.
12318             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12319                                DAG.getConstant(1, Cond.getValueType()));
12320
12321           // Zero extend the condition if needed.
12322           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12323                              FalseC->getValueType(0), Cond);
12324           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12325                              SDValue(FalseC, 0));
12326         }
12327
12328         // Optimize cases that will turn into an LEA instruction.  This requires
12329         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12330         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12331           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12332           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12333
12334           bool isFastMultiplier = false;
12335           if (Diff < 10) {
12336             switch ((unsigned char)Diff) {
12337               default: break;
12338               case 1:  // result = add base, cond
12339               case 2:  // result = lea base(    , cond*2)
12340               case 3:  // result = lea base(cond, cond*2)
12341               case 4:  // result = lea base(    , cond*4)
12342               case 5:  // result = lea base(cond, cond*4)
12343               case 8:  // result = lea base(    , cond*8)
12344               case 9:  // result = lea base(cond, cond*8)
12345                 isFastMultiplier = true;
12346                 break;
12347             }
12348           }
12349
12350           if (isFastMultiplier) {
12351             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12352             if (NeedsCondInvert) // Invert the condition if needed.
12353               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12354                                  DAG.getConstant(1, Cond.getValueType()));
12355
12356             // Zero extend the condition if needed.
12357             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12358                                Cond);
12359             // Scale the condition by the difference.
12360             if (Diff != 1)
12361               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12362                                  DAG.getConstant(Diff, Cond.getValueType()));
12363
12364             // Add the base if non-zero.
12365             if (FalseC->getAPIntValue() != 0)
12366               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12367                                  SDValue(FalseC, 0));
12368             return Cond;
12369           }
12370         }
12371       }
12372   }
12373
12374   return SDValue();
12375 }
12376
12377 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12378 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12379                                   TargetLowering::DAGCombinerInfo &DCI) {
12380   DebugLoc DL = N->getDebugLoc();
12381
12382   // If the flag operand isn't dead, don't touch this CMOV.
12383   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12384     return SDValue();
12385
12386   SDValue FalseOp = N->getOperand(0);
12387   SDValue TrueOp = N->getOperand(1);
12388   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12389   SDValue Cond = N->getOperand(3);
12390   if (CC == X86::COND_E || CC == X86::COND_NE) {
12391     switch (Cond.getOpcode()) {
12392     default: break;
12393     case X86ISD::BSR:
12394     case X86ISD::BSF:
12395       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12396       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12397         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12398     }
12399   }
12400
12401   // If this is a select between two integer constants, try to do some
12402   // optimizations.  Note that the operands are ordered the opposite of SELECT
12403   // operands.
12404   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12405     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12406       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12407       // larger than FalseC (the false value).
12408       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12409         CC = X86::GetOppositeBranchCondition(CC);
12410         std::swap(TrueC, FalseC);
12411       }
12412
12413       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12414       // This is efficient for any integer data type (including i8/i16) and
12415       // shift amount.
12416       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12417         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12418                            DAG.getConstant(CC, MVT::i8), Cond);
12419
12420         // Zero extend the condition if needed.
12421         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12422
12423         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12424         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12425                            DAG.getConstant(ShAmt, MVT::i8));
12426         if (N->getNumValues() == 2)  // Dead flag value?
12427           return DCI.CombineTo(N, Cond, SDValue());
12428         return Cond;
12429       }
12430
12431       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12432       // for any integer data type, including i8/i16.
12433       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12434         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12435                            DAG.getConstant(CC, MVT::i8), Cond);
12436
12437         // Zero extend the condition if needed.
12438         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12439                            FalseC->getValueType(0), Cond);
12440         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12441                            SDValue(FalseC, 0));
12442
12443         if (N->getNumValues() == 2)  // Dead flag value?
12444           return DCI.CombineTo(N, Cond, SDValue());
12445         return Cond;
12446       }
12447
12448       // Optimize cases that will turn into an LEA instruction.  This requires
12449       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12450       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12451         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12452         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12453
12454         bool isFastMultiplier = false;
12455         if (Diff < 10) {
12456           switch ((unsigned char)Diff) {
12457           default: break;
12458           case 1:  // result = add base, cond
12459           case 2:  // result = lea base(    , cond*2)
12460           case 3:  // result = lea base(cond, cond*2)
12461           case 4:  // result = lea base(    , cond*4)
12462           case 5:  // result = lea base(cond, cond*4)
12463           case 8:  // result = lea base(    , cond*8)
12464           case 9:  // result = lea base(cond, cond*8)
12465             isFastMultiplier = true;
12466             break;
12467           }
12468         }
12469
12470         if (isFastMultiplier) {
12471           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12472           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12473                              DAG.getConstant(CC, MVT::i8), Cond);
12474           // Zero extend the condition if needed.
12475           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12476                              Cond);
12477           // Scale the condition by the difference.
12478           if (Diff != 1)
12479             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12480                                DAG.getConstant(Diff, Cond.getValueType()));
12481
12482           // Add the base if non-zero.
12483           if (FalseC->getAPIntValue() != 0)
12484             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12485                                SDValue(FalseC, 0));
12486           if (N->getNumValues() == 2)  // Dead flag value?
12487             return DCI.CombineTo(N, Cond, SDValue());
12488           return Cond;
12489         }
12490       }
12491     }
12492   }
12493   return SDValue();
12494 }
12495
12496
12497 /// PerformMulCombine - Optimize a single multiply with constant into two
12498 /// in order to implement it with two cheaper instructions, e.g.
12499 /// LEA + SHL, LEA + LEA.
12500 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12501                                  TargetLowering::DAGCombinerInfo &DCI) {
12502   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12503     return SDValue();
12504
12505   EVT VT = N->getValueType(0);
12506   if (VT != MVT::i64)
12507     return SDValue();
12508
12509   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12510   if (!C)
12511     return SDValue();
12512   uint64_t MulAmt = C->getZExtValue();
12513   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12514     return SDValue();
12515
12516   uint64_t MulAmt1 = 0;
12517   uint64_t MulAmt2 = 0;
12518   if ((MulAmt % 9) == 0) {
12519     MulAmt1 = 9;
12520     MulAmt2 = MulAmt / 9;
12521   } else if ((MulAmt % 5) == 0) {
12522     MulAmt1 = 5;
12523     MulAmt2 = MulAmt / 5;
12524   } else if ((MulAmt % 3) == 0) {
12525     MulAmt1 = 3;
12526     MulAmt2 = MulAmt / 3;
12527   }
12528   if (MulAmt2 &&
12529       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
12530     DebugLoc DL = N->getDebugLoc();
12531
12532     if (isPowerOf2_64(MulAmt2) &&
12533         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
12534       // If second multiplifer is pow2, issue it first. We want the multiply by
12535       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
12536       // is an add.
12537       std::swap(MulAmt1, MulAmt2);
12538
12539     SDValue NewMul;
12540     if (isPowerOf2_64(MulAmt1))
12541       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
12542                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
12543     else
12544       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
12545                            DAG.getConstant(MulAmt1, VT));
12546
12547     if (isPowerOf2_64(MulAmt2))
12548       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
12549                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
12550     else
12551       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
12552                            DAG.getConstant(MulAmt2, VT));
12553
12554     // Do not add new nodes to DAG combiner worklist.
12555     DCI.CombineTo(N, NewMul, false);
12556   }
12557   return SDValue();
12558 }
12559
12560 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
12561   SDValue N0 = N->getOperand(0);
12562   SDValue N1 = N->getOperand(1);
12563   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12564   EVT VT = N0.getValueType();
12565
12566   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
12567   // since the result of setcc_c is all zero's or all ones.
12568   if (N1C && N0.getOpcode() == ISD::AND &&
12569       N0.getOperand(1).getOpcode() == ISD::Constant) {
12570     SDValue N00 = N0.getOperand(0);
12571     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
12572         ((N00.getOpcode() == ISD::ANY_EXTEND ||
12573           N00.getOpcode() == ISD::ZERO_EXTEND) &&
12574          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
12575       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
12576       APInt ShAmt = N1C->getAPIntValue();
12577       Mask = Mask.shl(ShAmt);
12578       if (Mask != 0)
12579         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
12580                            N00, DAG.getConstant(Mask, VT));
12581     }
12582   }
12583
12584   return SDValue();
12585 }
12586
12587 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
12588 ///                       when possible.
12589 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
12590                                    const X86Subtarget *Subtarget) {
12591   EVT VT = N->getValueType(0);
12592   if (!VT.isVector() && VT.isInteger() &&
12593       N->getOpcode() == ISD::SHL)
12594     return PerformSHLCombine(N, DAG);
12595
12596   // On X86 with SSE2 support, we can transform this to a vector shift if
12597   // all elements are shifted by the same amount.  We can't do this in legalize
12598   // because the a constant vector is typically transformed to a constant pool
12599   // so we have no knowledge of the shift amount.
12600   if (!(Subtarget->hasSSE2() || Subtarget->hasAVX()))
12601     return SDValue();
12602
12603   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
12604     return SDValue();
12605
12606   SDValue ShAmtOp = N->getOperand(1);
12607   EVT EltVT = VT.getVectorElementType();
12608   DebugLoc DL = N->getDebugLoc();
12609   SDValue BaseShAmt = SDValue();
12610   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
12611     unsigned NumElts = VT.getVectorNumElements();
12612     unsigned i = 0;
12613     for (; i != NumElts; ++i) {
12614       SDValue Arg = ShAmtOp.getOperand(i);
12615       if (Arg.getOpcode() == ISD::UNDEF) continue;
12616       BaseShAmt = Arg;
12617       break;
12618     }
12619     for (; i != NumElts; ++i) {
12620       SDValue Arg = ShAmtOp.getOperand(i);
12621       if (Arg.getOpcode() == ISD::UNDEF) continue;
12622       if (Arg != BaseShAmt) {
12623         return SDValue();
12624       }
12625     }
12626   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
12627              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
12628     SDValue InVec = ShAmtOp.getOperand(0);
12629     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12630       unsigned NumElts = InVec.getValueType().getVectorNumElements();
12631       unsigned i = 0;
12632       for (; i != NumElts; ++i) {
12633         SDValue Arg = InVec.getOperand(i);
12634         if (Arg.getOpcode() == ISD::UNDEF) continue;
12635         BaseShAmt = Arg;
12636         break;
12637       }
12638     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12639        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12640          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
12641          if (C->getZExtValue() == SplatIdx)
12642            BaseShAmt = InVec.getOperand(1);
12643        }
12644     }
12645     if (BaseShAmt.getNode() == 0)
12646       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
12647                               DAG.getIntPtrConstant(0));
12648   } else
12649     return SDValue();
12650
12651   // The shift amount is an i32.
12652   if (EltVT.bitsGT(MVT::i32))
12653     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
12654   else if (EltVT.bitsLT(MVT::i32))
12655     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
12656
12657   // The shift amount is identical so we can do a vector shift.
12658   SDValue  ValOp = N->getOperand(0);
12659   switch (N->getOpcode()) {
12660   default:
12661     llvm_unreachable("Unknown shift opcode!");
12662     break;
12663   case ISD::SHL:
12664     if (VT == MVT::v2i64)
12665       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12666                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
12667                          ValOp, BaseShAmt);
12668     if (VT == MVT::v4i32)
12669       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12670                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
12671                          ValOp, BaseShAmt);
12672     if (VT == MVT::v8i16)
12673       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12674                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
12675                          ValOp, BaseShAmt);
12676     break;
12677   case ISD::SRA:
12678     if (VT == MVT::v4i32)
12679       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12680                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
12681                          ValOp, BaseShAmt);
12682     if (VT == MVT::v8i16)
12683       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12684                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
12685                          ValOp, BaseShAmt);
12686     break;
12687   case ISD::SRL:
12688     if (VT == MVT::v2i64)
12689       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12690                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
12691                          ValOp, BaseShAmt);
12692     if (VT == MVT::v4i32)
12693       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12694                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
12695                          ValOp, BaseShAmt);
12696     if (VT ==  MVT::v8i16)
12697       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
12698                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
12699                          ValOp, BaseShAmt);
12700     break;
12701   }
12702   return SDValue();
12703 }
12704
12705
12706 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
12707 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
12708 // and friends.  Likewise for OR -> CMPNEQSS.
12709 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
12710                             TargetLowering::DAGCombinerInfo &DCI,
12711                             const X86Subtarget *Subtarget) {
12712   unsigned opcode;
12713
12714   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
12715   // we're requiring SSE2 for both.
12716   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
12717     SDValue N0 = N->getOperand(0);
12718     SDValue N1 = N->getOperand(1);
12719     SDValue CMP0 = N0->getOperand(1);
12720     SDValue CMP1 = N1->getOperand(1);
12721     DebugLoc DL = N->getDebugLoc();
12722
12723     // The SETCCs should both refer to the same CMP.
12724     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
12725       return SDValue();
12726
12727     SDValue CMP00 = CMP0->getOperand(0);
12728     SDValue CMP01 = CMP0->getOperand(1);
12729     EVT     VT    = CMP00.getValueType();
12730
12731     if (VT == MVT::f32 || VT == MVT::f64) {
12732       bool ExpectingFlags = false;
12733       // Check for any users that want flags:
12734       for (SDNode::use_iterator UI = N->use_begin(),
12735              UE = N->use_end();
12736            !ExpectingFlags && UI != UE; ++UI)
12737         switch (UI->getOpcode()) {
12738         default:
12739         case ISD::BR_CC:
12740         case ISD::BRCOND:
12741         case ISD::SELECT:
12742           ExpectingFlags = true;
12743           break;
12744         case ISD::CopyToReg:
12745         case ISD::SIGN_EXTEND:
12746         case ISD::ZERO_EXTEND:
12747         case ISD::ANY_EXTEND:
12748           break;
12749         }
12750
12751       if (!ExpectingFlags) {
12752         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
12753         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
12754
12755         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
12756           X86::CondCode tmp = cc0;
12757           cc0 = cc1;
12758           cc1 = tmp;
12759         }
12760
12761         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
12762             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
12763           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
12764           X86ISD::NodeType NTOperator = is64BitFP ?
12765             X86ISD::FSETCCsd : X86ISD::FSETCCss;
12766           // FIXME: need symbolic constants for these magic numbers.
12767           // See X86ATTInstPrinter.cpp:printSSECC().
12768           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
12769           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
12770                                               DAG.getConstant(x86cc, MVT::i8));
12771           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
12772                                               OnesOrZeroesF);
12773           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
12774                                       DAG.getConstant(1, MVT::i32));
12775           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
12776           return OneBitOfTruth;
12777         }
12778       }
12779     }
12780   }
12781   return SDValue();
12782 }
12783
12784 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
12785 /// so it can be folded inside ANDNP.
12786 static bool CanFoldXORWithAllOnes(const SDNode *N) {
12787   EVT VT = N->getValueType(0);
12788
12789   // Match direct AllOnes for 128 and 256-bit vectors
12790   if (ISD::isBuildVectorAllOnes(N))
12791     return true;
12792
12793   // Look through a bit convert.
12794   if (N->getOpcode() == ISD::BITCAST)
12795     N = N->getOperand(0).getNode();
12796
12797   // Sometimes the operand may come from a insert_subvector building a 256-bit
12798   // allones vector
12799   if (VT.getSizeInBits() == 256 &&
12800       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
12801     SDValue V1 = N->getOperand(0);
12802     SDValue V2 = N->getOperand(1);
12803
12804     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
12805         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
12806         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
12807         ISD::isBuildVectorAllOnes(V2.getNode()))
12808       return true;
12809   }
12810
12811   return false;
12812 }
12813
12814 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
12815                                  TargetLowering::DAGCombinerInfo &DCI,
12816                                  const X86Subtarget *Subtarget) {
12817   if (DCI.isBeforeLegalizeOps())
12818     return SDValue();
12819
12820   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12821   if (R.getNode())
12822     return R;
12823
12824   // Want to form ANDNP nodes:
12825   // 1) In the hopes of then easily combining them with OR and AND nodes
12826   //    to form PBLEND/PSIGN.
12827   // 2) To match ANDN packed intrinsics
12828   EVT VT = N->getValueType(0);
12829   if (VT != MVT::v2i64 && VT != MVT::v4i64)
12830     return SDValue();
12831
12832   SDValue N0 = N->getOperand(0);
12833   SDValue N1 = N->getOperand(1);
12834   DebugLoc DL = N->getDebugLoc();
12835
12836   // Check LHS for vnot
12837   if (N0.getOpcode() == ISD::XOR &&
12838       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
12839       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
12840     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
12841
12842   // Check RHS for vnot
12843   if (N1.getOpcode() == ISD::XOR &&
12844       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
12845       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
12846     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
12847
12848   return SDValue();
12849 }
12850
12851 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
12852                                 TargetLowering::DAGCombinerInfo &DCI,
12853                                 const X86Subtarget *Subtarget) {
12854   if (DCI.isBeforeLegalizeOps())
12855     return SDValue();
12856
12857   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
12858   if (R.getNode())
12859     return R;
12860
12861   EVT VT = N->getValueType(0);
12862   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
12863     return SDValue();
12864
12865   SDValue N0 = N->getOperand(0);
12866   SDValue N1 = N->getOperand(1);
12867
12868   // look for psign/blend
12869   if (Subtarget->hasSSSE3()) {
12870     if (VT == MVT::v2i64) {
12871       // Canonicalize pandn to RHS
12872       if (N0.getOpcode() == X86ISD::ANDNP)
12873         std::swap(N0, N1);
12874       // or (and (m, x), (pandn m, y))
12875       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
12876         SDValue Mask = N1.getOperand(0);
12877         SDValue X    = N1.getOperand(1);
12878         SDValue Y;
12879         if (N0.getOperand(0) == Mask)
12880           Y = N0.getOperand(1);
12881         if (N0.getOperand(1) == Mask)
12882           Y = N0.getOperand(0);
12883
12884         // Check to see if the mask appeared in both the AND and ANDNP and
12885         if (!Y.getNode())
12886           return SDValue();
12887
12888         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
12889         if (Mask.getOpcode() != ISD::BITCAST ||
12890             X.getOpcode() != ISD::BITCAST ||
12891             Y.getOpcode() != ISD::BITCAST)
12892           return SDValue();
12893
12894         // Look through mask bitcast.
12895         Mask = Mask.getOperand(0);
12896         EVT MaskVT = Mask.getValueType();
12897
12898         // Validate that the Mask operand is a vector sra node.  The sra node
12899         // will be an intrinsic.
12900         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
12901           return SDValue();
12902
12903         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
12904         // there is no psrai.b
12905         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
12906         case Intrinsic::x86_sse2_psrai_w:
12907         case Intrinsic::x86_sse2_psrai_d:
12908           break;
12909         default: return SDValue();
12910         }
12911
12912         // Check that the SRA is all signbits.
12913         SDValue SraC = Mask.getOperand(2);
12914         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
12915         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
12916         if ((SraAmt + 1) != EltBits)
12917           return SDValue();
12918
12919         DebugLoc DL = N->getDebugLoc();
12920
12921         // Now we know we at least have a plendvb with the mask val.  See if
12922         // we can form a psignb/w/d.
12923         // psign = x.type == y.type == mask.type && y = sub(0, x);
12924         X = X.getOperand(0);
12925         Y = Y.getOperand(0);
12926         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
12927             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
12928             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
12929           unsigned Opc = 0;
12930           switch (EltBits) {
12931           case 8: Opc = X86ISD::PSIGNB; break;
12932           case 16: Opc = X86ISD::PSIGNW; break;
12933           case 32: Opc = X86ISD::PSIGND; break;
12934           default: break;
12935           }
12936           if (Opc) {
12937             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
12938             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
12939           }
12940         }
12941         // PBLENDVB only available on SSE 4.1
12942         if (!Subtarget->hasSSE41())
12943           return SDValue();
12944
12945         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
12946         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
12947         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
12948         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
12949         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
12950       }
12951     }
12952   }
12953
12954   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
12955   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
12956     std::swap(N0, N1);
12957   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
12958     return SDValue();
12959   if (!N0.hasOneUse() || !N1.hasOneUse())
12960     return SDValue();
12961
12962   SDValue ShAmt0 = N0.getOperand(1);
12963   if (ShAmt0.getValueType() != MVT::i8)
12964     return SDValue();
12965   SDValue ShAmt1 = N1.getOperand(1);
12966   if (ShAmt1.getValueType() != MVT::i8)
12967     return SDValue();
12968   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
12969     ShAmt0 = ShAmt0.getOperand(0);
12970   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
12971     ShAmt1 = ShAmt1.getOperand(0);
12972
12973   DebugLoc DL = N->getDebugLoc();
12974   unsigned Opc = X86ISD::SHLD;
12975   SDValue Op0 = N0.getOperand(0);
12976   SDValue Op1 = N1.getOperand(0);
12977   if (ShAmt0.getOpcode() == ISD::SUB) {
12978     Opc = X86ISD::SHRD;
12979     std::swap(Op0, Op1);
12980     std::swap(ShAmt0, ShAmt1);
12981   }
12982
12983   unsigned Bits = VT.getSizeInBits();
12984   if (ShAmt1.getOpcode() == ISD::SUB) {
12985     SDValue Sum = ShAmt1.getOperand(0);
12986     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
12987       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
12988       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
12989         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
12990       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
12991         return DAG.getNode(Opc, DL, VT,
12992                            Op0, Op1,
12993                            DAG.getNode(ISD::TRUNCATE, DL,
12994                                        MVT::i8, ShAmt0));
12995     }
12996   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
12997     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
12998     if (ShAmt0C &&
12999         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13000       return DAG.getNode(Opc, DL, VT,
13001                          N0.getOperand(0), N1.getOperand(0),
13002                          DAG.getNode(ISD::TRUNCATE, DL,
13003                                        MVT::i8, ShAmt0));
13004   }
13005
13006   return SDValue();
13007 }
13008
13009 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13010 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13011                                    const X86Subtarget *Subtarget) {
13012   StoreSDNode *St = cast<StoreSDNode>(N);
13013   EVT VT = St->getValue().getValueType();
13014   EVT StVT = St->getMemoryVT();
13015   DebugLoc dl = St->getDebugLoc();
13016   SDValue StoredVal = St->getOperand(1);
13017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13018
13019   // If we are saving a concatination of two XMM registers, perform two stores.
13020   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13021   // 128-bit ones. If in the future the cost becomes only one memory access the
13022   // first version would be better.
13023   if (VT.getSizeInBits() == 256 &&
13024     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13025     StoredVal.getNumOperands() == 2) {
13026
13027     SDValue Value0 = StoredVal.getOperand(0);
13028     SDValue Value1 = StoredVal.getOperand(1);
13029
13030     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13031     SDValue Ptr0 = St->getBasePtr();
13032     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13033
13034     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13035                                 St->getPointerInfo(), St->isVolatile(),
13036                                 St->isNonTemporal(), St->getAlignment());
13037     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13038                                 St->getPointerInfo(), St->isVolatile(),
13039                                 St->isNonTemporal(), St->getAlignment());
13040     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13041   }
13042
13043   // Optimize trunc store (of multiple scalars) to shuffle and store.
13044   // First, pack all of the elements in one place. Next, store to memory
13045   // in fewer chunks.
13046   if (St->isTruncatingStore() && VT.isVector()) {
13047     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13048     unsigned NumElems = VT.getVectorNumElements();
13049     assert(StVT != VT && "Cannot truncate to the same type");
13050     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13051     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13052
13053     // From, To sizes and ElemCount must be pow of two
13054     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13055     // We are going to use the original vector elt for storing.
13056     // accumulated smaller vector elements must be a multiple of bigger size.
13057     if (0 != (NumElems * ToSz) % FromSz) return SDValue();
13058     unsigned SizeRatio  = FromSz / ToSz;
13059
13060     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13061
13062     // Create a type on which we perform the shuffle
13063     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13064             StVT.getScalarType(), NumElems*SizeRatio);
13065
13066     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13067
13068     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13069     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13070     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13071
13072     // Can't shuffle using an illegal type
13073     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13074
13075     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13076                                 DAG.getUNDEF(WideVec.getValueType()),
13077                                 ShuffleVec.data());
13078     // At this point all of the data is stored at the bottom of the
13079     // register. We now need to save it to mem.
13080
13081     // Find the largest store unit
13082     MVT StoreType = MVT::i8;
13083     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13084          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13085       MVT Tp = (MVT::SimpleValueType)tp;
13086       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13087         StoreType = Tp;
13088     }
13089
13090     // Bitcast the original vector into a vector of store-size units
13091     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13092             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13093     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13094     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13095     SmallVector<SDValue, 8> Chains;
13096     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13097                                         TLI.getPointerTy());
13098     SDValue Ptr = St->getBasePtr();
13099
13100     // Perform one or more big stores into memory.
13101     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13102       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13103                                    StoreType, ShuffWide,
13104                                    DAG.getIntPtrConstant(i));
13105       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13106                                 St->getPointerInfo(), St->isVolatile(),
13107                                 St->isNonTemporal(), St->getAlignment());
13108       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13109       Chains.push_back(Ch);
13110     }
13111
13112     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13113                                Chains.size());
13114   }
13115
13116
13117   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13118   // the FP state in cases where an emms may be missing.
13119   // A preferable solution to the general problem is to figure out the right
13120   // places to insert EMMS.  This qualifies as a quick hack.
13121
13122   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13123   if (VT.getSizeInBits() != 64)
13124     return SDValue();
13125
13126   const Function *F = DAG.getMachineFunction().getFunction();
13127   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13128   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13129     && Subtarget->hasSSE2();
13130   if ((VT.isVector() ||
13131        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13132       isa<LoadSDNode>(St->getValue()) &&
13133       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13134       St->getChain().hasOneUse() && !St->isVolatile()) {
13135     SDNode* LdVal = St->getValue().getNode();
13136     LoadSDNode *Ld = 0;
13137     int TokenFactorIndex = -1;
13138     SmallVector<SDValue, 8> Ops;
13139     SDNode* ChainVal = St->getChain().getNode();
13140     // Must be a store of a load.  We currently handle two cases:  the load
13141     // is a direct child, and it's under an intervening TokenFactor.  It is
13142     // possible to dig deeper under nested TokenFactors.
13143     if (ChainVal == LdVal)
13144       Ld = cast<LoadSDNode>(St->getChain());
13145     else if (St->getValue().hasOneUse() &&
13146              ChainVal->getOpcode() == ISD::TokenFactor) {
13147       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13148         if (ChainVal->getOperand(i).getNode() == LdVal) {
13149           TokenFactorIndex = i;
13150           Ld = cast<LoadSDNode>(St->getValue());
13151         } else
13152           Ops.push_back(ChainVal->getOperand(i));
13153       }
13154     }
13155
13156     if (!Ld || !ISD::isNormalLoad(Ld))
13157       return SDValue();
13158
13159     // If this is not the MMX case, i.e. we are just turning i64 load/store
13160     // into f64 load/store, avoid the transformation if there are multiple
13161     // uses of the loaded value.
13162     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13163       return SDValue();
13164
13165     DebugLoc LdDL = Ld->getDebugLoc();
13166     DebugLoc StDL = N->getDebugLoc();
13167     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13168     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13169     // pair instead.
13170     if (Subtarget->is64Bit() || F64IsLegal) {
13171       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13172       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13173                                   Ld->getPointerInfo(), Ld->isVolatile(),
13174                                   Ld->isNonTemporal(), Ld->getAlignment());
13175       SDValue NewChain = NewLd.getValue(1);
13176       if (TokenFactorIndex != -1) {
13177         Ops.push_back(NewChain);
13178         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13179                                Ops.size());
13180       }
13181       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13182                           St->getPointerInfo(),
13183                           St->isVolatile(), St->isNonTemporal(),
13184                           St->getAlignment());
13185     }
13186
13187     // Otherwise, lower to two pairs of 32-bit loads / stores.
13188     SDValue LoAddr = Ld->getBasePtr();
13189     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13190                                  DAG.getConstant(4, MVT::i32));
13191
13192     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13193                                Ld->getPointerInfo(),
13194                                Ld->isVolatile(), Ld->isNonTemporal(),
13195                                Ld->getAlignment());
13196     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13197                                Ld->getPointerInfo().getWithOffset(4),
13198                                Ld->isVolatile(), Ld->isNonTemporal(),
13199                                MinAlign(Ld->getAlignment(), 4));
13200
13201     SDValue NewChain = LoLd.getValue(1);
13202     if (TokenFactorIndex != -1) {
13203       Ops.push_back(LoLd);
13204       Ops.push_back(HiLd);
13205       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13206                              Ops.size());
13207     }
13208
13209     LoAddr = St->getBasePtr();
13210     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13211                          DAG.getConstant(4, MVT::i32));
13212
13213     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13214                                 St->getPointerInfo(),
13215                                 St->isVolatile(), St->isNonTemporal(),
13216                                 St->getAlignment());
13217     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13218                                 St->getPointerInfo().getWithOffset(4),
13219                                 St->isVolatile(),
13220                                 St->isNonTemporal(),
13221                                 MinAlign(St->getAlignment(), 4));
13222     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13223   }
13224   return SDValue();
13225 }
13226
13227 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13228 /// X86ISD::FXOR nodes.
13229 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13230   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13231   // F[X]OR(0.0, x) -> x
13232   // F[X]OR(x, 0.0) -> x
13233   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13234     if (C->getValueAPF().isPosZero())
13235       return N->getOperand(1);
13236   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13237     if (C->getValueAPF().isPosZero())
13238       return N->getOperand(0);
13239   return SDValue();
13240 }
13241
13242 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13243 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13244   // FAND(0.0, x) -> 0.0
13245   // FAND(x, 0.0) -> 0.0
13246   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13247     if (C->getValueAPF().isPosZero())
13248       return N->getOperand(0);
13249   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13250     if (C->getValueAPF().isPosZero())
13251       return N->getOperand(1);
13252   return SDValue();
13253 }
13254
13255 static SDValue PerformBTCombine(SDNode *N,
13256                                 SelectionDAG &DAG,
13257                                 TargetLowering::DAGCombinerInfo &DCI) {
13258   // BT ignores high bits in the bit index operand.
13259   SDValue Op1 = N->getOperand(1);
13260   if (Op1.hasOneUse()) {
13261     unsigned BitWidth = Op1.getValueSizeInBits();
13262     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13263     APInt KnownZero, KnownOne;
13264     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13265                                           !DCI.isBeforeLegalizeOps());
13266     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13267     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13268         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13269       DCI.CommitTargetLoweringOpt(TLO);
13270   }
13271   return SDValue();
13272 }
13273
13274 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13275   SDValue Op = N->getOperand(0);
13276   if (Op.getOpcode() == ISD::BITCAST)
13277     Op = Op.getOperand(0);
13278   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13279   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13280       VT.getVectorElementType().getSizeInBits() ==
13281       OpVT.getVectorElementType().getSizeInBits()) {
13282     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13283   }
13284   return SDValue();
13285 }
13286
13287 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13288   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13289   //           (and (i32 x86isd::setcc_carry), 1)
13290   // This eliminates the zext. This transformation is necessary because
13291   // ISD::SETCC is always legalized to i8.
13292   DebugLoc dl = N->getDebugLoc();
13293   SDValue N0 = N->getOperand(0);
13294   EVT VT = N->getValueType(0);
13295   if (N0.getOpcode() == ISD::AND &&
13296       N0.hasOneUse() &&
13297       N0.getOperand(0).hasOneUse()) {
13298     SDValue N00 = N0.getOperand(0);
13299     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
13300       return SDValue();
13301     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
13302     if (!C || C->getZExtValue() != 1)
13303       return SDValue();
13304     return DAG.getNode(ISD::AND, dl, VT,
13305                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
13306                                    N00.getOperand(0), N00.getOperand(1)),
13307                        DAG.getConstant(1, VT));
13308   }
13309
13310   return SDValue();
13311 }
13312
13313 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
13314 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
13315   unsigned X86CC = N->getConstantOperandVal(0);
13316   SDValue EFLAG = N->getOperand(1);
13317   DebugLoc DL = N->getDebugLoc();
13318
13319   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
13320   // a zext and produces an all-ones bit which is more useful than 0/1 in some
13321   // cases.
13322   if (X86CC == X86::COND_B)
13323     return DAG.getNode(ISD::AND, DL, MVT::i8,
13324                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
13325                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
13326                        DAG.getConstant(1, MVT::i8));
13327
13328   return SDValue();
13329 }
13330
13331 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
13332                                         const X86TargetLowering *XTLI) {
13333   SDValue Op0 = N->getOperand(0);
13334   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
13335   // a 32-bit target where SSE doesn't support i64->FP operations.
13336   if (Op0.getOpcode() == ISD::LOAD) {
13337     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
13338     EVT VT = Ld->getValueType(0);
13339     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
13340         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
13341         !XTLI->getSubtarget()->is64Bit() &&
13342         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13343       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
13344                                           Ld->getChain(), Op0, DAG);
13345       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
13346       return FILDChain;
13347     }
13348   }
13349   return SDValue();
13350 }
13351
13352 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
13353 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
13354                                  X86TargetLowering::DAGCombinerInfo &DCI) {
13355   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
13356   // the result is either zero or one (depending on the input carry bit).
13357   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
13358   if (X86::isZeroNode(N->getOperand(0)) &&
13359       X86::isZeroNode(N->getOperand(1)) &&
13360       // We don't have a good way to replace an EFLAGS use, so only do this when
13361       // dead right now.
13362       SDValue(N, 1).use_empty()) {
13363     DebugLoc DL = N->getDebugLoc();
13364     EVT VT = N->getValueType(0);
13365     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
13366     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
13367                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
13368                                            DAG.getConstant(X86::COND_B,MVT::i8),
13369                                            N->getOperand(2)),
13370                                DAG.getConstant(1, VT));
13371     return DCI.CombineTo(N, Res1, CarryOut);
13372   }
13373
13374   return SDValue();
13375 }
13376
13377 // fold (add Y, (sete  X, 0)) -> adc  0, Y
13378 //      (add Y, (setne X, 0)) -> sbb -1, Y
13379 //      (sub (sete  X, 0), Y) -> sbb  0, Y
13380 //      (sub (setne X, 0), Y) -> adc -1, Y
13381 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
13382   DebugLoc DL = N->getDebugLoc();
13383
13384   // Look through ZExts.
13385   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
13386   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
13387     return SDValue();
13388
13389   SDValue SetCC = Ext.getOperand(0);
13390   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
13391     return SDValue();
13392
13393   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
13394   if (CC != X86::COND_E && CC != X86::COND_NE)
13395     return SDValue();
13396
13397   SDValue Cmp = SetCC.getOperand(1);
13398   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
13399       !X86::isZeroNode(Cmp.getOperand(1)) ||
13400       !Cmp.getOperand(0).getValueType().isInteger())
13401     return SDValue();
13402
13403   SDValue CmpOp0 = Cmp.getOperand(0);
13404   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
13405                                DAG.getConstant(1, CmpOp0.getValueType()));
13406
13407   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
13408   if (CC == X86::COND_NE)
13409     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
13410                        DL, OtherVal.getValueType(), OtherVal,
13411                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
13412   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
13413                      DL, OtherVal.getValueType(), OtherVal,
13414                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
13415 }
13416
13417 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
13418   SDValue Op0 = N->getOperand(0);
13419   SDValue Op1 = N->getOperand(1);
13420
13421   // X86 can't encode an immediate LHS of a sub. See if we can push the
13422   // negation into a preceding instruction.
13423   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
13424     // If the RHS of the sub is a XOR with one use and a constant, invert the
13425     // immediate. Then add one to the LHS of the sub so we can turn
13426     // X-Y -> X+~Y+1, saving one register.
13427     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
13428         isa<ConstantSDNode>(Op1.getOperand(1))) {
13429       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
13430       EVT VT = Op0.getValueType();
13431       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
13432                                    Op1.getOperand(0),
13433                                    DAG.getConstant(~XorC, VT));
13434       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
13435                          DAG.getConstant(C->getAPIntValue()+1, VT));
13436     }
13437   }
13438
13439   return OptimizeConditionalInDecrement(N, DAG);
13440 }
13441
13442 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
13443                                              DAGCombinerInfo &DCI) const {
13444   SelectionDAG &DAG = DCI.DAG;
13445   switch (N->getOpcode()) {
13446   default: break;
13447   case ISD::EXTRACT_VECTOR_ELT:
13448     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
13449   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
13450   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
13451   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
13452   case ISD::SUB:            return PerformSubCombine(N, DAG);
13453   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
13454   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
13455   case ISD::SHL:
13456   case ISD::SRA:
13457   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
13458   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
13459   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
13460   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
13461   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
13462   case X86ISD::FXOR:
13463   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
13464   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
13465   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
13466   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
13467   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
13468   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
13469   case X86ISD::SHUFPS:      // Handle all target specific shuffles
13470   case X86ISD::SHUFPD:
13471   case X86ISD::PALIGN:
13472   case X86ISD::PUNPCKHBW:
13473   case X86ISD::PUNPCKHWD:
13474   case X86ISD::PUNPCKHDQ:
13475   case X86ISD::PUNPCKHQDQ:
13476   case X86ISD::UNPCKHPS:
13477   case X86ISD::UNPCKHPD:
13478   case X86ISD::VUNPCKHPSY:
13479   case X86ISD::VUNPCKHPDY:
13480   case X86ISD::PUNPCKLBW:
13481   case X86ISD::PUNPCKLWD:
13482   case X86ISD::PUNPCKLDQ:
13483   case X86ISD::PUNPCKLQDQ:
13484   case X86ISD::UNPCKLPS:
13485   case X86ISD::UNPCKLPD:
13486   case X86ISD::VUNPCKLPSY:
13487   case X86ISD::VUNPCKLPDY:
13488   case X86ISD::MOVHLPS:
13489   case X86ISD::MOVLHPS:
13490   case X86ISD::PSHUFD:
13491   case X86ISD::PSHUFHW:
13492   case X86ISD::PSHUFLW:
13493   case X86ISD::MOVSS:
13494   case X86ISD::MOVSD:
13495   case X86ISD::VPERMILPS:
13496   case X86ISD::VPERMILPSY:
13497   case X86ISD::VPERMILPD:
13498   case X86ISD::VPERMILPDY:
13499   case X86ISD::VPERM2F128:
13500   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
13501   }
13502
13503   return SDValue();
13504 }
13505
13506 /// isTypeDesirableForOp - Return true if the target has native support for
13507 /// the specified value type and it is 'desirable' to use the type for the
13508 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
13509 /// instruction encodings are longer and some i16 instructions are slow.
13510 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
13511   if (!isTypeLegal(VT))
13512     return false;
13513   if (VT != MVT::i16)
13514     return true;
13515
13516   switch (Opc) {
13517   default:
13518     return true;
13519   case ISD::LOAD:
13520   case ISD::SIGN_EXTEND:
13521   case ISD::ZERO_EXTEND:
13522   case ISD::ANY_EXTEND:
13523   case ISD::SHL:
13524   case ISD::SRL:
13525   case ISD::SUB:
13526   case ISD::ADD:
13527   case ISD::MUL:
13528   case ISD::AND:
13529   case ISD::OR:
13530   case ISD::XOR:
13531     return false;
13532   }
13533 }
13534
13535 /// IsDesirableToPromoteOp - This method query the target whether it is
13536 /// beneficial for dag combiner to promote the specified node. If true, it
13537 /// should return the desired promotion type by reference.
13538 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
13539   EVT VT = Op.getValueType();
13540   if (VT != MVT::i16)
13541     return false;
13542
13543   bool Promote = false;
13544   bool Commute = false;
13545   switch (Op.getOpcode()) {
13546   default: break;
13547   case ISD::LOAD: {
13548     LoadSDNode *LD = cast<LoadSDNode>(Op);
13549     // If the non-extending load has a single use and it's not live out, then it
13550     // might be folded.
13551     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
13552                                                      Op.hasOneUse()*/) {
13553       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13554              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
13555         // The only case where we'd want to promote LOAD (rather then it being
13556         // promoted as an operand is when it's only use is liveout.
13557         if (UI->getOpcode() != ISD::CopyToReg)
13558           return false;
13559       }
13560     }
13561     Promote = true;
13562     break;
13563   }
13564   case ISD::SIGN_EXTEND:
13565   case ISD::ZERO_EXTEND:
13566   case ISD::ANY_EXTEND:
13567     Promote = true;
13568     break;
13569   case ISD::SHL:
13570   case ISD::SRL: {
13571     SDValue N0 = Op.getOperand(0);
13572     // Look out for (store (shl (load), x)).
13573     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
13574       return false;
13575     Promote = true;
13576     break;
13577   }
13578   case ISD::ADD:
13579   case ISD::MUL:
13580   case ISD::AND:
13581   case ISD::OR:
13582   case ISD::XOR:
13583     Commute = true;
13584     // fallthrough
13585   case ISD::SUB: {
13586     SDValue N0 = Op.getOperand(0);
13587     SDValue N1 = Op.getOperand(1);
13588     if (!Commute && MayFoldLoad(N1))
13589       return false;
13590     // Avoid disabling potential load folding opportunities.
13591     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
13592       return false;
13593     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
13594       return false;
13595     Promote = true;
13596   }
13597   }
13598
13599   PVT = MVT::i32;
13600   return Promote;
13601 }
13602
13603 //===----------------------------------------------------------------------===//
13604 //                           X86 Inline Assembly Support
13605 //===----------------------------------------------------------------------===//
13606
13607 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
13608   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13609
13610   std::string AsmStr = IA->getAsmString();
13611
13612   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
13613   SmallVector<StringRef, 4> AsmPieces;
13614   SplitString(AsmStr, AsmPieces, ";\n");
13615
13616   switch (AsmPieces.size()) {
13617   default: return false;
13618   case 1:
13619     AsmStr = AsmPieces[0];
13620     AsmPieces.clear();
13621     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
13622
13623     // FIXME: this should verify that we are targeting a 486 or better.  If not,
13624     // we will turn this bswap into something that will be lowered to logical ops
13625     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
13626     // so don't worry about this.
13627     // bswap $0
13628     if (AsmPieces.size() == 2 &&
13629         (AsmPieces[0] == "bswap" ||
13630          AsmPieces[0] == "bswapq" ||
13631          AsmPieces[0] == "bswapl") &&
13632         (AsmPieces[1] == "$0" ||
13633          AsmPieces[1] == "${0:q}")) {
13634       // No need to check constraints, nothing other than the equivalent of
13635       // "=r,0" would be valid here.
13636       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13637       if (!Ty || Ty->getBitWidth() % 16 != 0)
13638         return false;
13639       return IntrinsicLowering::LowerToByteSwap(CI);
13640     }
13641     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
13642     if (CI->getType()->isIntegerTy(16) &&
13643         AsmPieces.size() == 3 &&
13644         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
13645         AsmPieces[1] == "$$8," &&
13646         AsmPieces[2] == "${0:w}" &&
13647         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13648       AsmPieces.clear();
13649       const std::string &ConstraintsStr = IA->getConstraintString();
13650       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13651       std::sort(AsmPieces.begin(), AsmPieces.end());
13652       if (AsmPieces.size() == 4 &&
13653           AsmPieces[0] == "~{cc}" &&
13654           AsmPieces[1] == "~{dirflag}" &&
13655           AsmPieces[2] == "~{flags}" &&
13656           AsmPieces[3] == "~{fpsr}") {
13657         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13658         if (!Ty || Ty->getBitWidth() % 16 != 0)
13659           return false;
13660         return IntrinsicLowering::LowerToByteSwap(CI);
13661       }
13662     }
13663     break;
13664   case 3:
13665     if (CI->getType()->isIntegerTy(32) &&
13666         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
13667       SmallVector<StringRef, 4> Words;
13668       SplitString(AsmPieces[0], Words, " \t,");
13669       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13670           Words[2] == "${0:w}") {
13671         Words.clear();
13672         SplitString(AsmPieces[1], Words, " \t,");
13673         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
13674             Words[2] == "$0") {
13675           Words.clear();
13676           SplitString(AsmPieces[2], Words, " \t,");
13677           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
13678               Words[2] == "${0:w}") {
13679             AsmPieces.clear();
13680             const std::string &ConstraintsStr = IA->getConstraintString();
13681             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
13682             std::sort(AsmPieces.begin(), AsmPieces.end());
13683             if (AsmPieces.size() == 4 &&
13684                 AsmPieces[0] == "~{cc}" &&
13685                 AsmPieces[1] == "~{dirflag}" &&
13686                 AsmPieces[2] == "~{flags}" &&
13687                 AsmPieces[3] == "~{fpsr}") {
13688               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13689               if (!Ty || Ty->getBitWidth() % 16 != 0)
13690                 return false;
13691               return IntrinsicLowering::LowerToByteSwap(CI);
13692             }
13693           }
13694         }
13695       }
13696     }
13697
13698     if (CI->getType()->isIntegerTy(64)) {
13699       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
13700       if (Constraints.size() >= 2 &&
13701           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
13702           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
13703         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
13704         SmallVector<StringRef, 4> Words;
13705         SplitString(AsmPieces[0], Words, " \t");
13706         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
13707           Words.clear();
13708           SplitString(AsmPieces[1], Words, " \t");
13709           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
13710             Words.clear();
13711             SplitString(AsmPieces[2], Words, " \t,");
13712             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
13713                 Words[2] == "%edx") {
13714               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13715               if (!Ty || Ty->getBitWidth() % 16 != 0)
13716                 return false;
13717               return IntrinsicLowering::LowerToByteSwap(CI);
13718             }
13719           }
13720         }
13721       }
13722     }
13723     break;
13724   }
13725   return false;
13726 }
13727
13728
13729
13730 /// getConstraintType - Given a constraint letter, return the type of
13731 /// constraint it is for this target.
13732 X86TargetLowering::ConstraintType
13733 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
13734   if (Constraint.size() == 1) {
13735     switch (Constraint[0]) {
13736     case 'R':
13737     case 'q':
13738     case 'Q':
13739     case 'f':
13740     case 't':
13741     case 'u':
13742     case 'y':
13743     case 'x':
13744     case 'Y':
13745     case 'l':
13746       return C_RegisterClass;
13747     case 'a':
13748     case 'b':
13749     case 'c':
13750     case 'd':
13751     case 'S':
13752     case 'D':
13753     case 'A':
13754       return C_Register;
13755     case 'I':
13756     case 'J':
13757     case 'K':
13758     case 'L':
13759     case 'M':
13760     case 'N':
13761     case 'G':
13762     case 'C':
13763     case 'e':
13764     case 'Z':
13765       return C_Other;
13766     default:
13767       break;
13768     }
13769   }
13770   return TargetLowering::getConstraintType(Constraint);
13771 }
13772
13773 /// Examine constraint type and operand type and determine a weight value.
13774 /// This object must already have been set up with the operand type
13775 /// and the current alternative constraint selected.
13776 TargetLowering::ConstraintWeight
13777   X86TargetLowering::getSingleConstraintMatchWeight(
13778     AsmOperandInfo &info, const char *constraint) const {
13779   ConstraintWeight weight = CW_Invalid;
13780   Value *CallOperandVal = info.CallOperandVal;
13781     // If we don't have a value, we can't do a match,
13782     // but allow it at the lowest weight.
13783   if (CallOperandVal == NULL)
13784     return CW_Default;
13785   Type *type = CallOperandVal->getType();
13786   // Look at the constraint type.
13787   switch (*constraint) {
13788   default:
13789     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13790   case 'R':
13791   case 'q':
13792   case 'Q':
13793   case 'a':
13794   case 'b':
13795   case 'c':
13796   case 'd':
13797   case 'S':
13798   case 'D':
13799   case 'A':
13800     if (CallOperandVal->getType()->isIntegerTy())
13801       weight = CW_SpecificReg;
13802     break;
13803   case 'f':
13804   case 't':
13805   case 'u':
13806       if (type->isFloatingPointTy())
13807         weight = CW_SpecificReg;
13808       break;
13809   case 'y':
13810       if (type->isX86_MMXTy() && Subtarget->hasMMX())
13811         weight = CW_SpecificReg;
13812       break;
13813   case 'x':
13814   case 'Y':
13815     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
13816       weight = CW_Register;
13817     break;
13818   case 'I':
13819     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
13820       if (C->getZExtValue() <= 31)
13821         weight = CW_Constant;
13822     }
13823     break;
13824   case 'J':
13825     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13826       if (C->getZExtValue() <= 63)
13827         weight = CW_Constant;
13828     }
13829     break;
13830   case 'K':
13831     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13832       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
13833         weight = CW_Constant;
13834     }
13835     break;
13836   case 'L':
13837     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13838       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
13839         weight = CW_Constant;
13840     }
13841     break;
13842   case 'M':
13843     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13844       if (C->getZExtValue() <= 3)
13845         weight = CW_Constant;
13846     }
13847     break;
13848   case 'N':
13849     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13850       if (C->getZExtValue() <= 0xff)
13851         weight = CW_Constant;
13852     }
13853     break;
13854   case 'G':
13855   case 'C':
13856     if (dyn_cast<ConstantFP>(CallOperandVal)) {
13857       weight = CW_Constant;
13858     }
13859     break;
13860   case 'e':
13861     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13862       if ((C->getSExtValue() >= -0x80000000LL) &&
13863           (C->getSExtValue() <= 0x7fffffffLL))
13864         weight = CW_Constant;
13865     }
13866     break;
13867   case 'Z':
13868     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
13869       if (C->getZExtValue() <= 0xffffffff)
13870         weight = CW_Constant;
13871     }
13872     break;
13873   }
13874   return weight;
13875 }
13876
13877 /// LowerXConstraint - try to replace an X constraint, which matches anything,
13878 /// with another that has more specific requirements based on the type of the
13879 /// corresponding operand.
13880 const char *X86TargetLowering::
13881 LowerXConstraint(EVT ConstraintVT) const {
13882   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
13883   // 'f' like normal targets.
13884   if (ConstraintVT.isFloatingPoint()) {
13885     if (Subtarget->hasXMMInt())
13886       return "Y";
13887     if (Subtarget->hasXMM())
13888       return "x";
13889   }
13890
13891   return TargetLowering::LowerXConstraint(ConstraintVT);
13892 }
13893
13894 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13895 /// vector.  If it is invalid, don't add anything to Ops.
13896 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13897                                                      std::string &Constraint,
13898                                                      std::vector<SDValue>&Ops,
13899                                                      SelectionDAG &DAG) const {
13900   SDValue Result(0, 0);
13901
13902   // Only support length 1 constraints for now.
13903   if (Constraint.length() > 1) return;
13904
13905   char ConstraintLetter = Constraint[0];
13906   switch (ConstraintLetter) {
13907   default: break;
13908   case 'I':
13909     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13910       if (C->getZExtValue() <= 31) {
13911         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13912         break;
13913       }
13914     }
13915     return;
13916   case 'J':
13917     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13918       if (C->getZExtValue() <= 63) {
13919         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13920         break;
13921       }
13922     }
13923     return;
13924   case 'K':
13925     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13926       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
13927         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13928         break;
13929       }
13930     }
13931     return;
13932   case 'N':
13933     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13934       if (C->getZExtValue() <= 255) {
13935         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13936         break;
13937       }
13938     }
13939     return;
13940   case 'e': {
13941     // 32-bit signed value
13942     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13943       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13944                                            C->getSExtValue())) {
13945         // Widen to 64 bits here to get it sign extended.
13946         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
13947         break;
13948       }
13949     // FIXME gcc accepts some relocatable values here too, but only in certain
13950     // memory models; it's complicated.
13951     }
13952     return;
13953   }
13954   case 'Z': {
13955     // 32-bit unsigned value
13956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
13957       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
13958                                            C->getZExtValue())) {
13959         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
13960         break;
13961       }
13962     }
13963     // FIXME gcc accepts some relocatable values here too, but only in certain
13964     // memory models; it's complicated.
13965     return;
13966   }
13967   case 'i': {
13968     // Literal immediates are always ok.
13969     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
13970       // Widen to 64 bits here to get it sign extended.
13971       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
13972       break;
13973     }
13974
13975     // In any sort of PIC mode addresses need to be computed at runtime by
13976     // adding in a register or some sort of table lookup.  These can't
13977     // be used as immediates.
13978     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
13979       return;
13980
13981     // If we are in non-pic codegen mode, we allow the address of a global (with
13982     // an optional displacement) to be used with 'i'.
13983     GlobalAddressSDNode *GA = 0;
13984     int64_t Offset = 0;
13985
13986     // Match either (GA), (GA+C), (GA+C1+C2), etc.
13987     while (1) {
13988       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
13989         Offset += GA->getOffset();
13990         break;
13991       } else if (Op.getOpcode() == ISD::ADD) {
13992         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13993           Offset += C->getZExtValue();
13994           Op = Op.getOperand(0);
13995           continue;
13996         }
13997       } else if (Op.getOpcode() == ISD::SUB) {
13998         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
13999           Offset += -C->getZExtValue();
14000           Op = Op.getOperand(0);
14001           continue;
14002         }
14003       }
14004
14005       // Otherwise, this isn't something we can handle, reject it.
14006       return;
14007     }
14008
14009     const GlobalValue *GV = GA->getGlobal();
14010     // If we require an extra load to get this address, as in PIC mode, we
14011     // can't accept it.
14012     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14013                                                         getTargetMachine())))
14014       return;
14015
14016     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14017                                         GA->getValueType(0), Offset);
14018     break;
14019   }
14020   }
14021
14022   if (Result.getNode()) {
14023     Ops.push_back(Result);
14024     return;
14025   }
14026   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14027 }
14028
14029 std::pair<unsigned, const TargetRegisterClass*>
14030 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14031                                                 EVT VT) const {
14032   // First, see if this is a constraint that directly corresponds to an LLVM
14033   // register class.
14034   if (Constraint.size() == 1) {
14035     // GCC Constraint Letters
14036     switch (Constraint[0]) {
14037     default: break;
14038       // TODO: Slight differences here in allocation order and leaving
14039       // RIP in the class. Do they matter any more here than they do
14040       // in the normal allocation?
14041     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14042       if (Subtarget->is64Bit()) {
14043         if (VT == MVT::i32 || VT == MVT::f32)
14044           return std::make_pair(0U, X86::GR32RegisterClass);
14045         else if (VT == MVT::i16)
14046           return std::make_pair(0U, X86::GR16RegisterClass);
14047         else if (VT == MVT::i8 || VT == MVT::i1)
14048           return std::make_pair(0U, X86::GR8RegisterClass);
14049         else if (VT == MVT::i64 || VT == MVT::f64)
14050           return std::make_pair(0U, X86::GR64RegisterClass);
14051         break;
14052       }
14053       // 32-bit fallthrough
14054     case 'Q':   // Q_REGS
14055       if (VT == MVT::i32 || VT == MVT::f32)
14056         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14057       else if (VT == MVT::i16)
14058         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14059       else if (VT == MVT::i8 || VT == MVT::i1)
14060         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14061       else if (VT == MVT::i64)
14062         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14063       break;
14064     case 'r':   // GENERAL_REGS
14065     case 'l':   // INDEX_REGS
14066       if (VT == MVT::i8 || VT == MVT::i1)
14067         return std::make_pair(0U, X86::GR8RegisterClass);
14068       if (VT == MVT::i16)
14069         return std::make_pair(0U, X86::GR16RegisterClass);
14070       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14071         return std::make_pair(0U, X86::GR32RegisterClass);
14072       return std::make_pair(0U, X86::GR64RegisterClass);
14073     case 'R':   // LEGACY_REGS
14074       if (VT == MVT::i8 || VT == MVT::i1)
14075         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14076       if (VT == MVT::i16)
14077         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14078       if (VT == MVT::i32 || !Subtarget->is64Bit())
14079         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14080       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14081     case 'f':  // FP Stack registers.
14082       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14083       // value to the correct fpstack register class.
14084       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14085         return std::make_pair(0U, X86::RFP32RegisterClass);
14086       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14087         return std::make_pair(0U, X86::RFP64RegisterClass);
14088       return std::make_pair(0U, X86::RFP80RegisterClass);
14089     case 'y':   // MMX_REGS if MMX allowed.
14090       if (!Subtarget->hasMMX()) break;
14091       return std::make_pair(0U, X86::VR64RegisterClass);
14092     case 'Y':   // SSE_REGS if SSE2 allowed
14093       if (!Subtarget->hasXMMInt()) break;
14094       // FALL THROUGH.
14095     case 'x':   // SSE_REGS if SSE1 allowed
14096       if (!Subtarget->hasXMM()) break;
14097
14098       switch (VT.getSimpleVT().SimpleTy) {
14099       default: break;
14100       // Scalar SSE types.
14101       case MVT::f32:
14102       case MVT::i32:
14103         return std::make_pair(0U, X86::FR32RegisterClass);
14104       case MVT::f64:
14105       case MVT::i64:
14106         return std::make_pair(0U, X86::FR64RegisterClass);
14107       // Vector types.
14108       case MVT::v16i8:
14109       case MVT::v8i16:
14110       case MVT::v4i32:
14111       case MVT::v2i64:
14112       case MVT::v4f32:
14113       case MVT::v2f64:
14114         return std::make_pair(0U, X86::VR128RegisterClass);
14115       }
14116       break;
14117     }
14118   }
14119
14120   // Use the default implementation in TargetLowering to convert the register
14121   // constraint into a member of a register class.
14122   std::pair<unsigned, const TargetRegisterClass*> Res;
14123   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14124
14125   // Not found as a standard register?
14126   if (Res.second == 0) {
14127     // Map st(0) -> st(7) -> ST0
14128     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14129         tolower(Constraint[1]) == 's' &&
14130         tolower(Constraint[2]) == 't' &&
14131         Constraint[3] == '(' &&
14132         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14133         Constraint[5] == ')' &&
14134         Constraint[6] == '}') {
14135
14136       Res.first = X86::ST0+Constraint[4]-'0';
14137       Res.second = X86::RFP80RegisterClass;
14138       return Res;
14139     }
14140
14141     // GCC allows "st(0)" to be called just plain "st".
14142     if (StringRef("{st}").equals_lower(Constraint)) {
14143       Res.first = X86::ST0;
14144       Res.second = X86::RFP80RegisterClass;
14145       return Res;
14146     }
14147
14148     // flags -> EFLAGS
14149     if (StringRef("{flags}").equals_lower(Constraint)) {
14150       Res.first = X86::EFLAGS;
14151       Res.second = X86::CCRRegisterClass;
14152       return Res;
14153     }
14154
14155     // 'A' means EAX + EDX.
14156     if (Constraint == "A") {
14157       Res.first = X86::EAX;
14158       Res.second = X86::GR32_ADRegisterClass;
14159       return Res;
14160     }
14161     return Res;
14162   }
14163
14164   // Otherwise, check to see if this is a register class of the wrong value
14165   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14166   // turn into {ax},{dx}.
14167   if (Res.second->hasType(VT))
14168     return Res;   // Correct type already, nothing to do.
14169
14170   // All of the single-register GCC register classes map their values onto
14171   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14172   // really want an 8-bit or 32-bit register, map to the appropriate register
14173   // class and return the appropriate register.
14174   if (Res.second == X86::GR16RegisterClass) {
14175     if (VT == MVT::i8) {
14176       unsigned DestReg = 0;
14177       switch (Res.first) {
14178       default: break;
14179       case X86::AX: DestReg = X86::AL; break;
14180       case X86::DX: DestReg = X86::DL; break;
14181       case X86::CX: DestReg = X86::CL; break;
14182       case X86::BX: DestReg = X86::BL; break;
14183       }
14184       if (DestReg) {
14185         Res.first = DestReg;
14186         Res.second = X86::GR8RegisterClass;
14187       }
14188     } else if (VT == MVT::i32) {
14189       unsigned DestReg = 0;
14190       switch (Res.first) {
14191       default: break;
14192       case X86::AX: DestReg = X86::EAX; break;
14193       case X86::DX: DestReg = X86::EDX; break;
14194       case X86::CX: DestReg = X86::ECX; break;
14195       case X86::BX: DestReg = X86::EBX; break;
14196       case X86::SI: DestReg = X86::ESI; break;
14197       case X86::DI: DestReg = X86::EDI; break;
14198       case X86::BP: DestReg = X86::EBP; break;
14199       case X86::SP: DestReg = X86::ESP; break;
14200       }
14201       if (DestReg) {
14202         Res.first = DestReg;
14203         Res.second = X86::GR32RegisterClass;
14204       }
14205     } else if (VT == MVT::i64) {
14206       unsigned DestReg = 0;
14207       switch (Res.first) {
14208       default: break;
14209       case X86::AX: DestReg = X86::RAX; break;
14210       case X86::DX: DestReg = X86::RDX; break;
14211       case X86::CX: DestReg = X86::RCX; break;
14212       case X86::BX: DestReg = X86::RBX; break;
14213       case X86::SI: DestReg = X86::RSI; break;
14214       case X86::DI: DestReg = X86::RDI; break;
14215       case X86::BP: DestReg = X86::RBP; break;
14216       case X86::SP: DestReg = X86::RSP; break;
14217       }
14218       if (DestReg) {
14219         Res.first = DestReg;
14220         Res.second = X86::GR64RegisterClass;
14221       }
14222     }
14223   } else if (Res.second == X86::FR32RegisterClass ||
14224              Res.second == X86::FR64RegisterClass ||
14225              Res.second == X86::VR128RegisterClass) {
14226     // Handle references to XMM physical registers that got mapped into the
14227     // wrong class.  This can happen with constraints like {xmm0} where the
14228     // target independent register mapper will just pick the first match it can
14229     // find, ignoring the required type.
14230     if (VT == MVT::f32)
14231       Res.second = X86::FR32RegisterClass;
14232     else if (VT == MVT::f64)
14233       Res.second = X86::FR64RegisterClass;
14234     else if (X86::VR128RegisterClass->hasType(VT))
14235       Res.second = X86::VR128RegisterClass;
14236   }
14237
14238   return Res;
14239 }