93f7de89de2f07942827987ceecb0d396785d047
[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 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt();
173   X86ScalarSSEf32 = Subtarget->hasXMM();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187   // For 64-bit since we have so many registers use the ILP scheduler, for
188   // 32-bit code use the register pressure specific scheduling.
189   if (Subtarget->is64Bit())
190     setSchedulingPreference(Sched::ILP);
191   else
192     setSchedulingPreference(Sched::RegPressure);
193   setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196     // Setup Windows compiler runtime calls.
197     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199     setLibcallName(RTLIB::SREM_I64, "_allrem");
200     setLibcallName(RTLIB::UREM_I64, "_aullrem");
201     setLibcallName(RTLIB::MUL_I64, "_allmul");
202     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211   }
212
213   if (Subtarget->isTargetDarwin()) {
214     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215     setUseUnderscoreSetJmp(false);
216     setUseUnderscoreLongJmp(false);
217   } else if (Subtarget->isTargetMingw()) {
218     // MS runtime is weird: it exports _setjmp, but longjmp!
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(false);
221   } else {
222     setUseUnderscoreSetJmp(true);
223     setUseUnderscoreLongJmp(true);
224   }
225
226   // Set up the register classes.
227   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230   if (Subtarget->is64Bit())
231     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235   // We don't accept any truncstore of integer registers.
236   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243   // SETOEQ and SETUNE require checking two conditions.
244   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252   // operation.
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257   if (Subtarget->is64Bit()) {
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260   } else if (!UseSoftFloat) {
261     // We have an algorithm for SSE2->double, and we turn this into a
262     // 64-bit FILD followed by conditional FADD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264     // We have an algorithm for SSE2, and we turn this into a 64-bit
265     // FILD for other targets.
266     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267   }
268
269   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270   // this operation.
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274   if (!UseSoftFloat) {
275     // SSE has no i16 to fp conversion, only i32
276     if (X86ScalarSSEf32) {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278       // f32 and f64 cases are Legal, f80 case is not
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     } else {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283     }
284   } else {
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287   }
288
289   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290   // are Legal, f80 is custom lowered.
291   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295   // this operation.
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299   if (X86ScalarSSEf32) {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301     // f32 and f64 cases are Legal, f80 case is not
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   } else {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306   }
307
308   // Handle FP_TO_UINT by promoting the destination to a larger signed
309   // conversion.
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314   if (Subtarget->is64Bit()) {
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317   } else if (!UseSoftFloat) {
318     // Since AVX is a superset of SSE3, only check for SSE here.
319     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320       // Expand FP_TO_UINT into a select.
321       // FIXME: We would like to use a Custom expander here eventually to do
322       // the optimal thing for SSE vs. the default expansion in the legalizer.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324     else
325       // With SSE3 we can use fisttpll to convert to a signed i64; without
326       // SSE, we're stuck with a fistpll.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328   }
329
330   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331   if (!X86ScalarSSEf64) {
332     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334     if (Subtarget->is64Bit()) {
335       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336       // Without SSE, i64->f64 goes through memory.
337       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338     }
339   }
340
341   // Scalar integer divide and remainder are lowered to use operations that
342   // produce two results, to match the available instructions. This exposes
343   // the two-result form to trivial CSE, which is able to combine x/y and x%y
344   // into a single instruction.
345   //
346   // Scalar integer multiply-high is also lowered to use two-result
347   // operations, to match the available instructions. However, plain multiply
348   // (low) operations are left as Legal, as there are single-result
349   // instructions for this in x86. Using the two-result multiply instructions
350   // when both high and low results are needed must be arranged by dagcombine.
351   for (unsigned i = 0, e = 4; i != e; ++i) {
352     MVT VT = IntVTs[i];
353     setOperationAction(ISD::MULHS, VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::SDIV, VT, Expand);
356     setOperationAction(ISD::UDIV, VT, Expand);
357     setOperationAction(ISD::SREM, VT, Expand);
358     setOperationAction(ISD::UREM, VT, Expand);
359
360     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361     setOperationAction(ISD::ADDC, VT, Custom);
362     setOperationAction(ISD::ADDE, VT, Custom);
363     setOperationAction(ISD::SUBC, VT, Custom);
364     setOperationAction(ISD::SUBE, VT, Custom);
365   }
366
367   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371   if (Subtarget->is64Bit())
372     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382   if (Subtarget->hasBMI()) {
383     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
384   } else {
385     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
387     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
388     if (Subtarget->is64Bit())
389       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
390   }
391
392   if (Subtarget->hasLZCNT()) {
393     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
394   } else {
395     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasPOPCNT()) {
403     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
404   } else {
405     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
407     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
410   }
411
412   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
413   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
414
415   // These should be promoted to a larger select which is supported.
416   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
417   // X86 wants to expand cmov itself.
418   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
423   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
430   if (Subtarget->is64Bit()) {
431     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
432     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
433   }
434   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
435
436   // Darwin ABI issue.
437   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
438   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
440   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
441   if (Subtarget->is64Bit())
442     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
444   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
447     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
448     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
449     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
450     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
451   }
452   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
453   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
455   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
459     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
460   }
461
462   if (Subtarget->hasXMM())
463     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
464
465   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
466   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
467
468   // On X86 and X86-64, atomic operations are lowered to locked instructions.
469   // Locked instructions, in turn, have implicit fence semantics (all memory
470   // operations are flushed before issuing the locked instruction, and they
471   // are not buffered), so we can fold away the common pattern of
472   // fence-atomic-fence.
473   setShouldFoldAtomicFences(true);
474
475   // Expand certain atomics
476   for (unsigned i = 0, e = 4; i != e; ++i) {
477     MVT VT = IntVTs[i];
478     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
479     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
480     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
481   }
482
483   if (!Subtarget->is64Bit()) {
484     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
491     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
492   }
493
494   if (Subtarget->hasCmpxchg16b()) {
495     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
496   }
497
498   // FIXME - use subtarget debug flags
499   if (!Subtarget->isTargetDarwin() &&
500       !Subtarget->isTargetELF() &&
501       !Subtarget->isTargetCygMing()) {
502     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
506   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
507   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
508   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
509   if (Subtarget->is64Bit()) {
510     setExceptionPointerRegister(X86::RAX);
511     setExceptionSelectorRegister(X86::RDX);
512   } else {
513     setExceptionPointerRegister(X86::EAX);
514     setExceptionSelectorRegister(X86::EDX);
515   }
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518
519   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521
522   setOperationAction(ISD::TRAP, MVT::Other, Legal);
523
524   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
525   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
526   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
529     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
530   } else {
531     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
532     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
533   }
534
535   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
536   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
537
538   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
539     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
540                        MVT::i64 : MVT::i32, Custom);
541   else if (EnableSegmentedStacks)
542     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
543                        MVT::i64 : MVT::i32, Custom);
544   else
545     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
546                        MVT::i64 : MVT::i32, Expand);
547
548   if (!UseSoftFloat && X86ScalarSSEf64) {
549     // f32 and f64 use SSE.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
552     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553
554     // Use ANDPD to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f64, Custom);
556     setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558     // Use XORP to simulate FNEG.
559     setOperationAction(ISD::FNEG , MVT::f64, Custom);
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     // Use ANDPD and ORPD to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // Lower this to FGETSIGNx86 plus an AND.
567     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
568     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569
570     // We don't support sin/cos/fmod
571     setOperationAction(ISD::FSIN , MVT::f64, Expand);
572     setOperationAction(ISD::FCOS , MVT::f64, Expand);
573     setOperationAction(ISD::FSIN , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS , MVT::f32, Expand);
575
576     // Expand FP immediates into loads from the stack, except for the special
577     // cases we handle.
578     addLegalFPImmediate(APFloat(+0.0)); // xorpd
579     addLegalFPImmediate(APFloat(+0.0f)); // xorps
580   } else if (!UseSoftFloat && X86ScalarSSEf32) {
581     // Use SSE for f32, x87 for f64.
582     // Set up the FP register classes.
583     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
584     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585
586     // Use ANDPS to simulate FABS.
587     setOperationAction(ISD::FABS , MVT::f32, Custom);
588
589     // Use XORP to simulate FNEG.
590     setOperationAction(ISD::FNEG , MVT::f32, Custom);
591
592     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593
594     // Use ANDPS and ORPS to simulate FCOPYSIGN.
595     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597
598     // We don't support sin/cos/fmod
599     setOperationAction(ISD::FSIN , MVT::f32, Expand);
600     setOperationAction(ISD::FCOS , MVT::f32, Expand);
601
602     // Special cases we handle for FP constants.
603     addLegalFPImmediate(APFloat(+0.0f)); // xorps
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608
609     if (!UnsafeFPMath) {
610       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
611       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
612     }
613   } else if (!UseSoftFloat) {
614     // f32 and f64 in x87.
615     // Set up the FP register classes.
616     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
617     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618
619     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
620     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
623
624     if (!UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628     addLegalFPImmediate(APFloat(+0.0)); // FLD0
629     addLegalFPImmediate(APFloat(+1.0)); // FLD1
630     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
631     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
632     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
633     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
634     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
635     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
636   }
637
638   // We don't support FMA.
639   setOperationAction(ISD::FMA, MVT::f64, Expand);
640   setOperationAction(ISD::FMA, MVT::f32, Expand);
641
642   // Long double always uses X87.
643   if (!UseSoftFloat) {
644     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
645     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647     {
648       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
649       addLegalFPImmediate(TmpFlt);  // FLD0
650       TmpFlt.changeSign();
651       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
652
653       bool ignored;
654       APFloat TmpFlt2(+1.0);
655       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656                       &ignored);
657       addLegalFPImmediate(TmpFlt2);  // FLD1
658       TmpFlt2.changeSign();
659       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
660     }
661
662     if (!UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
665     }
666
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680
681   // First set operation action for all vector types to either promote
682   // (for widening) or expand (for scalarization). Then we will selectively
683   // turn on ones that can be effectively codegen'd.
684   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
685        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
686     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
736     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
932     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
933     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
934     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
935     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
936
937     // i8 and i16 vectors are custom , because the source register and source
938     // source memory operand types are not the same width.  f32 vectors are
939     // custom since the immediate controlling the insert encodes additional
940     // information.
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
944     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
945
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
950
951     if (Subtarget->is64Bit()) {
952       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
953       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
954     }
955   }
956
957   if (Subtarget->hasXMMInt()) {
958     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
959     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
960     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
961     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
962
963     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
964     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
966
967     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
968     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
969     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
970   }
971
972   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
973     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
974
975   if (!UseSoftFloat && Subtarget->hasAVX()) {
976     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
977     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
978     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
979     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
980     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
981     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
982
983     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
984     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
985     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
986
987     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
988     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
989     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
990     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
991     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
992     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
993
994     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
995     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
996     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
997     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
998     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
999     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1000
1001     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1002     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1003     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1004
1005     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1006     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1007     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1008     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1009     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1010     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1011
1012     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1013     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1014     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1015     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1016
1017     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1019     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1020     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1021
1022     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1023     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1024
1025     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1026     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1027     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1028     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1029
1030     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1031     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1032     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1033
1034     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1035     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1036     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1037     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1038
1039     if (Subtarget->hasAVX2()) {
1040       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1041       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1042       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1043       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1044
1045       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1046       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1047       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1048       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1049
1050       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1051       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1052       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1053
1054       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1055
1056       setOperationAction(ISD::SHL,         MVT::v4i32, Legal);
1057       setOperationAction(ISD::SHL,         MVT::v2i64, Legal);
1058       setOperationAction(ISD::SRL,         MVT::v4i32, Legal);
1059       setOperationAction(ISD::SRL,         MVT::v2i64, Legal);
1060       setOperationAction(ISD::SRA,         MVT::v4i32, Legal);
1061
1062       setOperationAction(ISD::SHL,         MVT::v8i32, Legal);
1063       setOperationAction(ISD::SHL,         MVT::v4i64, Legal);
1064       setOperationAction(ISD::SRL,         MVT::v8i32, Legal);
1065       setOperationAction(ISD::SRL,         MVT::v4i64, Legal);
1066       setOperationAction(ISD::SRA,         MVT::v8i32, Legal);
1067       // Don't lower v32i8 because there is no 128-bit byte mul
1068     } else {
1069       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1070       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1071       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1072       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1073
1074       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1075       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1076       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1077       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1078
1079       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1080       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1081       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1082       // Don't lower v32i8 because there is no 128-bit byte mul
1083     }
1084
1085     // Custom lower several nodes for 256-bit types.
1086     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1087                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1088       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1089       EVT VT = SVT;
1090
1091       // Extract subvector is special because the value type
1092       // (result) is 128-bit but the source is 256-bit wide.
1093       if (VT.is128BitVector())
1094         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1095
1096       // Do not attempt to custom lower other non-256-bit vectors
1097       if (!VT.is256BitVector())
1098         continue;
1099
1100       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1101       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1102       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1103       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1104       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1105       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1106     }
1107
1108     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1109     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1110       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1111       EVT VT = SVT;
1112
1113       // Do not attempt to promote non-256-bit vectors
1114       if (!VT.is256BitVector())
1115         continue;
1116
1117       setOperationAction(ISD::AND,    SVT, Promote);
1118       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1119       setOperationAction(ISD::OR,     SVT, Promote);
1120       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1121       setOperationAction(ISD::XOR,    SVT, Promote);
1122       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1123       setOperationAction(ISD::LOAD,   SVT, Promote);
1124       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1125       setOperationAction(ISD::SELECT, SVT, Promote);
1126       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1127     }
1128   }
1129
1130   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1131   // of this type with custom code.
1132   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1133          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1134     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1135   }
1136
1137   // We want to custom lower some of our intrinsics.
1138   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1139
1140
1141   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1142   // handle type legalization for these operations here.
1143   //
1144   // FIXME: We really should do custom legalization for addition and
1145   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1146   // than generic legalization for 64-bit multiplication-with-overflow, though.
1147   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1148     // Add/Sub/Mul with overflow operations are custom lowered.
1149     MVT VT = IntVTs[i];
1150     setOperationAction(ISD::SADDO, VT, Custom);
1151     setOperationAction(ISD::UADDO, VT, Custom);
1152     setOperationAction(ISD::SSUBO, VT, Custom);
1153     setOperationAction(ISD::USUBO, VT, Custom);
1154     setOperationAction(ISD::SMULO, VT, Custom);
1155     setOperationAction(ISD::UMULO, VT, Custom);
1156   }
1157
1158   // There are no 8-bit 3-address imul/mul instructions
1159   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1160   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1161
1162   if (!Subtarget->is64Bit()) {
1163     // These libcalls are not available in 32-bit.
1164     setLibcallName(RTLIB::SHL_I128, 0);
1165     setLibcallName(RTLIB::SRL_I128, 0);
1166     setLibcallName(RTLIB::SRA_I128, 0);
1167   }
1168
1169   // We have target-specific dag combine patterns for the following nodes:
1170   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1171   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1172   setTargetDAGCombine(ISD::BUILD_VECTOR);
1173   setTargetDAGCombine(ISD::VSELECT);
1174   setTargetDAGCombine(ISD::SELECT);
1175   setTargetDAGCombine(ISD::SHL);
1176   setTargetDAGCombine(ISD::SRA);
1177   setTargetDAGCombine(ISD::SRL);
1178   setTargetDAGCombine(ISD::OR);
1179   setTargetDAGCombine(ISD::AND);
1180   setTargetDAGCombine(ISD::ADD);
1181   setTargetDAGCombine(ISD::FADD);
1182   setTargetDAGCombine(ISD::FSUB);
1183   setTargetDAGCombine(ISD::SUB);
1184   setTargetDAGCombine(ISD::LOAD);
1185   setTargetDAGCombine(ISD::STORE);
1186   setTargetDAGCombine(ISD::ZERO_EXTEND);
1187   setTargetDAGCombine(ISD::SINT_TO_FP);
1188   if (Subtarget->is64Bit())
1189     setTargetDAGCombine(ISD::MUL);
1190   if (Subtarget->hasBMI())
1191     setTargetDAGCombine(ISD::XOR);
1192
1193   computeRegisterProperties();
1194
1195   // On Darwin, -Os means optimize for size without hurting performance,
1196   // do not reduce the limit.
1197   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1198   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1199   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1200   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1201   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1202   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1203   setPrefLoopAlignment(16);
1204   benefitFromCodePlacementOpt = true;
1205
1206   setPrefFunctionAlignment(4);
1207 }
1208
1209
1210 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1211   if (!VT.isVector()) return MVT::i8;
1212   return VT.changeVectorElementTypeToInteger();
1213 }
1214
1215
1216 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1217 /// the desired ByVal argument alignment.
1218 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1219   if (MaxAlign == 16)
1220     return;
1221   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1222     if (VTy->getBitWidth() == 128)
1223       MaxAlign = 16;
1224   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1225     unsigned EltAlign = 0;
1226     getMaxByValAlign(ATy->getElementType(), EltAlign);
1227     if (EltAlign > MaxAlign)
1228       MaxAlign = EltAlign;
1229   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1230     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1231       unsigned EltAlign = 0;
1232       getMaxByValAlign(STy->getElementType(i), EltAlign);
1233       if (EltAlign > MaxAlign)
1234         MaxAlign = EltAlign;
1235       if (MaxAlign == 16)
1236         break;
1237     }
1238   }
1239   return;
1240 }
1241
1242 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1243 /// function arguments in the caller parameter area. For X86, aggregates
1244 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1245 /// are at 4-byte boundaries.
1246 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1247   if (Subtarget->is64Bit()) {
1248     // Max of 8 and alignment of type.
1249     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1250     if (TyAlign > 8)
1251       return TyAlign;
1252     return 8;
1253   }
1254
1255   unsigned Align = 4;
1256   if (Subtarget->hasXMM())
1257     getMaxByValAlign(Ty, Align);
1258   return Align;
1259 }
1260
1261 /// getOptimalMemOpType - Returns the target specific optimal type for load
1262 /// and store operations as a result of memset, memcpy, and memmove
1263 /// lowering. If DstAlign is zero that means it's safe to destination
1264 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1265 /// means there isn't a need to check it against alignment requirement,
1266 /// probably because the source does not need to be loaded. If
1267 /// 'IsZeroVal' is true, that means it's safe to return a
1268 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1269 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1270 /// constant so it does not need to be loaded.
1271 /// It returns EVT::Other if the type should be determined using generic
1272 /// target-independent logic.
1273 EVT
1274 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1275                                        unsigned DstAlign, unsigned SrcAlign,
1276                                        bool IsZeroVal,
1277                                        bool MemcpyStrSrc,
1278                                        MachineFunction &MF) const {
1279   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1280   // linux.  This is because the stack realignment code can't handle certain
1281   // cases like PR2962.  This should be removed when PR2962 is fixed.
1282   const Function *F = MF.getFunction();
1283   if (IsZeroVal &&
1284       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1285     if (Size >= 16 &&
1286         (Subtarget->isUnalignedMemAccessFast() ||
1287          ((DstAlign == 0 || DstAlign >= 16) &&
1288           (SrcAlign == 0 || SrcAlign >= 16))) &&
1289         Subtarget->getStackAlignment() >= 16) {
1290       if (Subtarget->hasAVX() &&
1291           Subtarget->getStackAlignment() >= 32)
1292         return MVT::v8f32;
1293       if (Subtarget->hasXMMInt())
1294         return MVT::v4i32;
1295       if (Subtarget->hasXMM())
1296         return MVT::v4f32;
1297     } else if (!MemcpyStrSrc && Size >= 8 &&
1298                !Subtarget->is64Bit() &&
1299                Subtarget->getStackAlignment() >= 8 &&
1300                Subtarget->hasXMMInt()) {
1301       // Do not use f64 to lower memcpy if source is string constant. It's
1302       // better to use i32 to avoid the loads.
1303       return MVT::f64;
1304     }
1305   }
1306   if (Subtarget->is64Bit() && Size >= 8)
1307     return MVT::i64;
1308   return MVT::i32;
1309 }
1310
1311 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1312 /// current function.  The returned value is a member of the
1313 /// MachineJumpTableInfo::JTEntryKind enum.
1314 unsigned X86TargetLowering::getJumpTableEncoding() const {
1315   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1316   // symbol.
1317   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1318       Subtarget->isPICStyleGOT())
1319     return MachineJumpTableInfo::EK_Custom32;
1320
1321   // Otherwise, use the normal jump table encoding heuristics.
1322   return TargetLowering::getJumpTableEncoding();
1323 }
1324
1325 const MCExpr *
1326 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1327                                              const MachineBasicBlock *MBB,
1328                                              unsigned uid,MCContext &Ctx) const{
1329   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1330          Subtarget->isPICStyleGOT());
1331   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1332   // entries.
1333   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1334                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1335 }
1336
1337 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1338 /// jumptable.
1339 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1340                                                     SelectionDAG &DAG) const {
1341   if (!Subtarget->is64Bit())
1342     // This doesn't have DebugLoc associated with it, but is not really the
1343     // same as a Register.
1344     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1345   return Table;
1346 }
1347
1348 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1349 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1350 /// MCExpr.
1351 const MCExpr *X86TargetLowering::
1352 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1353                              MCContext &Ctx) const {
1354   // X86-64 uses RIP relative addressing based on the jump table label.
1355   if (Subtarget->isPICStyleRIPRel())
1356     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1357
1358   // Otherwise, the reference is relative to the PIC base.
1359   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1360 }
1361
1362 // FIXME: Why this routine is here? Move to RegInfo!
1363 std::pair<const TargetRegisterClass*, uint8_t>
1364 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1365   const TargetRegisterClass *RRC = 0;
1366   uint8_t Cost = 1;
1367   switch (VT.getSimpleVT().SimpleTy) {
1368   default:
1369     return TargetLowering::findRepresentativeClass(VT);
1370   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1371     RRC = (Subtarget->is64Bit()
1372            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1373     break;
1374   case MVT::x86mmx:
1375     RRC = X86::VR64RegisterClass;
1376     break;
1377   case MVT::f32: case MVT::f64:
1378   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1379   case MVT::v4f32: case MVT::v2f64:
1380   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1381   case MVT::v4f64:
1382     RRC = X86::VR128RegisterClass;
1383     break;
1384   }
1385   return std::make_pair(RRC, Cost);
1386 }
1387
1388 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1389                                                unsigned &Offset) const {
1390   if (!Subtarget->isTargetLinux())
1391     return false;
1392
1393   if (Subtarget->is64Bit()) {
1394     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1395     Offset = 0x28;
1396     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1397       AddressSpace = 256;
1398     else
1399       AddressSpace = 257;
1400   } else {
1401     // %gs:0x14 on i386
1402     Offset = 0x14;
1403     AddressSpace = 256;
1404   }
1405   return true;
1406 }
1407
1408
1409 //===----------------------------------------------------------------------===//
1410 //               Return Value Calling Convention Implementation
1411 //===----------------------------------------------------------------------===//
1412
1413 #include "X86GenCallingConv.inc"
1414
1415 bool
1416 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1417                                   MachineFunction &MF, bool isVarArg,
1418                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1419                         LLVMContext &Context) const {
1420   SmallVector<CCValAssign, 16> RVLocs;
1421   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1422                  RVLocs, Context);
1423   return CCInfo.CheckReturn(Outs, RetCC_X86);
1424 }
1425
1426 SDValue
1427 X86TargetLowering::LowerReturn(SDValue Chain,
1428                                CallingConv::ID CallConv, bool isVarArg,
1429                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1430                                const SmallVectorImpl<SDValue> &OutVals,
1431                                DebugLoc dl, SelectionDAG &DAG) const {
1432   MachineFunction &MF = DAG.getMachineFunction();
1433   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1434
1435   SmallVector<CCValAssign, 16> RVLocs;
1436   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1437                  RVLocs, *DAG.getContext());
1438   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1439
1440   // Add the regs to the liveout set for the function.
1441   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1442   for (unsigned i = 0; i != RVLocs.size(); ++i)
1443     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1444       MRI.addLiveOut(RVLocs[i].getLocReg());
1445
1446   SDValue Flag;
1447
1448   SmallVector<SDValue, 6> RetOps;
1449   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1450   // Operand #1 = Bytes To Pop
1451   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1452                    MVT::i16));
1453
1454   // Copy the result values into the output registers.
1455   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1456     CCValAssign &VA = RVLocs[i];
1457     assert(VA.isRegLoc() && "Can only return in registers!");
1458     SDValue ValToCopy = OutVals[i];
1459     EVT ValVT = ValToCopy.getValueType();
1460
1461     // If this is x86-64, and we disabled SSE, we can't return FP values,
1462     // or SSE or MMX vectors.
1463     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1464          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1465           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1466       report_fatal_error("SSE register return with SSE disabled");
1467     }
1468     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1469     // llvm-gcc has never done it right and no one has noticed, so this
1470     // should be OK for now.
1471     if (ValVT == MVT::f64 &&
1472         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1473       report_fatal_error("SSE2 register return with SSE2 disabled");
1474
1475     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1476     // the RET instruction and handled by the FP Stackifier.
1477     if (VA.getLocReg() == X86::ST0 ||
1478         VA.getLocReg() == X86::ST1) {
1479       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1480       // change the value to the FP stack register class.
1481       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1482         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1483       RetOps.push_back(ValToCopy);
1484       // Don't emit a copytoreg.
1485       continue;
1486     }
1487
1488     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1489     // which is returned in RAX / RDX.
1490     if (Subtarget->is64Bit()) {
1491       if (ValVT == MVT::x86mmx) {
1492         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1493           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1494           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1495                                   ValToCopy);
1496           // If we don't have SSE2 available, convert to v4f32 so the generated
1497           // register is legal.
1498           if (!Subtarget->hasXMMInt())
1499             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1500         }
1501       }
1502     }
1503
1504     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1505     Flag = Chain.getValue(1);
1506   }
1507
1508   // The x86-64 ABI for returning structs by value requires that we copy
1509   // the sret argument into %rax for the return. We saved the argument into
1510   // a virtual register in the entry block, so now we copy the value out
1511   // and into %rax.
1512   if (Subtarget->is64Bit() &&
1513       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1514     MachineFunction &MF = DAG.getMachineFunction();
1515     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1516     unsigned Reg = FuncInfo->getSRetReturnReg();
1517     assert(Reg &&
1518            "SRetReturnReg should have been set in LowerFormalArguments().");
1519     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1520
1521     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1522     Flag = Chain.getValue(1);
1523
1524     // RAX now acts like a return value.
1525     MRI.addLiveOut(X86::RAX);
1526   }
1527
1528   RetOps[0] = Chain;  // Update chain.
1529
1530   // Add the flag if we have it.
1531   if (Flag.getNode())
1532     RetOps.push_back(Flag);
1533
1534   return DAG.getNode(X86ISD::RET_FLAG, dl,
1535                      MVT::Other, &RetOps[0], RetOps.size());
1536 }
1537
1538 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1539   if (N->getNumValues() != 1)
1540     return false;
1541   if (!N->hasNUsesOfValue(1, 0))
1542     return false;
1543
1544   SDNode *Copy = *N->use_begin();
1545   if (Copy->getOpcode() != ISD::CopyToReg &&
1546       Copy->getOpcode() != ISD::FP_EXTEND)
1547     return false;
1548
1549   bool HasRet = false;
1550   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1551        UI != UE; ++UI) {
1552     if (UI->getOpcode() != X86ISD::RET_FLAG)
1553       return false;
1554     HasRet = true;
1555   }
1556
1557   return HasRet;
1558 }
1559
1560 EVT
1561 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1562                                             ISD::NodeType ExtendKind) const {
1563   MVT ReturnMVT;
1564   // TODO: Is this also valid on 32-bit?
1565   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1566     ReturnMVT = MVT::i8;
1567   else
1568     ReturnMVT = MVT::i32;
1569
1570   EVT MinVT = getRegisterType(Context, ReturnMVT);
1571   return VT.bitsLT(MinVT) ? MinVT : VT;
1572 }
1573
1574 /// LowerCallResult - Lower the result values of a call into the
1575 /// appropriate copies out of appropriate physical registers.
1576 ///
1577 SDValue
1578 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1579                                    CallingConv::ID CallConv, bool isVarArg,
1580                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1581                                    DebugLoc dl, SelectionDAG &DAG,
1582                                    SmallVectorImpl<SDValue> &InVals) const {
1583
1584   // Assign locations to each value returned by this call.
1585   SmallVector<CCValAssign, 16> RVLocs;
1586   bool Is64Bit = Subtarget->is64Bit();
1587   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1588                  getTargetMachine(), RVLocs, *DAG.getContext());
1589   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1590
1591   // Copy all of the result registers out of their specified physreg.
1592   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1593     CCValAssign &VA = RVLocs[i];
1594     EVT CopyVT = VA.getValVT();
1595
1596     // If this is x86-64, and we disabled SSE, we can't return FP values
1597     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1598         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1599       report_fatal_error("SSE register return with SSE disabled");
1600     }
1601
1602     SDValue Val;
1603
1604     // If this is a call to a function that returns an fp value on the floating
1605     // point stack, we must guarantee the the value is popped from the stack, so
1606     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1607     // if the return value is not used. We use the FpPOP_RETVAL instruction
1608     // instead.
1609     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1610       // If we prefer to use the value in xmm registers, copy it out as f80 and
1611       // use a truncate to move it from fp stack reg to xmm reg.
1612       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1613       SDValue Ops[] = { Chain, InFlag };
1614       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1615                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1616       Val = Chain.getValue(0);
1617
1618       // Round the f80 to the right size, which also moves it to the appropriate
1619       // xmm register.
1620       if (CopyVT != VA.getValVT())
1621         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1622                           // This truncation won't change the value.
1623                           DAG.getIntPtrConstant(1));
1624     } else {
1625       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1626                                  CopyVT, InFlag).getValue(1);
1627       Val = Chain.getValue(0);
1628     }
1629     InFlag = Chain.getValue(2);
1630     InVals.push_back(Val);
1631   }
1632
1633   return Chain;
1634 }
1635
1636
1637 //===----------------------------------------------------------------------===//
1638 //                C & StdCall & Fast Calling Convention implementation
1639 //===----------------------------------------------------------------------===//
1640 //  StdCall calling convention seems to be standard for many Windows' API
1641 //  routines and around. It differs from C calling convention just a little:
1642 //  callee should clean up the stack, not caller. Symbols should be also
1643 //  decorated in some fancy way :) It doesn't support any vector arguments.
1644 //  For info on fast calling convention see Fast Calling Convention (tail call)
1645 //  implementation LowerX86_32FastCCCallTo.
1646
1647 /// CallIsStructReturn - Determines whether a call uses struct return
1648 /// semantics.
1649 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1650   if (Outs.empty())
1651     return false;
1652
1653   return Outs[0].Flags.isSRet();
1654 }
1655
1656 /// ArgsAreStructReturn - Determines whether a function uses struct
1657 /// return semantics.
1658 static bool
1659 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1660   if (Ins.empty())
1661     return false;
1662
1663   return Ins[0].Flags.isSRet();
1664 }
1665
1666 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1667 /// by "Src" to address "Dst" with size and alignment information specified by
1668 /// the specific parameter attribute. The copy will be passed as a byval
1669 /// function parameter.
1670 static SDValue
1671 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1672                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1673                           DebugLoc dl) {
1674   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1675
1676   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1677                        /*isVolatile*/false, /*AlwaysInline=*/true,
1678                        MachinePointerInfo(), MachinePointerInfo());
1679 }
1680
1681 /// IsTailCallConvention - Return true if the calling convention is one that
1682 /// supports tail call optimization.
1683 static bool IsTailCallConvention(CallingConv::ID CC) {
1684   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1685 }
1686
1687 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1688   if (!CI->isTailCall())
1689     return false;
1690
1691   CallSite CS(CI);
1692   CallingConv::ID CalleeCC = CS.getCallingConv();
1693   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1694     return false;
1695
1696   return true;
1697 }
1698
1699 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1700 /// a tailcall target by changing its ABI.
1701 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1702   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1703 }
1704
1705 SDValue
1706 X86TargetLowering::LowerMemArgument(SDValue Chain,
1707                                     CallingConv::ID CallConv,
1708                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1709                                     DebugLoc dl, SelectionDAG &DAG,
1710                                     const CCValAssign &VA,
1711                                     MachineFrameInfo *MFI,
1712                                     unsigned i) const {
1713   // Create the nodes corresponding to a load from this parameter slot.
1714   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1715   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1716   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1717   EVT ValVT;
1718
1719   // If value is passed by pointer we have address passed instead of the value
1720   // itself.
1721   if (VA.getLocInfo() == CCValAssign::Indirect)
1722     ValVT = VA.getLocVT();
1723   else
1724     ValVT = VA.getValVT();
1725
1726   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1727   // changed with more analysis.
1728   // In case of tail call optimization mark all arguments mutable. Since they
1729   // could be overwritten by lowering of arguments in case of a tail call.
1730   if (Flags.isByVal()) {
1731     unsigned Bytes = Flags.getByValSize();
1732     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1733     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1734     return DAG.getFrameIndex(FI, getPointerTy());
1735   } else {
1736     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1737                                     VA.getLocMemOffset(), isImmutable);
1738     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1739     return DAG.getLoad(ValVT, dl, Chain, FIN,
1740                        MachinePointerInfo::getFixedStack(FI),
1741                        false, false, false, 0);
1742   }
1743 }
1744
1745 SDValue
1746 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1747                                         CallingConv::ID CallConv,
1748                                         bool isVarArg,
1749                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1750                                         DebugLoc dl,
1751                                         SelectionDAG &DAG,
1752                                         SmallVectorImpl<SDValue> &InVals)
1753                                           const {
1754   MachineFunction &MF = DAG.getMachineFunction();
1755   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1756
1757   const Function* Fn = MF.getFunction();
1758   if (Fn->hasExternalLinkage() &&
1759       Subtarget->isTargetCygMing() &&
1760       Fn->getName() == "main")
1761     FuncInfo->setForceFramePointer(true);
1762
1763   MachineFrameInfo *MFI = MF.getFrameInfo();
1764   bool Is64Bit = Subtarget->is64Bit();
1765   bool IsWin64 = Subtarget->isTargetWin64();
1766
1767   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1768          "Var args not supported with calling convention fastcc or ghc");
1769
1770   // Assign locations to all of the incoming arguments.
1771   SmallVector<CCValAssign, 16> ArgLocs;
1772   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1773                  ArgLocs, *DAG.getContext());
1774
1775   // Allocate shadow area for Win64
1776   if (IsWin64) {
1777     CCInfo.AllocateStack(32, 8);
1778   }
1779
1780   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1781
1782   unsigned LastVal = ~0U;
1783   SDValue ArgValue;
1784   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1785     CCValAssign &VA = ArgLocs[i];
1786     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1787     // places.
1788     assert(VA.getValNo() != LastVal &&
1789            "Don't support value assigned to multiple locs yet");
1790     (void)LastVal;
1791     LastVal = VA.getValNo();
1792
1793     if (VA.isRegLoc()) {
1794       EVT RegVT = VA.getLocVT();
1795       TargetRegisterClass *RC = NULL;
1796       if (RegVT == MVT::i32)
1797         RC = X86::GR32RegisterClass;
1798       else if (Is64Bit && RegVT == MVT::i64)
1799         RC = X86::GR64RegisterClass;
1800       else if (RegVT == MVT::f32)
1801         RC = X86::FR32RegisterClass;
1802       else if (RegVT == MVT::f64)
1803         RC = X86::FR64RegisterClass;
1804       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1805         RC = X86::VR256RegisterClass;
1806       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1807         RC = X86::VR128RegisterClass;
1808       else if (RegVT == MVT::x86mmx)
1809         RC = X86::VR64RegisterClass;
1810       else
1811         llvm_unreachable("Unknown argument type!");
1812
1813       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1814       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1815
1816       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1817       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1818       // right size.
1819       if (VA.getLocInfo() == CCValAssign::SExt)
1820         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1821                                DAG.getValueType(VA.getValVT()));
1822       else if (VA.getLocInfo() == CCValAssign::ZExt)
1823         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1824                                DAG.getValueType(VA.getValVT()));
1825       else if (VA.getLocInfo() == CCValAssign::BCvt)
1826         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1827
1828       if (VA.isExtInLoc()) {
1829         // Handle MMX values passed in XMM regs.
1830         if (RegVT.isVector()) {
1831           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1832                                  ArgValue);
1833         } else
1834           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1835       }
1836     } else {
1837       assert(VA.isMemLoc());
1838       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1839     }
1840
1841     // If value is passed via pointer - do a load.
1842     if (VA.getLocInfo() == CCValAssign::Indirect)
1843       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1844                              MachinePointerInfo(), false, false, false, 0);
1845
1846     InVals.push_back(ArgValue);
1847   }
1848
1849   // The x86-64 ABI for returning structs by value requires that we copy
1850   // the sret argument into %rax for the return. Save the argument into
1851   // a virtual register so that we can access it from the return points.
1852   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1853     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1854     unsigned Reg = FuncInfo->getSRetReturnReg();
1855     if (!Reg) {
1856       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1857       FuncInfo->setSRetReturnReg(Reg);
1858     }
1859     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1860     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1861   }
1862
1863   unsigned StackSize = CCInfo.getNextStackOffset();
1864   // Align stack specially for tail calls.
1865   if (FuncIsMadeTailCallSafe(CallConv))
1866     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1867
1868   // If the function takes variable number of arguments, make a frame index for
1869   // the start of the first vararg value... for expansion of llvm.va_start.
1870   if (isVarArg) {
1871     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1872                     CallConv != CallingConv::X86_ThisCall)) {
1873       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1874     }
1875     if (Is64Bit) {
1876       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1877
1878       // FIXME: We should really autogenerate these arrays
1879       static const unsigned GPR64ArgRegsWin64[] = {
1880         X86::RCX, X86::RDX, X86::R8,  X86::R9
1881       };
1882       static const unsigned GPR64ArgRegs64Bit[] = {
1883         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1884       };
1885       static const unsigned XMMArgRegs64Bit[] = {
1886         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1887         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1888       };
1889       const unsigned *GPR64ArgRegs;
1890       unsigned NumXMMRegs = 0;
1891
1892       if (IsWin64) {
1893         // The XMM registers which might contain var arg parameters are shadowed
1894         // in their paired GPR.  So we only need to save the GPR to their home
1895         // slots.
1896         TotalNumIntRegs = 4;
1897         GPR64ArgRegs = GPR64ArgRegsWin64;
1898       } else {
1899         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1900         GPR64ArgRegs = GPR64ArgRegs64Bit;
1901
1902         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1903       }
1904       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1905                                                        TotalNumIntRegs);
1906
1907       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1908       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1909              "SSE register cannot be used when SSE is disabled!");
1910       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1911              "SSE register cannot be used when SSE is disabled!");
1912       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1913         // Kernel mode asks for SSE to be disabled, so don't push them
1914         // on the stack.
1915         TotalNumXMMRegs = 0;
1916
1917       if (IsWin64) {
1918         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1919         // Get to the caller-allocated home save location.  Add 8 to account
1920         // for the return address.
1921         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1922         FuncInfo->setRegSaveFrameIndex(
1923           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1924         // Fixup to set vararg frame on shadow area (4 x i64).
1925         if (NumIntRegs < 4)
1926           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1927       } else {
1928         // For X86-64, if there are vararg parameters that are passed via
1929         // registers, then we must store them to their spots on the stack so they
1930         // may be loaded by deferencing the result of va_next.
1931         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1932         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1933         FuncInfo->setRegSaveFrameIndex(
1934           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1935                                false));
1936       }
1937
1938       // Store the integer parameter registers.
1939       SmallVector<SDValue, 8> MemOps;
1940       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1941                                         getPointerTy());
1942       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1943       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1944         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1945                                   DAG.getIntPtrConstant(Offset));
1946         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1947                                      X86::GR64RegisterClass);
1948         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1949         SDValue Store =
1950           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1951                        MachinePointerInfo::getFixedStack(
1952                          FuncInfo->getRegSaveFrameIndex(), Offset),
1953                        false, false, 0);
1954         MemOps.push_back(Store);
1955         Offset += 8;
1956       }
1957
1958       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1959         // Now store the XMM (fp + vector) parameter registers.
1960         SmallVector<SDValue, 11> SaveXMMOps;
1961         SaveXMMOps.push_back(Chain);
1962
1963         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1964         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1965         SaveXMMOps.push_back(ALVal);
1966
1967         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1968                                FuncInfo->getRegSaveFrameIndex()));
1969         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1970                                FuncInfo->getVarArgsFPOffset()));
1971
1972         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1973           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1974                                        X86::VR128RegisterClass);
1975           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1976           SaveXMMOps.push_back(Val);
1977         }
1978         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1979                                      MVT::Other,
1980                                      &SaveXMMOps[0], SaveXMMOps.size()));
1981       }
1982
1983       if (!MemOps.empty())
1984         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1985                             &MemOps[0], MemOps.size());
1986     }
1987   }
1988
1989   // Some CCs need callee pop.
1990   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1991     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1992   } else {
1993     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1994     // If this is an sret function, the return should pop the hidden pointer.
1995     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1996       FuncInfo->setBytesToPopOnReturn(4);
1997   }
1998
1999   if (!Is64Bit) {
2000     // RegSaveFrameIndex is X86-64 only.
2001     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2002     if (CallConv == CallingConv::X86_FastCall ||
2003         CallConv == CallingConv::X86_ThisCall)
2004       // fastcc functions can't have varargs.
2005       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2006   }
2007
2008   FuncInfo->setArgumentStackSize(StackSize);
2009
2010   return Chain;
2011 }
2012
2013 SDValue
2014 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2015                                     SDValue StackPtr, SDValue Arg,
2016                                     DebugLoc dl, SelectionDAG &DAG,
2017                                     const CCValAssign &VA,
2018                                     ISD::ArgFlagsTy Flags) const {
2019   unsigned LocMemOffset = VA.getLocMemOffset();
2020   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2021   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2022   if (Flags.isByVal())
2023     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2024
2025   return DAG.getStore(Chain, dl, Arg, PtrOff,
2026                       MachinePointerInfo::getStack(LocMemOffset),
2027                       false, false, 0);
2028 }
2029
2030 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2031 /// optimization is performed and it is required.
2032 SDValue
2033 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2034                                            SDValue &OutRetAddr, SDValue Chain,
2035                                            bool IsTailCall, bool Is64Bit,
2036                                            int FPDiff, DebugLoc dl) const {
2037   // Adjust the Return address stack slot.
2038   EVT VT = getPointerTy();
2039   OutRetAddr = getReturnAddressFrameIndex(DAG);
2040
2041   // Load the "old" Return address.
2042   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2043                            false, false, false, 0);
2044   return SDValue(OutRetAddr.getNode(), 1);
2045 }
2046
2047 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2048 /// optimization is performed and it is required (FPDiff!=0).
2049 static SDValue
2050 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2051                          SDValue Chain, SDValue RetAddrFrIdx,
2052                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2053   // Store the return address to the appropriate stack slot.
2054   if (!FPDiff) return Chain;
2055   // Calculate the new stack slot for the return address.
2056   int SlotSize = Is64Bit ? 8 : 4;
2057   int NewReturnAddrFI =
2058     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2059   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2060   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2061   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2062                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2063                        false, false, 0);
2064   return Chain;
2065 }
2066
2067 SDValue
2068 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2069                              CallingConv::ID CallConv, bool isVarArg,
2070                              bool &isTailCall,
2071                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2072                              const SmallVectorImpl<SDValue> &OutVals,
2073                              const SmallVectorImpl<ISD::InputArg> &Ins,
2074                              DebugLoc dl, SelectionDAG &DAG,
2075                              SmallVectorImpl<SDValue> &InVals) const {
2076   MachineFunction &MF = DAG.getMachineFunction();
2077   bool Is64Bit        = Subtarget->is64Bit();
2078   bool IsWin64        = Subtarget->isTargetWin64();
2079   bool IsStructRet    = CallIsStructReturn(Outs);
2080   bool IsSibcall      = false;
2081
2082   if (isTailCall) {
2083     // Check if it's really possible to do a tail call.
2084     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2085                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2086                                                    Outs, OutVals, Ins, DAG);
2087
2088     // Sibcalls are automatically detected tailcalls which do not require
2089     // ABI changes.
2090     if (!GuaranteedTailCallOpt && isTailCall)
2091       IsSibcall = true;
2092
2093     if (isTailCall)
2094       ++NumTailCalls;
2095   }
2096
2097   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2098          "Var args not supported with calling convention fastcc or ghc");
2099
2100   // Analyze operands of the call, assigning locations to each operand.
2101   SmallVector<CCValAssign, 16> ArgLocs;
2102   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2103                  ArgLocs, *DAG.getContext());
2104
2105   // Allocate shadow area for Win64
2106   if (IsWin64) {
2107     CCInfo.AllocateStack(32, 8);
2108   }
2109
2110   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2111
2112   // Get a count of how many bytes are to be pushed on the stack.
2113   unsigned NumBytes = CCInfo.getNextStackOffset();
2114   if (IsSibcall)
2115     // This is a sibcall. The memory operands are available in caller's
2116     // own caller's stack.
2117     NumBytes = 0;
2118   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2119     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2120
2121   int FPDiff = 0;
2122   if (isTailCall && !IsSibcall) {
2123     // Lower arguments at fp - stackoffset + fpdiff.
2124     unsigned NumBytesCallerPushed =
2125       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2126     FPDiff = NumBytesCallerPushed - NumBytes;
2127
2128     // Set the delta of movement of the returnaddr stackslot.
2129     // But only set if delta is greater than previous delta.
2130     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2131       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2132   }
2133
2134   if (!IsSibcall)
2135     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2136
2137   SDValue RetAddrFrIdx;
2138   // Load return address for tail calls.
2139   if (isTailCall && FPDiff)
2140     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2141                                     Is64Bit, FPDiff, dl);
2142
2143   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2144   SmallVector<SDValue, 8> MemOpChains;
2145   SDValue StackPtr;
2146
2147   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2148   // of tail call optimization arguments are handle later.
2149   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2150     CCValAssign &VA = ArgLocs[i];
2151     EVT RegVT = VA.getLocVT();
2152     SDValue Arg = OutVals[i];
2153     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2154     bool isByVal = Flags.isByVal();
2155
2156     // Promote the value if needed.
2157     switch (VA.getLocInfo()) {
2158     default: llvm_unreachable("Unknown loc info!");
2159     case CCValAssign::Full: break;
2160     case CCValAssign::SExt:
2161       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2162       break;
2163     case CCValAssign::ZExt:
2164       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2165       break;
2166     case CCValAssign::AExt:
2167       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2168         // Special case: passing MMX values in XMM registers.
2169         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2170         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2171         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2172       } else
2173         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2174       break;
2175     case CCValAssign::BCvt:
2176       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2177       break;
2178     case CCValAssign::Indirect: {
2179       // Store the argument.
2180       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2181       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2182       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2183                            MachinePointerInfo::getFixedStack(FI),
2184                            false, false, 0);
2185       Arg = SpillSlot;
2186       break;
2187     }
2188     }
2189
2190     if (VA.isRegLoc()) {
2191       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2192       if (isVarArg && IsWin64) {
2193         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2194         // shadow reg if callee is a varargs function.
2195         unsigned ShadowReg = 0;
2196         switch (VA.getLocReg()) {
2197         case X86::XMM0: ShadowReg = X86::RCX; break;
2198         case X86::XMM1: ShadowReg = X86::RDX; break;
2199         case X86::XMM2: ShadowReg = X86::R8; break;
2200         case X86::XMM3: ShadowReg = X86::R9; break;
2201         }
2202         if (ShadowReg)
2203           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2204       }
2205     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2206       assert(VA.isMemLoc());
2207       if (StackPtr.getNode() == 0)
2208         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2209       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2210                                              dl, DAG, VA, Flags));
2211     }
2212   }
2213
2214   if (!MemOpChains.empty())
2215     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2216                         &MemOpChains[0], MemOpChains.size());
2217
2218   // Build a sequence of copy-to-reg nodes chained together with token chain
2219   // and flag operands which copy the outgoing args into registers.
2220   SDValue InFlag;
2221   // Tail call byval lowering might overwrite argument registers so in case of
2222   // tail call optimization the copies to registers are lowered later.
2223   if (!isTailCall)
2224     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2225       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2226                                RegsToPass[i].second, InFlag);
2227       InFlag = Chain.getValue(1);
2228     }
2229
2230   if (Subtarget->isPICStyleGOT()) {
2231     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2232     // GOT pointer.
2233     if (!isTailCall) {
2234       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2235                                DAG.getNode(X86ISD::GlobalBaseReg,
2236                                            DebugLoc(), getPointerTy()),
2237                                InFlag);
2238       InFlag = Chain.getValue(1);
2239     } else {
2240       // If we are tail calling and generating PIC/GOT style code load the
2241       // address of the callee into ECX. The value in ecx is used as target of
2242       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2243       // for tail calls on PIC/GOT architectures. Normally we would just put the
2244       // address of GOT into ebx and then call target@PLT. But for tail calls
2245       // ebx would be restored (since ebx is callee saved) before jumping to the
2246       // target@PLT.
2247
2248       // Note: The actual moving to ECX is done further down.
2249       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2250       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2251           !G->getGlobal()->hasProtectedVisibility())
2252         Callee = LowerGlobalAddress(Callee, DAG);
2253       else if (isa<ExternalSymbolSDNode>(Callee))
2254         Callee = LowerExternalSymbol(Callee, DAG);
2255     }
2256   }
2257
2258   if (Is64Bit && isVarArg && !IsWin64) {
2259     // From AMD64 ABI document:
2260     // For calls that may call functions that use varargs or stdargs
2261     // (prototype-less calls or calls to functions containing ellipsis (...) in
2262     // the declaration) %al is used as hidden argument to specify the number
2263     // of SSE registers used. The contents of %al do not need to match exactly
2264     // the number of registers, but must be an ubound on the number of SSE
2265     // registers used and is in the range 0 - 8 inclusive.
2266
2267     // Count the number of XMM registers allocated.
2268     static const unsigned XMMArgRegs[] = {
2269       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2270       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2271     };
2272     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2273     assert((Subtarget->hasXMM() || !NumXMMRegs)
2274            && "SSE registers cannot be used when SSE is disabled");
2275
2276     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2277                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2278     InFlag = Chain.getValue(1);
2279   }
2280
2281
2282   // For tail calls lower the arguments to the 'real' stack slot.
2283   if (isTailCall) {
2284     // Force all the incoming stack arguments to be loaded from the stack
2285     // before any new outgoing arguments are stored to the stack, because the
2286     // outgoing stack slots may alias the incoming argument stack slots, and
2287     // the alias isn't otherwise explicit. This is slightly more conservative
2288     // than necessary, because it means that each store effectively depends
2289     // on every argument instead of just those arguments it would clobber.
2290     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2291
2292     SmallVector<SDValue, 8> MemOpChains2;
2293     SDValue FIN;
2294     int FI = 0;
2295     // Do not flag preceding copytoreg stuff together with the following stuff.
2296     InFlag = SDValue();
2297     if (GuaranteedTailCallOpt) {
2298       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2299         CCValAssign &VA = ArgLocs[i];
2300         if (VA.isRegLoc())
2301           continue;
2302         assert(VA.isMemLoc());
2303         SDValue Arg = OutVals[i];
2304         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2305         // Create frame index.
2306         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2307         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2308         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2309         FIN = DAG.getFrameIndex(FI, getPointerTy());
2310
2311         if (Flags.isByVal()) {
2312           // Copy relative to framepointer.
2313           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2314           if (StackPtr.getNode() == 0)
2315             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2316                                           getPointerTy());
2317           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2318
2319           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2320                                                            ArgChain,
2321                                                            Flags, DAG, dl));
2322         } else {
2323           // Store relative to framepointer.
2324           MemOpChains2.push_back(
2325             DAG.getStore(ArgChain, dl, Arg, FIN,
2326                          MachinePointerInfo::getFixedStack(FI),
2327                          false, false, 0));
2328         }
2329       }
2330     }
2331
2332     if (!MemOpChains2.empty())
2333       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2334                           &MemOpChains2[0], MemOpChains2.size());
2335
2336     // Copy arguments to their registers.
2337     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2338       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2339                                RegsToPass[i].second, InFlag);
2340       InFlag = Chain.getValue(1);
2341     }
2342     InFlag =SDValue();
2343
2344     // Store the return address to the appropriate stack slot.
2345     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2346                                      FPDiff, dl);
2347   }
2348
2349   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2350     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2351     // In the 64-bit large code model, we have to make all calls
2352     // through a register, since the call instruction's 32-bit
2353     // pc-relative offset may not be large enough to hold the whole
2354     // address.
2355   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2356     // If the callee is a GlobalAddress node (quite common, every direct call
2357     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2358     // it.
2359
2360     // We should use extra load for direct calls to dllimported functions in
2361     // non-JIT mode.
2362     const GlobalValue *GV = G->getGlobal();
2363     if (!GV->hasDLLImportLinkage()) {
2364       unsigned char OpFlags = 0;
2365       bool ExtraLoad = false;
2366       unsigned WrapperKind = ISD::DELETED_NODE;
2367
2368       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2369       // external symbols most go through the PLT in PIC mode.  If the symbol
2370       // has hidden or protected visibility, or if it is static or local, then
2371       // we don't need to use the PLT - we can directly call it.
2372       if (Subtarget->isTargetELF() &&
2373           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2374           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2375         OpFlags = X86II::MO_PLT;
2376       } else if (Subtarget->isPICStyleStubAny() &&
2377                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2378                  (!Subtarget->getTargetTriple().isMacOSX() ||
2379                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2380         // PC-relative references to external symbols should go through $stub,
2381         // unless we're building with the leopard linker or later, which
2382         // automatically synthesizes these stubs.
2383         OpFlags = X86II::MO_DARWIN_STUB;
2384       } else if (Subtarget->isPICStyleRIPRel() &&
2385                  isa<Function>(GV) &&
2386                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2387         // If the function is marked as non-lazy, generate an indirect call
2388         // which loads from the GOT directly. This avoids runtime overhead
2389         // at the cost of eager binding (and one extra byte of encoding).
2390         OpFlags = X86II::MO_GOTPCREL;
2391         WrapperKind = X86ISD::WrapperRIP;
2392         ExtraLoad = true;
2393       }
2394
2395       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2396                                           G->getOffset(), OpFlags);
2397
2398       // Add a wrapper if needed.
2399       if (WrapperKind != ISD::DELETED_NODE)
2400         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2401       // Add extra indirection if needed.
2402       if (ExtraLoad)
2403         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2404                              MachinePointerInfo::getGOT(),
2405                              false, false, false, 0);
2406     }
2407   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2408     unsigned char OpFlags = 0;
2409
2410     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2411     // external symbols should go through the PLT.
2412     if (Subtarget->isTargetELF() &&
2413         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2414       OpFlags = X86II::MO_PLT;
2415     } else if (Subtarget->isPICStyleStubAny() &&
2416                (!Subtarget->getTargetTriple().isMacOSX() ||
2417                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2418       // PC-relative references to external symbols should go through $stub,
2419       // unless we're building with the leopard linker or later, which
2420       // automatically synthesizes these stubs.
2421       OpFlags = X86II::MO_DARWIN_STUB;
2422     }
2423
2424     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2425                                          OpFlags);
2426   }
2427
2428   // Returns a chain & a flag for retval copy to use.
2429   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2430   SmallVector<SDValue, 8> Ops;
2431
2432   if (!IsSibcall && isTailCall) {
2433     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2434                            DAG.getIntPtrConstant(0, true), InFlag);
2435     InFlag = Chain.getValue(1);
2436   }
2437
2438   Ops.push_back(Chain);
2439   Ops.push_back(Callee);
2440
2441   if (isTailCall)
2442     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2443
2444   // Add argument registers to the end of the list so that they are known live
2445   // into the call.
2446   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2447     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2448                                   RegsToPass[i].second.getValueType()));
2449
2450   // Add an implicit use GOT pointer in EBX.
2451   if (!isTailCall && Subtarget->isPICStyleGOT())
2452     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2453
2454   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2455   if (Is64Bit && isVarArg && !IsWin64)
2456     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2457
2458   if (InFlag.getNode())
2459     Ops.push_back(InFlag);
2460
2461   if (isTailCall) {
2462     // We used to do:
2463     //// If this is the first return lowered for this function, add the regs
2464     //// to the liveout set for the function.
2465     // This isn't right, although it's probably harmless on x86; liveouts
2466     // should be computed from returns not tail calls.  Consider a void
2467     // function making a tail call to a function returning int.
2468     return DAG.getNode(X86ISD::TC_RETURN, dl,
2469                        NodeTys, &Ops[0], Ops.size());
2470   }
2471
2472   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2473   InFlag = Chain.getValue(1);
2474
2475   // Create the CALLSEQ_END node.
2476   unsigned NumBytesForCalleeToPush;
2477   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2478     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2479   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2480     // If this is a call to a struct-return function, the callee
2481     // pops the hidden struct pointer, so we have to push it back.
2482     // This is common for Darwin/X86, Linux & Mingw32 targets.
2483     NumBytesForCalleeToPush = 4;
2484   else
2485     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2486
2487   // Returns a flag for retval copy to use.
2488   if (!IsSibcall) {
2489     Chain = DAG.getCALLSEQ_END(Chain,
2490                                DAG.getIntPtrConstant(NumBytes, true),
2491                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2492                                                      true),
2493                                InFlag);
2494     InFlag = Chain.getValue(1);
2495   }
2496
2497   // Handle result values, copying them out of physregs into vregs that we
2498   // return.
2499   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2500                          Ins, dl, DAG, InVals);
2501 }
2502
2503
2504 //===----------------------------------------------------------------------===//
2505 //                Fast Calling Convention (tail call) implementation
2506 //===----------------------------------------------------------------------===//
2507
2508 //  Like std call, callee cleans arguments, convention except that ECX is
2509 //  reserved for storing the tail called function address. Only 2 registers are
2510 //  free for argument passing (inreg). Tail call optimization is performed
2511 //  provided:
2512 //                * tailcallopt is enabled
2513 //                * caller/callee are fastcc
2514 //  On X86_64 architecture with GOT-style position independent code only local
2515 //  (within module) calls are supported at the moment.
2516 //  To keep the stack aligned according to platform abi the function
2517 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2518 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2519 //  If a tail called function callee has more arguments than the caller the
2520 //  caller needs to make sure that there is room to move the RETADDR to. This is
2521 //  achieved by reserving an area the size of the argument delta right after the
2522 //  original REtADDR, but before the saved framepointer or the spilled registers
2523 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2524 //  stack layout:
2525 //    arg1
2526 //    arg2
2527 //    RETADDR
2528 //    [ new RETADDR
2529 //      move area ]
2530 //    (possible EBP)
2531 //    ESI
2532 //    EDI
2533 //    local1 ..
2534
2535 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2536 /// for a 16 byte align requirement.
2537 unsigned
2538 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2539                                                SelectionDAG& DAG) const {
2540   MachineFunction &MF = DAG.getMachineFunction();
2541   const TargetMachine &TM = MF.getTarget();
2542   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2543   unsigned StackAlignment = TFI.getStackAlignment();
2544   uint64_t AlignMask = StackAlignment - 1;
2545   int64_t Offset = StackSize;
2546   uint64_t SlotSize = TD->getPointerSize();
2547   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2548     // Number smaller than 12 so just add the difference.
2549     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2550   } else {
2551     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2552     Offset = ((~AlignMask) & Offset) + StackAlignment +
2553       (StackAlignment-SlotSize);
2554   }
2555   return Offset;
2556 }
2557
2558 /// MatchingStackOffset - Return true if the given stack call argument is
2559 /// already available in the same position (relatively) of the caller's
2560 /// incoming argument stack.
2561 static
2562 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2563                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2564                          const X86InstrInfo *TII) {
2565   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2566   int FI = INT_MAX;
2567   if (Arg.getOpcode() == ISD::CopyFromReg) {
2568     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2569     if (!TargetRegisterInfo::isVirtualRegister(VR))
2570       return false;
2571     MachineInstr *Def = MRI->getVRegDef(VR);
2572     if (!Def)
2573       return false;
2574     if (!Flags.isByVal()) {
2575       if (!TII->isLoadFromStackSlot(Def, FI))
2576         return false;
2577     } else {
2578       unsigned Opcode = Def->getOpcode();
2579       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2580           Def->getOperand(1).isFI()) {
2581         FI = Def->getOperand(1).getIndex();
2582         Bytes = Flags.getByValSize();
2583       } else
2584         return false;
2585     }
2586   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2587     if (Flags.isByVal())
2588       // ByVal argument is passed in as a pointer but it's now being
2589       // dereferenced. e.g.
2590       // define @foo(%struct.X* %A) {
2591       //   tail call @bar(%struct.X* byval %A)
2592       // }
2593       return false;
2594     SDValue Ptr = Ld->getBasePtr();
2595     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2596     if (!FINode)
2597       return false;
2598     FI = FINode->getIndex();
2599   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2600     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2601     FI = FINode->getIndex();
2602     Bytes = Flags.getByValSize();
2603   } else
2604     return false;
2605
2606   assert(FI != INT_MAX);
2607   if (!MFI->isFixedObjectIndex(FI))
2608     return false;
2609   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2610 }
2611
2612 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2613 /// for tail call optimization. Targets which want to do tail call
2614 /// optimization should implement this function.
2615 bool
2616 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2617                                                      CallingConv::ID CalleeCC,
2618                                                      bool isVarArg,
2619                                                      bool isCalleeStructRet,
2620                                                      bool isCallerStructRet,
2621                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2622                                     const SmallVectorImpl<SDValue> &OutVals,
2623                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2624                                                      SelectionDAG& DAG) const {
2625   if (!IsTailCallConvention(CalleeCC) &&
2626       CalleeCC != CallingConv::C)
2627     return false;
2628
2629   // If -tailcallopt is specified, make fastcc functions tail-callable.
2630   const MachineFunction &MF = DAG.getMachineFunction();
2631   const Function *CallerF = DAG.getMachineFunction().getFunction();
2632   CallingConv::ID CallerCC = CallerF->getCallingConv();
2633   bool CCMatch = CallerCC == CalleeCC;
2634
2635   if (GuaranteedTailCallOpt) {
2636     if (IsTailCallConvention(CalleeCC) && CCMatch)
2637       return true;
2638     return false;
2639   }
2640
2641   // Look for obvious safe cases to perform tail call optimization that do not
2642   // require ABI changes. This is what gcc calls sibcall.
2643
2644   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2645   // emit a special epilogue.
2646   if (RegInfo->needsStackRealignment(MF))
2647     return false;
2648
2649   // Also avoid sibcall optimization if either caller or callee uses struct
2650   // return semantics.
2651   if (isCalleeStructRet || isCallerStructRet)
2652     return false;
2653
2654   // An stdcall caller is expected to clean up its arguments; the callee
2655   // isn't going to do that.
2656   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2657     return false;
2658
2659   // Do not sibcall optimize vararg calls unless all arguments are passed via
2660   // registers.
2661   if (isVarArg && !Outs.empty()) {
2662
2663     // Optimizing for varargs on Win64 is unlikely to be safe without
2664     // additional testing.
2665     if (Subtarget->isTargetWin64())
2666       return false;
2667
2668     SmallVector<CCValAssign, 16> ArgLocs;
2669     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2670                    getTargetMachine(), ArgLocs, *DAG.getContext());
2671
2672     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2673     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2674       if (!ArgLocs[i].isRegLoc())
2675         return false;
2676   }
2677
2678   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2679   // Therefore if it's not used by the call it is not safe to optimize this into
2680   // a sibcall.
2681   bool Unused = false;
2682   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2683     if (!Ins[i].Used) {
2684       Unused = true;
2685       break;
2686     }
2687   }
2688   if (Unused) {
2689     SmallVector<CCValAssign, 16> RVLocs;
2690     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2691                    getTargetMachine(), RVLocs, *DAG.getContext());
2692     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2693     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2694       CCValAssign &VA = RVLocs[i];
2695       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2696         return false;
2697     }
2698   }
2699
2700   // If the calling conventions do not match, then we'd better make sure the
2701   // results are returned in the same way as what the caller expects.
2702   if (!CCMatch) {
2703     SmallVector<CCValAssign, 16> RVLocs1;
2704     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2705                     getTargetMachine(), RVLocs1, *DAG.getContext());
2706     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2707
2708     SmallVector<CCValAssign, 16> RVLocs2;
2709     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2710                     getTargetMachine(), RVLocs2, *DAG.getContext());
2711     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2712
2713     if (RVLocs1.size() != RVLocs2.size())
2714       return false;
2715     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2716       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2717         return false;
2718       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2719         return false;
2720       if (RVLocs1[i].isRegLoc()) {
2721         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2722           return false;
2723       } else {
2724         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2725           return false;
2726       }
2727     }
2728   }
2729
2730   // If the callee takes no arguments then go on to check the results of the
2731   // call.
2732   if (!Outs.empty()) {
2733     // Check if stack adjustment is needed. For now, do not do this if any
2734     // argument is passed on the stack.
2735     SmallVector<CCValAssign, 16> ArgLocs;
2736     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2737                    getTargetMachine(), ArgLocs, *DAG.getContext());
2738
2739     // Allocate shadow area for Win64
2740     if (Subtarget->isTargetWin64()) {
2741       CCInfo.AllocateStack(32, 8);
2742     }
2743
2744     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2745     if (CCInfo.getNextStackOffset()) {
2746       MachineFunction &MF = DAG.getMachineFunction();
2747       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2748         return false;
2749
2750       // Check if the arguments are already laid out in the right way as
2751       // the caller's fixed stack objects.
2752       MachineFrameInfo *MFI = MF.getFrameInfo();
2753       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2754       const X86InstrInfo *TII =
2755         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2756       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2757         CCValAssign &VA = ArgLocs[i];
2758         SDValue Arg = OutVals[i];
2759         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2760         if (VA.getLocInfo() == CCValAssign::Indirect)
2761           return false;
2762         if (!VA.isRegLoc()) {
2763           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2764                                    MFI, MRI, TII))
2765             return false;
2766         }
2767       }
2768     }
2769
2770     // If the tailcall address may be in a register, then make sure it's
2771     // possible to register allocate for it. In 32-bit, the call address can
2772     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2773     // callee-saved registers are restored. These happen to be the same
2774     // registers used to pass 'inreg' arguments so watch out for those.
2775     if (!Subtarget->is64Bit() &&
2776         !isa<GlobalAddressSDNode>(Callee) &&
2777         !isa<ExternalSymbolSDNode>(Callee)) {
2778       unsigned NumInRegs = 0;
2779       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2780         CCValAssign &VA = ArgLocs[i];
2781         if (!VA.isRegLoc())
2782           continue;
2783         unsigned Reg = VA.getLocReg();
2784         switch (Reg) {
2785         default: break;
2786         case X86::EAX: case X86::EDX: case X86::ECX:
2787           if (++NumInRegs == 3)
2788             return false;
2789           break;
2790         }
2791       }
2792     }
2793   }
2794
2795   return true;
2796 }
2797
2798 FastISel *
2799 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2800   return X86::createFastISel(funcInfo);
2801 }
2802
2803
2804 //===----------------------------------------------------------------------===//
2805 //                           Other Lowering Hooks
2806 //===----------------------------------------------------------------------===//
2807
2808 static bool MayFoldLoad(SDValue Op) {
2809   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2810 }
2811
2812 static bool MayFoldIntoStore(SDValue Op) {
2813   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2814 }
2815
2816 static bool isTargetShuffle(unsigned Opcode) {
2817   switch(Opcode) {
2818   default: return false;
2819   case X86ISD::PSHUFD:
2820   case X86ISD::PSHUFHW:
2821   case X86ISD::PSHUFLW:
2822   case X86ISD::SHUFPD:
2823   case X86ISD::PALIGN:
2824   case X86ISD::SHUFPS:
2825   case X86ISD::MOVLHPS:
2826   case X86ISD::MOVLHPD:
2827   case X86ISD::MOVHLPS:
2828   case X86ISD::MOVLPS:
2829   case X86ISD::MOVLPD:
2830   case X86ISD::MOVSHDUP:
2831   case X86ISD::MOVSLDUP:
2832   case X86ISD::MOVDDUP:
2833   case X86ISD::MOVSS:
2834   case X86ISD::MOVSD:
2835   case X86ISD::UNPCKLPS:
2836   case X86ISD::UNPCKLPD:
2837   case X86ISD::VUNPCKLPSY:
2838   case X86ISD::VUNPCKLPDY:
2839   case X86ISD::PUNPCKLWD:
2840   case X86ISD::PUNPCKLBW:
2841   case X86ISD::PUNPCKLDQ:
2842   case X86ISD::PUNPCKLQDQ:
2843   case X86ISD::UNPCKHPS:
2844   case X86ISD::UNPCKHPD:
2845   case X86ISD::VUNPCKHPSY:
2846   case X86ISD::VUNPCKHPDY:
2847   case X86ISD::PUNPCKHWD:
2848   case X86ISD::PUNPCKHBW:
2849   case X86ISD::PUNPCKHDQ:
2850   case X86ISD::PUNPCKHQDQ:
2851   case X86ISD::VPERMILPS:
2852   case X86ISD::VPERMILPSY:
2853   case X86ISD::VPERMILPD:
2854   case X86ISD::VPERMILPDY:
2855   case X86ISD::VPERM2F128:
2856     return true;
2857   }
2858   return false;
2859 }
2860
2861 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2862                                                SDValue V1, SelectionDAG &DAG) {
2863   switch(Opc) {
2864   default: llvm_unreachable("Unknown x86 shuffle node");
2865   case X86ISD::MOVSHDUP:
2866   case X86ISD::MOVSLDUP:
2867   case X86ISD::MOVDDUP:
2868     return DAG.getNode(Opc, dl, VT, V1);
2869   }
2870
2871   return SDValue();
2872 }
2873
2874 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2875                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2876   switch(Opc) {
2877   default: llvm_unreachable("Unknown x86 shuffle node");
2878   case X86ISD::PSHUFD:
2879   case X86ISD::PSHUFHW:
2880   case X86ISD::PSHUFLW:
2881   case X86ISD::VPERMILPS:
2882   case X86ISD::VPERMILPSY:
2883   case X86ISD::VPERMILPD:
2884   case X86ISD::VPERMILPDY:
2885     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2886   }
2887
2888   return SDValue();
2889 }
2890
2891 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2892                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2893   switch(Opc) {
2894   default: llvm_unreachable("Unknown x86 shuffle node");
2895   case X86ISD::PALIGN:
2896   case X86ISD::SHUFPD:
2897   case X86ISD::SHUFPS:
2898   case X86ISD::VPERM2F128:
2899     return DAG.getNode(Opc, dl, VT, V1, V2,
2900                        DAG.getConstant(TargetMask, MVT::i8));
2901   }
2902   return SDValue();
2903 }
2904
2905 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2906                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2907   switch(Opc) {
2908   default: llvm_unreachable("Unknown x86 shuffle node");
2909   case X86ISD::MOVLHPS:
2910   case X86ISD::MOVLHPD:
2911   case X86ISD::MOVHLPS:
2912   case X86ISD::MOVLPS:
2913   case X86ISD::MOVLPD:
2914   case X86ISD::MOVSS:
2915   case X86ISD::MOVSD:
2916   case X86ISD::UNPCKLPS:
2917   case X86ISD::UNPCKLPD:
2918   case X86ISD::VUNPCKLPSY:
2919   case X86ISD::VUNPCKLPDY:
2920   case X86ISD::PUNPCKLWD:
2921   case X86ISD::PUNPCKLBW:
2922   case X86ISD::PUNPCKLDQ:
2923   case X86ISD::PUNPCKLQDQ:
2924   case X86ISD::UNPCKHPS:
2925   case X86ISD::UNPCKHPD:
2926   case X86ISD::VUNPCKHPSY:
2927   case X86ISD::VUNPCKHPDY:
2928   case X86ISD::PUNPCKHWD:
2929   case X86ISD::PUNPCKHBW:
2930   case X86ISD::PUNPCKHDQ:
2931   case X86ISD::PUNPCKHQDQ:
2932     return DAG.getNode(Opc, dl, VT, V1, V2);
2933   }
2934   return SDValue();
2935 }
2936
2937 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2938   MachineFunction &MF = DAG.getMachineFunction();
2939   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2940   int ReturnAddrIndex = FuncInfo->getRAIndex();
2941
2942   if (ReturnAddrIndex == 0) {
2943     // Set up a frame object for the return address.
2944     uint64_t SlotSize = TD->getPointerSize();
2945     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2946                                                            false);
2947     FuncInfo->setRAIndex(ReturnAddrIndex);
2948   }
2949
2950   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2951 }
2952
2953
2954 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2955                                        bool hasSymbolicDisplacement) {
2956   // Offset should fit into 32 bit immediate field.
2957   if (!isInt<32>(Offset))
2958     return false;
2959
2960   // If we don't have a symbolic displacement - we don't have any extra
2961   // restrictions.
2962   if (!hasSymbolicDisplacement)
2963     return true;
2964
2965   // FIXME: Some tweaks might be needed for medium code model.
2966   if (M != CodeModel::Small && M != CodeModel::Kernel)
2967     return false;
2968
2969   // For small code model we assume that latest object is 16MB before end of 31
2970   // bits boundary. We may also accept pretty large negative constants knowing
2971   // that all objects are in the positive half of address space.
2972   if (M == CodeModel::Small && Offset < 16*1024*1024)
2973     return true;
2974
2975   // For kernel code model we know that all object resist in the negative half
2976   // of 32bits address space. We may not accept negative offsets, since they may
2977   // be just off and we may accept pretty large positive ones.
2978   if (M == CodeModel::Kernel && Offset > 0)
2979     return true;
2980
2981   return false;
2982 }
2983
2984 /// isCalleePop - Determines whether the callee is required to pop its
2985 /// own arguments. Callee pop is necessary to support tail calls.
2986 bool X86::isCalleePop(CallingConv::ID CallingConv,
2987                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2988   if (IsVarArg)
2989     return false;
2990
2991   switch (CallingConv) {
2992   default:
2993     return false;
2994   case CallingConv::X86_StdCall:
2995     return !is64Bit;
2996   case CallingConv::X86_FastCall:
2997     return !is64Bit;
2998   case CallingConv::X86_ThisCall:
2999     return !is64Bit;
3000   case CallingConv::Fast:
3001     return TailCallOpt;
3002   case CallingConv::GHC:
3003     return TailCallOpt;
3004   }
3005 }
3006
3007 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3008 /// specific condition code, returning the condition code and the LHS/RHS of the
3009 /// comparison to make.
3010 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3011                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3012   if (!isFP) {
3013     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3014       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3015         // X > -1   -> X == 0, jump !sign.
3016         RHS = DAG.getConstant(0, RHS.getValueType());
3017         return X86::COND_NS;
3018       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3019         // X < 0   -> X == 0, jump on sign.
3020         return X86::COND_S;
3021       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3022         // X < 1   -> X <= 0
3023         RHS = DAG.getConstant(0, RHS.getValueType());
3024         return X86::COND_LE;
3025       }
3026     }
3027
3028     switch (SetCCOpcode) {
3029     default: llvm_unreachable("Invalid integer condition!");
3030     case ISD::SETEQ:  return X86::COND_E;
3031     case ISD::SETGT:  return X86::COND_G;
3032     case ISD::SETGE:  return X86::COND_GE;
3033     case ISD::SETLT:  return X86::COND_L;
3034     case ISD::SETLE:  return X86::COND_LE;
3035     case ISD::SETNE:  return X86::COND_NE;
3036     case ISD::SETULT: return X86::COND_B;
3037     case ISD::SETUGT: return X86::COND_A;
3038     case ISD::SETULE: return X86::COND_BE;
3039     case ISD::SETUGE: return X86::COND_AE;
3040     }
3041   }
3042
3043   // First determine if it is required or is profitable to flip the operands.
3044
3045   // If LHS is a foldable load, but RHS is not, flip the condition.
3046   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3047       !ISD::isNON_EXTLoad(RHS.getNode())) {
3048     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3049     std::swap(LHS, RHS);
3050   }
3051
3052   switch (SetCCOpcode) {
3053   default: break;
3054   case ISD::SETOLT:
3055   case ISD::SETOLE:
3056   case ISD::SETUGT:
3057   case ISD::SETUGE:
3058     std::swap(LHS, RHS);
3059     break;
3060   }
3061
3062   // On a floating point condition, the flags are set as follows:
3063   // ZF  PF  CF   op
3064   //  0 | 0 | 0 | X > Y
3065   //  0 | 0 | 1 | X < Y
3066   //  1 | 0 | 0 | X == Y
3067   //  1 | 1 | 1 | unordered
3068   switch (SetCCOpcode) {
3069   default: llvm_unreachable("Condcode should be pre-legalized away");
3070   case ISD::SETUEQ:
3071   case ISD::SETEQ:   return X86::COND_E;
3072   case ISD::SETOLT:              // flipped
3073   case ISD::SETOGT:
3074   case ISD::SETGT:   return X86::COND_A;
3075   case ISD::SETOLE:              // flipped
3076   case ISD::SETOGE:
3077   case ISD::SETGE:   return X86::COND_AE;
3078   case ISD::SETUGT:              // flipped
3079   case ISD::SETULT:
3080   case ISD::SETLT:   return X86::COND_B;
3081   case ISD::SETUGE:              // flipped
3082   case ISD::SETULE:
3083   case ISD::SETLE:   return X86::COND_BE;
3084   case ISD::SETONE:
3085   case ISD::SETNE:   return X86::COND_NE;
3086   case ISD::SETUO:   return X86::COND_P;
3087   case ISD::SETO:    return X86::COND_NP;
3088   case ISD::SETOEQ:
3089   case ISD::SETUNE:  return X86::COND_INVALID;
3090   }
3091 }
3092
3093 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3094 /// code. Current x86 isa includes the following FP cmov instructions:
3095 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3096 static bool hasFPCMov(unsigned X86CC) {
3097   switch (X86CC) {
3098   default:
3099     return false;
3100   case X86::COND_B:
3101   case X86::COND_BE:
3102   case X86::COND_E:
3103   case X86::COND_P:
3104   case X86::COND_A:
3105   case X86::COND_AE:
3106   case X86::COND_NE:
3107   case X86::COND_NP:
3108     return true;
3109   }
3110 }
3111
3112 /// isFPImmLegal - Returns true if the target can instruction select the
3113 /// specified FP immediate natively. If false, the legalizer will
3114 /// materialize the FP immediate as a load from a constant pool.
3115 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3116   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3117     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3118       return true;
3119   }
3120   return false;
3121 }
3122
3123 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3124 /// the specified range (L, H].
3125 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3126   return (Val < 0) || (Val >= Low && Val < Hi);
3127 }
3128
3129 /// isUndefOrInRange - Return true if every element in Mask, begining
3130 /// from position Pos and ending in Pos+Size, falls within the specified
3131 /// range (L, L+Pos]. or is undef.
3132 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3133                              int Pos, int Size, int Low, int Hi) {
3134   for (int i = Pos, e = Pos+Size; i != e; ++i)
3135     if (!isUndefOrInRange(Mask[i], Low, Hi))
3136       return false;
3137   return true;
3138 }
3139
3140 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3141 /// specified value.
3142 static bool isUndefOrEqual(int Val, int CmpVal) {
3143   if (Val < 0 || Val == CmpVal)
3144     return true;
3145   return false;
3146 }
3147
3148 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3149 /// from position Pos and ending in Pos+Size, falls within the specified
3150 /// sequential range (L, L+Pos]. or is undef.
3151 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3152                                        int Pos, int Size, int Low) {
3153   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3154     if (!isUndefOrEqual(Mask[i], Low))
3155       return false;
3156   return true;
3157 }
3158
3159 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3160 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3161 /// the second operand.
3162 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3163   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3164     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3165   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3166     return (Mask[0] < 2 && Mask[1] < 2);
3167   return false;
3168 }
3169
3170 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3171   SmallVector<int, 8> M;
3172   N->getMask(M);
3173   return ::isPSHUFDMask(M, N->getValueType(0));
3174 }
3175
3176 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3177 /// is suitable for input to PSHUFHW.
3178 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3179   if (VT != MVT::v8i16)
3180     return false;
3181
3182   // Lower quadword copied in order or undef.
3183   for (int i = 0; i != 4; ++i)
3184     if (Mask[i] >= 0 && Mask[i] != i)
3185       return false;
3186
3187   // Upper quadword shuffled.
3188   for (int i = 4; i != 8; ++i)
3189     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3190       return false;
3191
3192   return true;
3193 }
3194
3195 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3196   SmallVector<int, 8> M;
3197   N->getMask(M);
3198   return ::isPSHUFHWMask(M, N->getValueType(0));
3199 }
3200
3201 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3202 /// is suitable for input to PSHUFLW.
3203 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3204   if (VT != MVT::v8i16)
3205     return false;
3206
3207   // Upper quadword copied in order.
3208   for (int i = 4; i != 8; ++i)
3209     if (Mask[i] >= 0 && Mask[i] != i)
3210       return false;
3211
3212   // Lower quadword shuffled.
3213   for (int i = 0; i != 4; ++i)
3214     if (Mask[i] >= 4)
3215       return false;
3216
3217   return true;
3218 }
3219
3220 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3221   SmallVector<int, 8> M;
3222   N->getMask(M);
3223   return ::isPSHUFLWMask(M, N->getValueType(0));
3224 }
3225
3226 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3227 /// is suitable for input to PALIGNR.
3228 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3229                           bool hasSSSE3OrAVX) {
3230   int i, e = VT.getVectorNumElements();
3231   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3232     return false;
3233
3234   // Do not handle v2i64 / v2f64 shuffles with palignr.
3235   if (e < 4 || !hasSSSE3OrAVX)
3236     return false;
3237
3238   for (i = 0; i != e; ++i)
3239     if (Mask[i] >= 0)
3240       break;
3241
3242   // All undef, not a palignr.
3243   if (i == e)
3244     return false;
3245
3246   // Make sure we're shifting in the right direction.
3247   if (Mask[i] <= i)
3248     return false;
3249
3250   int s = Mask[i] - i;
3251
3252   // Check the rest of the elements to see if they are consecutive.
3253   for (++i; i != e; ++i) {
3254     int m = Mask[i];
3255     if (m >= 0 && m != s+i)
3256       return false;
3257   }
3258   return true;
3259 }
3260
3261 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3262 /// specifies a shuffle of elements that is suitable for input to 256-bit
3263 /// VSHUFPSY.
3264 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3265                           const X86Subtarget *Subtarget) {
3266   int NumElems = VT.getVectorNumElements();
3267
3268   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3269     return false;
3270
3271   if (NumElems != 8)
3272     return false;
3273
3274   // VSHUFPSY divides the resulting vector into 4 chunks.
3275   // The sources are also splitted into 4 chunks, and each destination
3276   // chunk must come from a different source chunk.
3277   //
3278   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3279   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3280   //
3281   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3282   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3283   //
3284   int QuarterSize = NumElems/4;
3285   int HalfSize = QuarterSize*2;
3286   for (int i = 0; i < QuarterSize; ++i)
3287     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3288       return false;
3289   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3290     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3291       return false;
3292
3293   // The mask of the second half must be the same as the first but with
3294   // the appropriate offsets. This works in the same way as VPERMILPS
3295   // works with masks.
3296   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3297     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3298       return false;
3299     int FstHalfIdx = i-HalfSize;
3300     if (Mask[FstHalfIdx] < 0)
3301       continue;
3302     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3303       return false;
3304   }
3305   for (int i = QuarterSize*3; i < NumElems; ++i) {
3306     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3307       return false;
3308     int FstHalfIdx = i-HalfSize;
3309     if (Mask[FstHalfIdx] < 0)
3310       continue;
3311     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3312       return false;
3313
3314   }
3315
3316   return true;
3317 }
3318
3319 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3320 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3321 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3322   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3323   EVT VT = SVOp->getValueType(0);
3324   int NumElems = VT.getVectorNumElements();
3325
3326   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3327          "Only supports v8i32 and v8f32 types");
3328
3329   int HalfSize = NumElems/2;
3330   unsigned Mask = 0;
3331   for (int i = 0; i != NumElems ; ++i) {
3332     if (SVOp->getMaskElt(i) < 0)
3333       continue;
3334     // The mask of the first half must be equal to the second one.
3335     unsigned Shamt = (i%HalfSize)*2;
3336     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3337     Mask |= Elt << Shamt;
3338   }
3339
3340   return Mask;
3341 }
3342
3343 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3344 /// specifies a shuffle of elements that is suitable for input to 256-bit
3345 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3346 /// version and the mask of the second half isn't binded with the first
3347 /// one.
3348 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3349                            const X86Subtarget *Subtarget) {
3350   int NumElems = VT.getVectorNumElements();
3351
3352   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3353     return false;
3354
3355   if (NumElems != 4)
3356     return false;
3357
3358   // VSHUFPSY divides the resulting vector into 4 chunks.
3359   // The sources are also splitted into 4 chunks, and each destination
3360   // chunk must come from a different source chunk.
3361   //
3362   //  SRC1 =>      X3       X2       X1       X0
3363   //  SRC2 =>      Y3       Y2       Y1       Y0
3364   //
3365   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3366   //
3367   int QuarterSize = NumElems/4;
3368   int HalfSize = QuarterSize*2;
3369   for (int i = 0; i < QuarterSize; ++i)
3370     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3371       return false;
3372   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3373     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3374       return false;
3375   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3376     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3377       return false;
3378   for (int i = QuarterSize*3; i < NumElems; ++i)
3379     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3380       return false;
3381
3382   return true;
3383 }
3384
3385 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3386 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3387 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3388   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3389   EVT VT = SVOp->getValueType(0);
3390   int NumElems = VT.getVectorNumElements();
3391
3392   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3393          "Only supports v4i64 and v4f64 types");
3394
3395   int HalfSize = NumElems/2;
3396   unsigned Mask = 0;
3397   for (int i = 0; i != NumElems ; ++i) {
3398     if (SVOp->getMaskElt(i) < 0)
3399       continue;
3400     int Elt = SVOp->getMaskElt(i) % HalfSize;
3401     Mask |= Elt << i;
3402   }
3403
3404   return Mask;
3405 }
3406
3407 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3408 /// specifies a shuffle of elements that is suitable for input to 128-bit
3409 /// SHUFPS and SHUFPD.
3410 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3411   int NumElems = VT.getVectorNumElements();
3412
3413   if (VT.getSizeInBits() != 128)
3414     return false;
3415
3416   if (NumElems != 2 && NumElems != 4)
3417     return false;
3418
3419   int Half = NumElems / 2;
3420   for (int i = 0; i < Half; ++i)
3421     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3422       return false;
3423   for (int i = Half; i < NumElems; ++i)
3424     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3425       return false;
3426
3427   return true;
3428 }
3429
3430 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3431   SmallVector<int, 8> M;
3432   N->getMask(M);
3433   return ::isSHUFPMask(M, N->getValueType(0));
3434 }
3435
3436 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3437 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3438 /// half elements to come from vector 1 (which would equal the dest.) and
3439 /// the upper half to come from vector 2.
3440 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3441   int NumElems = VT.getVectorNumElements();
3442
3443   if (NumElems != 2 && NumElems != 4)
3444     return false;
3445
3446   int Half = NumElems / 2;
3447   for (int i = 0; i < Half; ++i)
3448     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3449       return false;
3450   for (int i = Half; i < NumElems; ++i)
3451     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3452       return false;
3453   return true;
3454 }
3455
3456 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3457   SmallVector<int, 8> M;
3458   N->getMask(M);
3459   return isCommutedSHUFPMask(M, N->getValueType(0));
3460 }
3461
3462 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3463 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3464 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3465   EVT VT = N->getValueType(0);
3466   unsigned NumElems = VT.getVectorNumElements();
3467
3468   if (VT.getSizeInBits() != 128)
3469     return false;
3470
3471   if (NumElems != 4)
3472     return false;
3473
3474   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3475   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3476          isUndefOrEqual(N->getMaskElt(1), 7) &&
3477          isUndefOrEqual(N->getMaskElt(2), 2) &&
3478          isUndefOrEqual(N->getMaskElt(3), 3);
3479 }
3480
3481 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3482 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3483 /// <2, 3, 2, 3>
3484 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3485   EVT VT = N->getValueType(0);
3486   unsigned NumElems = VT.getVectorNumElements();
3487
3488   if (VT.getSizeInBits() != 128)
3489     return false;
3490
3491   if (NumElems != 4)
3492     return false;
3493
3494   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3495          isUndefOrEqual(N->getMaskElt(1), 3) &&
3496          isUndefOrEqual(N->getMaskElt(2), 2) &&
3497          isUndefOrEqual(N->getMaskElt(3), 3);
3498 }
3499
3500 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3501 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3502 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3503   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3504
3505   if (NumElems != 2 && NumElems != 4)
3506     return false;
3507
3508   for (unsigned i = 0; i < NumElems/2; ++i)
3509     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3510       return false;
3511
3512   for (unsigned i = NumElems/2; i < NumElems; ++i)
3513     if (!isUndefOrEqual(N->getMaskElt(i), i))
3514       return false;
3515
3516   return true;
3517 }
3518
3519 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3520 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3521 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3522   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3523
3524   if ((NumElems != 2 && NumElems != 4)
3525       || N->getValueType(0).getSizeInBits() > 128)
3526     return false;
3527
3528   for (unsigned i = 0; i < NumElems/2; ++i)
3529     if (!isUndefOrEqual(N->getMaskElt(i), i))
3530       return false;
3531
3532   for (unsigned i = 0; i < NumElems/2; ++i)
3533     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3534       return false;
3535
3536   return true;
3537 }
3538
3539 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3540 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3541 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3542                          bool V2IsSplat = false) {
3543   int NumElts = VT.getVectorNumElements();
3544
3545   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3546          "Unsupported vector type for unpckh");
3547
3548   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3549     return false;
3550
3551   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3552   // independently on 128-bit lanes.
3553   unsigned NumLanes = VT.getSizeInBits()/128;
3554   unsigned NumLaneElts = NumElts/NumLanes;
3555
3556   unsigned Start = 0;
3557   unsigned End = NumLaneElts;
3558   for (unsigned s = 0; s < NumLanes; ++s) {
3559     for (unsigned i = Start, j = s * NumLaneElts;
3560          i != End;
3561          i += 2, ++j) {
3562       int BitI  = Mask[i];
3563       int BitI1 = Mask[i+1];
3564       if (!isUndefOrEqual(BitI, j))
3565         return false;
3566       if (V2IsSplat) {
3567         if (!isUndefOrEqual(BitI1, NumElts))
3568           return false;
3569       } else {
3570         if (!isUndefOrEqual(BitI1, j + NumElts))
3571           return false;
3572       }
3573     }
3574     // Process the next 128 bits.
3575     Start += NumLaneElts;
3576     End += NumLaneElts;
3577   }
3578
3579   return true;
3580 }
3581
3582 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3583   SmallVector<int, 8> M;
3584   N->getMask(M);
3585   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3586 }
3587
3588 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3590 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3591                          bool V2IsSplat = false) {
3592   int NumElts = VT.getVectorNumElements();
3593
3594   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3595          "Unsupported vector type for unpckh");
3596
3597   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3598     return false;
3599
3600   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3601   // independently on 128-bit lanes.
3602   unsigned NumLanes = VT.getSizeInBits()/128;
3603   unsigned NumLaneElts = NumElts/NumLanes;
3604
3605   unsigned Start = 0;
3606   unsigned End = NumLaneElts;
3607   for (unsigned l = 0; l != NumLanes; ++l) {
3608     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3609                              i != End; i += 2, ++j) {
3610       int BitI  = Mask[i];
3611       int BitI1 = Mask[i+1];
3612       if (!isUndefOrEqual(BitI, j))
3613         return false;
3614       if (V2IsSplat) {
3615         if (isUndefOrEqual(BitI1, NumElts))
3616           return false;
3617       } else {
3618         if (!isUndefOrEqual(BitI1, j+NumElts))
3619           return false;
3620       }
3621     }
3622     // Process the next 128 bits.
3623     Start += NumLaneElts;
3624     End += NumLaneElts;
3625   }
3626   return true;
3627 }
3628
3629 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3630   SmallVector<int, 8> M;
3631   N->getMask(M);
3632   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3633 }
3634
3635 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3636 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3637 /// <0, 0, 1, 1>
3638 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3639   int NumElems = VT.getVectorNumElements();
3640   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3641     return false;
3642
3643   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3644   // FIXME: Need a better way to get rid of this, there's no latency difference
3645   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3646   // the former later. We should also remove the "_undef" special mask.
3647   if (NumElems == 4 && VT.getSizeInBits() == 256)
3648     return false;
3649
3650   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3651   // independently on 128-bit lanes.
3652   unsigned NumLanes = VT.getSizeInBits() / 128;
3653   unsigned NumLaneElts = NumElems / NumLanes;
3654
3655   for (unsigned s = 0; s < NumLanes; ++s) {
3656     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3657          i != NumLaneElts * (s + 1);
3658          i += 2, ++j) {
3659       int BitI  = Mask[i];
3660       int BitI1 = Mask[i+1];
3661
3662       if (!isUndefOrEqual(BitI, j))
3663         return false;
3664       if (!isUndefOrEqual(BitI1, j))
3665         return false;
3666     }
3667   }
3668
3669   return true;
3670 }
3671
3672 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3673   SmallVector<int, 8> M;
3674   N->getMask(M);
3675   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3676 }
3677
3678 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3679 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3680 /// <2, 2, 3, 3>
3681 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3682   int NumElems = VT.getVectorNumElements();
3683   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3684     return false;
3685
3686   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3687     int BitI  = Mask[i];
3688     int BitI1 = Mask[i+1];
3689     if (!isUndefOrEqual(BitI, j))
3690       return false;
3691     if (!isUndefOrEqual(BitI1, j))
3692       return false;
3693   }
3694   return true;
3695 }
3696
3697 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3698   SmallVector<int, 8> M;
3699   N->getMask(M);
3700   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3701 }
3702
3703 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3704 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3705 /// MOVSD, and MOVD, i.e. setting the lowest element.
3706 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3707   if (VT.getVectorElementType().getSizeInBits() < 32)
3708     return false;
3709
3710   int NumElts = VT.getVectorNumElements();
3711
3712   if (!isUndefOrEqual(Mask[0], NumElts))
3713     return false;
3714
3715   for (int i = 1; i < NumElts; ++i)
3716     if (!isUndefOrEqual(Mask[i], i))
3717       return false;
3718
3719   return true;
3720 }
3721
3722 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3723   SmallVector<int, 8> M;
3724   N->getMask(M);
3725   return ::isMOVLMask(M, N->getValueType(0));
3726 }
3727
3728 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3729 /// as permutations between 128-bit chunks or halves. As an example: this
3730 /// shuffle bellow:
3731 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3732 /// The first half comes from the second half of V1 and the second half from the
3733 /// the second half of V2.
3734 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3735                              const X86Subtarget *Subtarget) {
3736   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3737     return false;
3738
3739   // The shuffle result is divided into half A and half B. In total the two
3740   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3741   // B must come from C, D, E or F.
3742   int HalfSize = VT.getVectorNumElements()/2;
3743   bool MatchA = false, MatchB = false;
3744
3745   // Check if A comes from one of C, D, E, F.
3746   for (int Half = 0; Half < 4; ++Half) {
3747     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3748       MatchA = true;
3749       break;
3750     }
3751   }
3752
3753   // Check if B comes from one of C, D, E, F.
3754   for (int Half = 0; Half < 4; ++Half) {
3755     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3756       MatchB = true;
3757       break;
3758     }
3759   }
3760
3761   return MatchA && MatchB;
3762 }
3763
3764 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3765 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3766 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3767   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3768   EVT VT = SVOp->getValueType(0);
3769
3770   int HalfSize = VT.getVectorNumElements()/2;
3771
3772   int FstHalf = 0, SndHalf = 0;
3773   for (int i = 0; i < HalfSize; ++i) {
3774     if (SVOp->getMaskElt(i) > 0) {
3775       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3776       break;
3777     }
3778   }
3779   for (int i = HalfSize; i < HalfSize*2; ++i) {
3780     if (SVOp->getMaskElt(i) > 0) {
3781       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3782       break;
3783     }
3784   }
3785
3786   return (FstHalf | (SndHalf << 4));
3787 }
3788
3789 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3790 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3791 /// Note that VPERMIL mask matching is different depending whether theunderlying
3792 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3793 /// to the same elements of the low, but to the higher half of the source.
3794 /// In VPERMILPD the two lanes could be shuffled independently of each other
3795 /// with the same restriction that lanes can't be crossed.
3796 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3797                             const X86Subtarget *Subtarget) {
3798   int NumElts = VT.getVectorNumElements();
3799   int NumLanes = VT.getSizeInBits()/128;
3800
3801   if (!Subtarget->hasAVX())
3802     return false;
3803
3804   // Only match 256-bit with 64-bit types
3805   if (VT.getSizeInBits() != 256 || NumElts != 4)
3806     return false;
3807
3808   // The mask on the high lane is independent of the low. Both can match
3809   // any element in inside its own lane, but can't cross.
3810   int LaneSize = NumElts/NumLanes;
3811   for (int l = 0; l < NumLanes; ++l)
3812     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3813       int LaneStart = l*LaneSize;
3814       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3815         return false;
3816     }
3817
3818   return true;
3819 }
3820
3821 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3822 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3823 /// Note that VPERMIL mask matching is different depending whether theunderlying
3824 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3825 /// to the same elements of the low, but to the higher half of the source.
3826 /// In VPERMILPD the two lanes could be shuffled independently of each other
3827 /// with the same restriction that lanes can't be crossed.
3828 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3829                             const X86Subtarget *Subtarget) {
3830   unsigned NumElts = VT.getVectorNumElements();
3831   unsigned NumLanes = VT.getSizeInBits()/128;
3832
3833   if (!Subtarget->hasAVX())
3834     return false;
3835
3836   // Only match 256-bit with 32-bit types
3837   if (VT.getSizeInBits() != 256 || NumElts != 8)
3838     return false;
3839
3840   // The mask on the high lane should be the same as the low. Actually,
3841   // they can differ if any of the corresponding index in a lane is undef
3842   // and the other stays in range.
3843   int LaneSize = NumElts/NumLanes;
3844   for (int i = 0; i < LaneSize; ++i) {
3845     int HighElt = i+LaneSize;
3846     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3847     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3848
3849     if (!HighValid || !LowValid)
3850       return false;
3851     if (Mask[i] < 0 || Mask[HighElt] < 0)
3852       continue;
3853     if (Mask[HighElt]-Mask[i] != LaneSize)
3854       return false;
3855   }
3856
3857   return true;
3858 }
3859
3860 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3861 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3862 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3863   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3864   EVT VT = SVOp->getValueType(0);
3865
3866   int NumElts = VT.getVectorNumElements();
3867   int NumLanes = VT.getSizeInBits()/128;
3868   int LaneSize = NumElts/NumLanes;
3869
3870   // Although the mask is equal for both lanes do it twice to get the cases
3871   // where a mask will match because the same mask element is undef on the
3872   // first half but valid on the second. This would get pathological cases
3873   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3874   unsigned Mask = 0;
3875   for (int l = 0; l < NumLanes; ++l) {
3876     for (int i = 0; i < LaneSize; ++i) {
3877       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3878       if (MaskElt < 0)
3879         continue;
3880       if (MaskElt >= LaneSize)
3881         MaskElt -= LaneSize;
3882       Mask |= MaskElt << (i*2);
3883     }
3884   }
3885
3886   return Mask;
3887 }
3888
3889 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3890 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3891 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3893   EVT VT = SVOp->getValueType(0);
3894
3895   int NumElts = VT.getVectorNumElements();
3896   int NumLanes = VT.getSizeInBits()/128;
3897
3898   unsigned Mask = 0;
3899   int LaneSize = NumElts/NumLanes;
3900   for (int l = 0; l < NumLanes; ++l)
3901     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3902       int MaskElt = SVOp->getMaskElt(i);
3903       if (MaskElt < 0)
3904         continue;
3905       Mask |= (MaskElt-l*LaneSize) << i;
3906     }
3907
3908   return Mask;
3909 }
3910
3911 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3912 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3913 /// element of vector 2 and the other elements to come from vector 1 in order.
3914 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3915                                bool V2IsSplat = false, bool V2IsUndef = false) {
3916   int NumOps = VT.getVectorNumElements();
3917   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3918     return false;
3919
3920   if (!isUndefOrEqual(Mask[0], 0))
3921     return false;
3922
3923   for (int i = 1; i < NumOps; ++i)
3924     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3925           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3926           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3927       return false;
3928
3929   return true;
3930 }
3931
3932 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3933                            bool V2IsUndef = false) {
3934   SmallVector<int, 8> M;
3935   N->getMask(M);
3936   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3937 }
3938
3939 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3940 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3941 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3942 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3943                          const X86Subtarget *Subtarget) {
3944   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3945     return false;
3946
3947   // The second vector must be undef
3948   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3949     return false;
3950
3951   EVT VT = N->getValueType(0);
3952   unsigned NumElems = VT.getVectorNumElements();
3953
3954   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3955       (VT.getSizeInBits() == 256 && NumElems != 8))
3956     return false;
3957
3958   // "i+1" is the value the indexed mask element must have
3959   for (unsigned i = 0; i < NumElems; i += 2)
3960     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3961         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3962       return false;
3963
3964   return true;
3965 }
3966
3967 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3968 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3969 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3970 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3971                          const X86Subtarget *Subtarget) {
3972   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3973     return false;
3974
3975   // The second vector must be undef
3976   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3977     return false;
3978
3979   EVT VT = N->getValueType(0);
3980   unsigned NumElems = VT.getVectorNumElements();
3981
3982   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3983       (VT.getSizeInBits() == 256 && NumElems != 8))
3984     return false;
3985
3986   // "i" is the value the indexed mask element must have
3987   for (unsigned i = 0; i < NumElems; i += 2)
3988     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3989         !isUndefOrEqual(N->getMaskElt(i+1), i))
3990       return false;
3991
3992   return true;
3993 }
3994
3995 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3996 /// specifies a shuffle of elements that is suitable for input to 256-bit
3997 /// version of MOVDDUP.
3998 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3999                            const X86Subtarget *Subtarget) {
4000   EVT VT = N->getValueType(0);
4001   int NumElts = VT.getVectorNumElements();
4002   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4003
4004   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4005       !V2IsUndef || NumElts != 4)
4006     return false;
4007
4008   for (int i = 0; i != NumElts/2; ++i)
4009     if (!isUndefOrEqual(N->getMaskElt(i), 0))
4010       return false;
4011   for (int i = NumElts/2; i != NumElts; ++i)
4012     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4013       return false;
4014   return true;
4015 }
4016
4017 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to 128-bit
4019 /// version of MOVDDUP.
4020 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4021   EVT VT = N->getValueType(0);
4022
4023   if (VT.getSizeInBits() != 128)
4024     return false;
4025
4026   int e = VT.getVectorNumElements() / 2;
4027   for (int i = 0; i < e; ++i)
4028     if (!isUndefOrEqual(N->getMaskElt(i), i))
4029       return false;
4030   for (int i = 0; i < e; ++i)
4031     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4032       return false;
4033   return true;
4034 }
4035
4036 /// isVEXTRACTF128Index - Return true if the specified
4037 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4038 /// suitable for input to VEXTRACTF128.
4039 bool X86::isVEXTRACTF128Index(SDNode *N) {
4040   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4041     return false;
4042
4043   // The index should be aligned on a 128-bit boundary.
4044   uint64_t Index =
4045     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4046
4047   unsigned VL = N->getValueType(0).getVectorNumElements();
4048   unsigned VBits = N->getValueType(0).getSizeInBits();
4049   unsigned ElSize = VBits / VL;
4050   bool Result = (Index * ElSize) % 128 == 0;
4051
4052   return Result;
4053 }
4054
4055 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4056 /// operand specifies a subvector insert that is suitable for input to
4057 /// VINSERTF128.
4058 bool X86::isVINSERTF128Index(SDNode *N) {
4059   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4060     return false;
4061
4062   // The index should be aligned on a 128-bit boundary.
4063   uint64_t Index =
4064     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4065
4066   unsigned VL = N->getValueType(0).getVectorNumElements();
4067   unsigned VBits = N->getValueType(0).getSizeInBits();
4068   unsigned ElSize = VBits / VL;
4069   bool Result = (Index * ElSize) % 128 == 0;
4070
4071   return Result;
4072 }
4073
4074 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4075 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4076 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4077   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4078   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4079
4080   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4081   unsigned Mask = 0;
4082   for (int i = 0; i < NumOperands; ++i) {
4083     int Val = SVOp->getMaskElt(NumOperands-i-1);
4084     if (Val < 0) Val = 0;
4085     if (Val >= NumOperands) Val -= NumOperands;
4086     Mask |= Val;
4087     if (i != NumOperands - 1)
4088       Mask <<= Shift;
4089   }
4090   return Mask;
4091 }
4092
4093 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4094 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4095 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4097   unsigned Mask = 0;
4098   // 8 nodes, but we only care about the last 4.
4099   for (unsigned i = 7; i >= 4; --i) {
4100     int Val = SVOp->getMaskElt(i);
4101     if (Val >= 0)
4102       Mask |= (Val - 4);
4103     if (i != 4)
4104       Mask <<= 2;
4105   }
4106   return Mask;
4107 }
4108
4109 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4110 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4111 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4112   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4113   unsigned Mask = 0;
4114   // 8 nodes, but we only care about the first 4.
4115   for (int i = 3; i >= 0; --i) {
4116     int Val = SVOp->getMaskElt(i);
4117     if (Val >= 0)
4118       Mask |= Val;
4119     if (i != 0)
4120       Mask <<= 2;
4121   }
4122   return Mask;
4123 }
4124
4125 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4126 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4127 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4128   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4129   EVT VVT = N->getValueType(0);
4130   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4131   int Val = 0;
4132
4133   unsigned i, e;
4134   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4135     Val = SVOp->getMaskElt(i);
4136     if (Val >= 0)
4137       break;
4138   }
4139   assert(Val - i > 0 && "PALIGNR imm should be positive");
4140   return (Val - i) * EltSize;
4141 }
4142
4143 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4144 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4145 /// instructions.
4146 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4147   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4148     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4149
4150   uint64_t Index =
4151     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4152
4153   EVT VecVT = N->getOperand(0).getValueType();
4154   EVT ElVT = VecVT.getVectorElementType();
4155
4156   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4157   return Index / NumElemsPerChunk;
4158 }
4159
4160 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4161 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4162 /// instructions.
4163 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4164   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4165     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4166
4167   uint64_t Index =
4168     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4169
4170   EVT VecVT = N->getValueType(0);
4171   EVT ElVT = VecVT.getVectorElementType();
4172
4173   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4174   return Index / NumElemsPerChunk;
4175 }
4176
4177 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4178 /// constant +0.0.
4179 bool X86::isZeroNode(SDValue Elt) {
4180   return ((isa<ConstantSDNode>(Elt) &&
4181            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4182           (isa<ConstantFPSDNode>(Elt) &&
4183            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4184 }
4185
4186 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4187 /// their permute mask.
4188 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4189                                     SelectionDAG &DAG) {
4190   EVT VT = SVOp->getValueType(0);
4191   unsigned NumElems = VT.getVectorNumElements();
4192   SmallVector<int, 8> MaskVec;
4193
4194   for (unsigned i = 0; i != NumElems; ++i) {
4195     int idx = SVOp->getMaskElt(i);
4196     if (idx < 0)
4197       MaskVec.push_back(idx);
4198     else if (idx < (int)NumElems)
4199       MaskVec.push_back(idx + NumElems);
4200     else
4201       MaskVec.push_back(idx - NumElems);
4202   }
4203   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4204                               SVOp->getOperand(0), &MaskVec[0]);
4205 }
4206
4207 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4208 /// the two vector operands have swapped position.
4209 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4210   unsigned NumElems = VT.getVectorNumElements();
4211   for (unsigned i = 0; i != NumElems; ++i) {
4212     int idx = Mask[i];
4213     if (idx < 0)
4214       continue;
4215     else if (idx < (int)NumElems)
4216       Mask[i] = idx + NumElems;
4217     else
4218       Mask[i] = idx - NumElems;
4219   }
4220 }
4221
4222 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4223 /// match movhlps. The lower half elements should come from upper half of
4224 /// V1 (and in order), and the upper half elements should come from the upper
4225 /// half of V2 (and in order).
4226 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4227   EVT VT = Op->getValueType(0);
4228   if (VT.getSizeInBits() != 128)
4229     return false;
4230   if (VT.getVectorNumElements() != 4)
4231     return false;
4232   for (unsigned i = 0, e = 2; i != e; ++i)
4233     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4234       return false;
4235   for (unsigned i = 2; i != 4; ++i)
4236     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4237       return false;
4238   return true;
4239 }
4240
4241 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4242 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4243 /// required.
4244 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4245   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4246     return false;
4247   N = N->getOperand(0).getNode();
4248   if (!ISD::isNON_EXTLoad(N))
4249     return false;
4250   if (LD)
4251     *LD = cast<LoadSDNode>(N);
4252   return true;
4253 }
4254
4255 // Test whether the given value is a vector value which will be legalized
4256 // into a load.
4257 static bool WillBeConstantPoolLoad(SDNode *N) {
4258   if (N->getOpcode() != ISD::BUILD_VECTOR)
4259     return false;
4260
4261   // Check for any non-constant elements.
4262   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4263     switch (N->getOperand(i).getNode()->getOpcode()) {
4264     case ISD::UNDEF:
4265     case ISD::ConstantFP:
4266     case ISD::Constant:
4267       break;
4268     default:
4269       return false;
4270     }
4271
4272   // Vectors of all-zeros and all-ones are materialized with special
4273   // instructions rather than being loaded.
4274   return !ISD::isBuildVectorAllZeros(N) &&
4275          !ISD::isBuildVectorAllOnes(N);
4276 }
4277
4278 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4279 /// match movlp{s|d}. The lower half elements should come from lower half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order). And since V1 will become the source of the
4282 /// MOVLP, it must be either a vector load or a scalar load to vector.
4283 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4284                                ShuffleVectorSDNode *Op) {
4285   EVT VT = Op->getValueType(0);
4286   if (VT.getSizeInBits() != 128)
4287     return false;
4288
4289   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4290     return false;
4291   // Is V2 is a vector load, don't do this transformation. We will try to use
4292   // load folding shufps op.
4293   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4294     return false;
4295
4296   unsigned NumElems = VT.getVectorNumElements();
4297
4298   if (NumElems != 2 && NumElems != 4)
4299     return false;
4300   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4301     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4302       return false;
4303   for (unsigned i = NumElems/2; i != NumElems; ++i)
4304     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4305       return false;
4306   return true;
4307 }
4308
4309 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4310 /// all the same.
4311 static bool isSplatVector(SDNode *N) {
4312   if (N->getOpcode() != ISD::BUILD_VECTOR)
4313     return false;
4314
4315   SDValue SplatValue = N->getOperand(0);
4316   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4317     if (N->getOperand(i) != SplatValue)
4318       return false;
4319   return true;
4320 }
4321
4322 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4323 /// to an zero vector.
4324 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4325 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4326   SDValue V1 = N->getOperand(0);
4327   SDValue V2 = N->getOperand(1);
4328   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4329   for (unsigned i = 0; i != NumElems; ++i) {
4330     int Idx = N->getMaskElt(i);
4331     if (Idx >= (int)NumElems) {
4332       unsigned Opc = V2.getOpcode();
4333       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4334         continue;
4335       if (Opc != ISD::BUILD_VECTOR ||
4336           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4337         return false;
4338     } else if (Idx >= 0) {
4339       unsigned Opc = V1.getOpcode();
4340       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4341         continue;
4342       if (Opc != ISD::BUILD_VECTOR ||
4343           !X86::isZeroNode(V1.getOperand(Idx)))
4344         return false;
4345     }
4346   }
4347   return true;
4348 }
4349
4350 /// getZeroVector - Returns a vector of specified type with all zero elements.
4351 ///
4352 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4353                              DebugLoc dl) {
4354   assert(VT.isVector() && "Expected a vector type");
4355
4356   // Always build SSE zero vectors as <4 x i32> bitcasted
4357   // to their dest type. This ensures they get CSE'd.
4358   SDValue Vec;
4359   if (VT.getSizeInBits() == 128) {  // SSE
4360     if (HasXMMInt) {  // SSE2
4361       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4363     } else { // SSE1
4364       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4365       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4366     }
4367   } else if (VT.getSizeInBits() == 256) { // AVX
4368     // 256-bit logic and arithmetic instructions in AVX are
4369     // all floating-point, no support for integer ops. Default
4370     // to emitting fp zeroed vectors then.
4371     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4372     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4373     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4374   }
4375   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4376 }
4377
4378 /// getOnesVector - Returns a vector of specified type with all bits set.
4379 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4380 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4381 /// original type, ensuring they get CSE'd.
4382 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4383   assert(VT.isVector() && "Expected a vector type");
4384   assert((VT.is128BitVector() || VT.is256BitVector())
4385          && "Expected a 128-bit or 256-bit vector type");
4386
4387   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4388   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4389                             Cst, Cst, Cst, Cst);
4390
4391   if (VT.is256BitVector()) {
4392     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4393                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4394     Vec = Insert128BitVector(InsV, Vec,
4395                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4396   }
4397
4398   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4399 }
4400
4401 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4402 /// that point to V2 points to its first element.
4403 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4404   EVT VT = SVOp->getValueType(0);
4405   unsigned NumElems = VT.getVectorNumElements();
4406
4407   bool Changed = false;
4408   SmallVector<int, 8> MaskVec;
4409   SVOp->getMask(MaskVec);
4410
4411   for (unsigned i = 0; i != NumElems; ++i) {
4412     if (MaskVec[i] > (int)NumElems) {
4413       MaskVec[i] = NumElems;
4414       Changed = true;
4415     }
4416   }
4417   if (Changed)
4418     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4419                                 SVOp->getOperand(1), &MaskVec[0]);
4420   return SDValue(SVOp, 0);
4421 }
4422
4423 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4424 /// operation of specified width.
4425 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4426                        SDValue V2) {
4427   unsigned NumElems = VT.getVectorNumElements();
4428   SmallVector<int, 8> Mask;
4429   Mask.push_back(NumElems);
4430   for (unsigned i = 1; i != NumElems; ++i)
4431     Mask.push_back(i);
4432   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4433 }
4434
4435 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4436 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4437                           SDValue V2) {
4438   unsigned NumElems = VT.getVectorNumElements();
4439   SmallVector<int, 8> Mask;
4440   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4441     Mask.push_back(i);
4442     Mask.push_back(i + NumElems);
4443   }
4444   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4445 }
4446
4447 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4448 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4449                           SDValue V2) {
4450   unsigned NumElems = VT.getVectorNumElements();
4451   unsigned Half = NumElems/2;
4452   SmallVector<int, 8> Mask;
4453   for (unsigned i = 0; i != Half; ++i) {
4454     Mask.push_back(i + Half);
4455     Mask.push_back(i + NumElems + Half);
4456   }
4457   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4458 }
4459
4460 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4461 // a generic shuffle instruction because the target has no such instructions.
4462 // Generate shuffles which repeat i16 and i8 several times until they can be
4463 // represented by v4f32 and then be manipulated by target suported shuffles.
4464 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4465   EVT VT = V.getValueType();
4466   int NumElems = VT.getVectorNumElements();
4467   DebugLoc dl = V.getDebugLoc();
4468
4469   while (NumElems > 4) {
4470     if (EltNo < NumElems/2) {
4471       V = getUnpackl(DAG, dl, VT, V, V);
4472     } else {
4473       V = getUnpackh(DAG, dl, VT, V, V);
4474       EltNo -= NumElems/2;
4475     }
4476     NumElems >>= 1;
4477   }
4478   return V;
4479 }
4480
4481 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4482 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4483   EVT VT = V.getValueType();
4484   DebugLoc dl = V.getDebugLoc();
4485   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4486          && "Vector size not supported");
4487
4488   if (VT.getSizeInBits() == 128) {
4489     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4490     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4491     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4492                              &SplatMask[0]);
4493   } else {
4494     // To use VPERMILPS to splat scalars, the second half of indicies must
4495     // refer to the higher part, which is a duplication of the lower one,
4496     // because VPERMILPS can only handle in-lane permutations.
4497     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4498                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4499
4500     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4501     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4502                              &SplatMask[0]);
4503   }
4504
4505   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4506 }
4507
4508 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4509 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4510   EVT SrcVT = SV->getValueType(0);
4511   SDValue V1 = SV->getOperand(0);
4512   DebugLoc dl = SV->getDebugLoc();
4513
4514   int EltNo = SV->getSplatIndex();
4515   int NumElems = SrcVT.getVectorNumElements();
4516   unsigned Size = SrcVT.getSizeInBits();
4517
4518   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4519           "Unknown how to promote splat for type");
4520
4521   // Extract the 128-bit part containing the splat element and update
4522   // the splat element index when it refers to the higher register.
4523   if (Size == 256) {
4524     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4525     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4526     if (Idx > 0)
4527       EltNo -= NumElems/2;
4528   }
4529
4530   // All i16 and i8 vector types can't be used directly by a generic shuffle
4531   // instruction because the target has no such instruction. Generate shuffles
4532   // which repeat i16 and i8 several times until they fit in i32, and then can
4533   // be manipulated by target suported shuffles.
4534   EVT EltVT = SrcVT.getVectorElementType();
4535   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4536     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4537
4538   // Recreate the 256-bit vector and place the same 128-bit vector
4539   // into the low and high part. This is necessary because we want
4540   // to use VPERM* to shuffle the vectors
4541   if (Size == 256) {
4542     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4543                          DAG.getConstant(0, MVT::i32), DAG, dl);
4544     V1 = Insert128BitVector(InsV, V1,
4545                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4546   }
4547
4548   return getLegalSplat(DAG, V1, EltNo);
4549 }
4550
4551 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4552 /// vector of zero or undef vector.  This produces a shuffle where the low
4553 /// element of V2 is swizzled into the zero/undef vector, landing at element
4554 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4555 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4556                                            bool isZero, bool HasXMMInt,
4557                                            SelectionDAG &DAG) {
4558   EVT VT = V2.getValueType();
4559   SDValue V1 = isZero
4560     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4561   unsigned NumElems = VT.getVectorNumElements();
4562   SmallVector<int, 16> MaskVec;
4563   for (unsigned i = 0; i != NumElems; ++i)
4564     // If this is the insertion idx, put the low elt of V2 here.
4565     MaskVec.push_back(i == Idx ? NumElems : i);
4566   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4567 }
4568
4569 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4570 /// element of the result of the vector shuffle.
4571 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4572                                    unsigned Depth) {
4573   if (Depth == 6)
4574     return SDValue();  // Limit search depth.
4575
4576   SDValue V = SDValue(N, 0);
4577   EVT VT = V.getValueType();
4578   unsigned Opcode = V.getOpcode();
4579
4580   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4581   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4582     Index = SV->getMaskElt(Index);
4583
4584     if (Index < 0)
4585       return DAG.getUNDEF(VT.getVectorElementType());
4586
4587     int NumElems = VT.getVectorNumElements();
4588     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4589     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4590   }
4591
4592   // Recurse into target specific vector shuffles to find scalars.
4593   if (isTargetShuffle(Opcode)) {
4594     int NumElems = VT.getVectorNumElements();
4595     SmallVector<unsigned, 16> ShuffleMask;
4596     SDValue ImmN;
4597
4598     switch(Opcode) {
4599     case X86ISD::SHUFPS:
4600     case X86ISD::SHUFPD:
4601       ImmN = N->getOperand(N->getNumOperands()-1);
4602       DecodeSHUFPSMask(NumElems,
4603                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4604                        ShuffleMask);
4605       break;
4606     case X86ISD::PUNPCKHBW:
4607     case X86ISD::PUNPCKHWD:
4608     case X86ISD::PUNPCKHDQ:
4609     case X86ISD::PUNPCKHQDQ:
4610       DecodePUNPCKHMask(NumElems, ShuffleMask);
4611       break;
4612     case X86ISD::UNPCKHPS:
4613     case X86ISD::UNPCKHPD:
4614     case X86ISD::VUNPCKHPSY:
4615     case X86ISD::VUNPCKHPDY:
4616       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4617       break;
4618     case X86ISD::PUNPCKLBW:
4619     case X86ISD::PUNPCKLWD:
4620     case X86ISD::PUNPCKLDQ:
4621     case X86ISD::PUNPCKLQDQ:
4622       DecodePUNPCKLMask(VT, ShuffleMask);
4623       break;
4624     case X86ISD::UNPCKLPS:
4625     case X86ISD::UNPCKLPD:
4626     case X86ISD::VUNPCKLPSY:
4627     case X86ISD::VUNPCKLPDY:
4628       DecodeUNPCKLPMask(VT, ShuffleMask);
4629       break;
4630     case X86ISD::MOVHLPS:
4631       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4632       break;
4633     case X86ISD::MOVLHPS:
4634       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4635       break;
4636     case X86ISD::PSHUFD:
4637       ImmN = N->getOperand(N->getNumOperands()-1);
4638       DecodePSHUFMask(NumElems,
4639                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4640                       ShuffleMask);
4641       break;
4642     case X86ISD::PSHUFHW:
4643       ImmN = N->getOperand(N->getNumOperands()-1);
4644       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4645                         ShuffleMask);
4646       break;
4647     case X86ISD::PSHUFLW:
4648       ImmN = N->getOperand(N->getNumOperands()-1);
4649       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4650                         ShuffleMask);
4651       break;
4652     case X86ISD::MOVSS:
4653     case X86ISD::MOVSD: {
4654       // The index 0 always comes from the first element of the second source,
4655       // this is why MOVSS and MOVSD are used in the first place. The other
4656       // elements come from the other positions of the first source vector.
4657       unsigned OpNum = (Index == 0) ? 1 : 0;
4658       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4659                                  Depth+1);
4660     }
4661     case X86ISD::VPERMILPS:
4662       ImmN = N->getOperand(N->getNumOperands()-1);
4663       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4664                         ShuffleMask);
4665       break;
4666     case X86ISD::VPERMILPSY:
4667       ImmN = N->getOperand(N->getNumOperands()-1);
4668       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4669                         ShuffleMask);
4670       break;
4671     case X86ISD::VPERMILPD:
4672       ImmN = N->getOperand(N->getNumOperands()-1);
4673       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4674                         ShuffleMask);
4675       break;
4676     case X86ISD::VPERMILPDY:
4677       ImmN = N->getOperand(N->getNumOperands()-1);
4678       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4679                         ShuffleMask);
4680       break;
4681     case X86ISD::VPERM2F128:
4682       ImmN = N->getOperand(N->getNumOperands()-1);
4683       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4684                            ShuffleMask);
4685       break;
4686     case X86ISD::MOVDDUP:
4687     case X86ISD::MOVLHPD:
4688     case X86ISD::MOVLPD:
4689     case X86ISD::MOVLPS:
4690     case X86ISD::MOVSHDUP:
4691     case X86ISD::MOVSLDUP:
4692     case X86ISD::PALIGN:
4693       return SDValue(); // Not yet implemented.
4694     default:
4695       assert(0 && "unknown target shuffle node");
4696       return SDValue();
4697     }
4698
4699     Index = ShuffleMask[Index];
4700     if (Index < 0)
4701       return DAG.getUNDEF(VT.getVectorElementType());
4702
4703     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4704     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4705                                Depth+1);
4706   }
4707
4708   // Actual nodes that may contain scalar elements
4709   if (Opcode == ISD::BITCAST) {
4710     V = V.getOperand(0);
4711     EVT SrcVT = V.getValueType();
4712     unsigned NumElems = VT.getVectorNumElements();
4713
4714     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4715       return SDValue();
4716   }
4717
4718   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4719     return (Index == 0) ? V.getOperand(0)
4720                           : DAG.getUNDEF(VT.getVectorElementType());
4721
4722   if (V.getOpcode() == ISD::BUILD_VECTOR)
4723     return V.getOperand(Index);
4724
4725   return SDValue();
4726 }
4727
4728 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4729 /// shuffle operation which come from a consecutively from a zero. The
4730 /// search can start in two different directions, from left or right.
4731 static
4732 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4733                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4734   int i = 0;
4735
4736   while (i < NumElems) {
4737     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4738     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4739     if (!(Elt.getNode() &&
4740          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4741       break;
4742     ++i;
4743   }
4744
4745   return i;
4746 }
4747
4748 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4749 /// MaskE correspond consecutively to elements from one of the vector operands,
4750 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4751 static
4752 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4753                               int OpIdx, int NumElems, unsigned &OpNum) {
4754   bool SeenV1 = false;
4755   bool SeenV2 = false;
4756
4757   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4758     int Idx = SVOp->getMaskElt(i);
4759     // Ignore undef indicies
4760     if (Idx < 0)
4761       continue;
4762
4763     if (Idx < NumElems)
4764       SeenV1 = true;
4765     else
4766       SeenV2 = true;
4767
4768     // Only accept consecutive elements from the same vector
4769     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4770       return false;
4771   }
4772
4773   OpNum = SeenV1 ? 0 : 1;
4774   return true;
4775 }
4776
4777 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4778 /// logical left shift of a vector.
4779 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4780                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4781   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4782   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4783               false /* check zeros from right */, DAG);
4784   unsigned OpSrc;
4785
4786   if (!NumZeros)
4787     return false;
4788
4789   // Considering the elements in the mask that are not consecutive zeros,
4790   // check if they consecutively come from only one of the source vectors.
4791   //
4792   //               V1 = {X, A, B, C}     0
4793   //                         \  \  \    /
4794   //   vector_shuffle V1, V2 <1, 2, 3, X>
4795   //
4796   if (!isShuffleMaskConsecutive(SVOp,
4797             0,                   // Mask Start Index
4798             NumElems-NumZeros-1, // Mask End Index
4799             NumZeros,            // Where to start looking in the src vector
4800             NumElems,            // Number of elements in vector
4801             OpSrc))              // Which source operand ?
4802     return false;
4803
4804   isLeft = false;
4805   ShAmt = NumZeros;
4806   ShVal = SVOp->getOperand(OpSrc);
4807   return true;
4808 }
4809
4810 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4811 /// logical left shift of a vector.
4812 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4813                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4814   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4815   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4816               true /* check zeros from left */, DAG);
4817   unsigned OpSrc;
4818
4819   if (!NumZeros)
4820     return false;
4821
4822   // Considering the elements in the mask that are not consecutive zeros,
4823   // check if they consecutively come from only one of the source vectors.
4824   //
4825   //                           0    { A, B, X, X } = V2
4826   //                          / \    /  /
4827   //   vector_shuffle V1, V2 <X, X, 4, 5>
4828   //
4829   if (!isShuffleMaskConsecutive(SVOp,
4830             NumZeros,     // Mask Start Index
4831             NumElems-1,   // Mask End Index
4832             0,            // Where to start looking in the src vector
4833             NumElems,     // Number of elements in vector
4834             OpSrc))       // Which source operand ?
4835     return false;
4836
4837   isLeft = true;
4838   ShAmt = NumZeros;
4839   ShVal = SVOp->getOperand(OpSrc);
4840   return true;
4841 }
4842
4843 /// isVectorShift - Returns true if the shuffle can be implemented as a
4844 /// logical left or right shift of a vector.
4845 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4846                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4847   // Although the logic below support any bitwidth size, there are no
4848   // shift instructions which handle more than 128-bit vectors.
4849   if (SVOp->getValueType(0).getSizeInBits() > 128)
4850     return false;
4851
4852   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4853       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4854     return true;
4855
4856   return false;
4857 }
4858
4859 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4860 ///
4861 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4862                                        unsigned NumNonZero, unsigned NumZero,
4863                                        SelectionDAG &DAG,
4864                                        const TargetLowering &TLI) {
4865   if (NumNonZero > 8)
4866     return SDValue();
4867
4868   DebugLoc dl = Op.getDebugLoc();
4869   SDValue V(0, 0);
4870   bool First = true;
4871   for (unsigned i = 0; i < 16; ++i) {
4872     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4873     if (ThisIsNonZero && First) {
4874       if (NumZero)
4875         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4876       else
4877         V = DAG.getUNDEF(MVT::v8i16);
4878       First = false;
4879     }
4880
4881     if ((i & 1) != 0) {
4882       SDValue ThisElt(0, 0), LastElt(0, 0);
4883       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4884       if (LastIsNonZero) {
4885         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4886                               MVT::i16, Op.getOperand(i-1));
4887       }
4888       if (ThisIsNonZero) {
4889         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4890         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4891                               ThisElt, DAG.getConstant(8, MVT::i8));
4892         if (LastIsNonZero)
4893           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4894       } else
4895         ThisElt = LastElt;
4896
4897       if (ThisElt.getNode())
4898         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4899                         DAG.getIntPtrConstant(i/2));
4900     }
4901   }
4902
4903   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4904 }
4905
4906 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4907 ///
4908 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4909                                      unsigned NumNonZero, unsigned NumZero,
4910                                      SelectionDAG &DAG,
4911                                      const TargetLowering &TLI) {
4912   if (NumNonZero > 4)
4913     return SDValue();
4914
4915   DebugLoc dl = Op.getDebugLoc();
4916   SDValue V(0, 0);
4917   bool First = true;
4918   for (unsigned i = 0; i < 8; ++i) {
4919     bool isNonZero = (NonZeros & (1 << i)) != 0;
4920     if (isNonZero) {
4921       if (First) {
4922         if (NumZero)
4923           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4924         else
4925           V = DAG.getUNDEF(MVT::v8i16);
4926         First = false;
4927       }
4928       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4929                       MVT::v8i16, V, Op.getOperand(i),
4930                       DAG.getIntPtrConstant(i));
4931     }
4932   }
4933
4934   return V;
4935 }
4936
4937 /// getVShift - Return a vector logical shift node.
4938 ///
4939 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4940                          unsigned NumBits, SelectionDAG &DAG,
4941                          const TargetLowering &TLI, DebugLoc dl) {
4942   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4943   EVT ShVT = MVT::v2i64;
4944   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4945   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4946   return DAG.getNode(ISD::BITCAST, dl, VT,
4947                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4948                              DAG.getConstant(NumBits,
4949                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4950 }
4951
4952 SDValue
4953 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4954                                           SelectionDAG &DAG) const {
4955
4956   // Check if the scalar load can be widened into a vector load. And if
4957   // the address is "base + cst" see if the cst can be "absorbed" into
4958   // the shuffle mask.
4959   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4960     SDValue Ptr = LD->getBasePtr();
4961     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4962       return SDValue();
4963     EVT PVT = LD->getValueType(0);
4964     if (PVT != MVT::i32 && PVT != MVT::f32)
4965       return SDValue();
4966
4967     int FI = -1;
4968     int64_t Offset = 0;
4969     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4970       FI = FINode->getIndex();
4971       Offset = 0;
4972     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4973                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4974       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4975       Offset = Ptr.getConstantOperandVal(1);
4976       Ptr = Ptr.getOperand(0);
4977     } else {
4978       return SDValue();
4979     }
4980
4981     // FIXME: 256-bit vector instructions don't require a strict alignment,
4982     // improve this code to support it better.
4983     unsigned RequiredAlign = VT.getSizeInBits()/8;
4984     SDValue Chain = LD->getChain();
4985     // Make sure the stack object alignment is at least 16 or 32.
4986     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4987     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4988       if (MFI->isFixedObjectIndex(FI)) {
4989         // Can't change the alignment. FIXME: It's possible to compute
4990         // the exact stack offset and reference FI + adjust offset instead.
4991         // If someone *really* cares about this. That's the way to implement it.
4992         return SDValue();
4993       } else {
4994         MFI->setObjectAlignment(FI, RequiredAlign);
4995       }
4996     }
4997
4998     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4999     // Ptr + (Offset & ~15).
5000     if (Offset < 0)
5001       return SDValue();
5002     if ((Offset % RequiredAlign) & 3)
5003       return SDValue();
5004     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5005     if (StartOffset)
5006       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5007                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5008
5009     int EltNo = (Offset - StartOffset) >> 2;
5010     int NumElems = VT.getVectorNumElements();
5011
5012     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5013     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5014     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5015                              LD->getPointerInfo().getWithOffset(StartOffset),
5016                              false, false, false, 0);
5017
5018     // Canonicalize it to a v4i32 or v8i32 shuffle.
5019     SmallVector<int, 8> Mask;
5020     for (int i = 0; i < NumElems; ++i)
5021       Mask.push_back(EltNo);
5022
5023     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5024     return DAG.getNode(ISD::BITCAST, dl, NVT,
5025                        DAG.getVectorShuffle(CanonVT, dl, V1,
5026                                             DAG.getUNDEF(CanonVT),&Mask[0]));
5027   }
5028
5029   return SDValue();
5030 }
5031
5032 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5033 /// vector of type 'VT', see if the elements can be replaced by a single large
5034 /// load which has the same value as a build_vector whose operands are 'elts'.
5035 ///
5036 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5037 ///
5038 /// FIXME: we'd also like to handle the case where the last elements are zero
5039 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5040 /// There's even a handy isZeroNode for that purpose.
5041 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5042                                         DebugLoc &DL, SelectionDAG &DAG) {
5043   EVT EltVT = VT.getVectorElementType();
5044   unsigned NumElems = Elts.size();
5045
5046   LoadSDNode *LDBase = NULL;
5047   unsigned LastLoadedElt = -1U;
5048
5049   // For each element in the initializer, see if we've found a load or an undef.
5050   // If we don't find an initial load element, or later load elements are
5051   // non-consecutive, bail out.
5052   for (unsigned i = 0; i < NumElems; ++i) {
5053     SDValue Elt = Elts[i];
5054
5055     if (!Elt.getNode() ||
5056         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5057       return SDValue();
5058     if (!LDBase) {
5059       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5060         return SDValue();
5061       LDBase = cast<LoadSDNode>(Elt.getNode());
5062       LastLoadedElt = i;
5063       continue;
5064     }
5065     if (Elt.getOpcode() == ISD::UNDEF)
5066       continue;
5067
5068     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5069     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5070       return SDValue();
5071     LastLoadedElt = i;
5072   }
5073
5074   // If we have found an entire vector of loads and undefs, then return a large
5075   // load of the entire vector width starting at the base pointer.  If we found
5076   // consecutive loads for the low half, generate a vzext_load node.
5077   if (LastLoadedElt == NumElems - 1) {
5078     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5079       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5080                          LDBase->getPointerInfo(),
5081                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5082                          LDBase->isInvariant(), 0);
5083     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5084                        LDBase->getPointerInfo(),
5085                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5086                        LDBase->isInvariant(), LDBase->getAlignment());
5087   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5088              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5089     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5090     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5091     SDValue ResNode =
5092         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5093                                 LDBase->getPointerInfo(),
5094                                 LDBase->getAlignment(),
5095                                 false/*isVolatile*/, true/*ReadMem*/,
5096                                 false/*WriteMem*/);
5097     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5098   }
5099   return SDValue();
5100 }
5101
5102 SDValue
5103 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5104   DebugLoc dl = Op.getDebugLoc();
5105
5106   EVT VT = Op.getValueType();
5107   EVT ExtVT = VT.getVectorElementType();
5108   unsigned NumElems = Op.getNumOperands();
5109
5110   // Vectors containing all zeros can be matched by pxor and xorps later
5111   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5112     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5113     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5114     if (Op.getValueType() == MVT::v4i32 ||
5115         Op.getValueType() == MVT::v8i32)
5116       return Op;
5117
5118     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5119   }
5120
5121   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5122   // vectors or broken into v4i32 operations on 256-bit vectors.
5123   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5124     if (Op.getValueType() == MVT::v4i32)
5125       return Op;
5126
5127     return getOnesVector(Op.getValueType(), DAG, dl);
5128   }
5129
5130   unsigned EVTBits = ExtVT.getSizeInBits();
5131
5132   unsigned NumZero  = 0;
5133   unsigned NumNonZero = 0;
5134   unsigned NonZeros = 0;
5135   bool IsAllConstants = true;
5136   SmallSet<SDValue, 8> Values;
5137   for (unsigned i = 0; i < NumElems; ++i) {
5138     SDValue Elt = Op.getOperand(i);
5139     if (Elt.getOpcode() == ISD::UNDEF)
5140       continue;
5141     Values.insert(Elt);
5142     if (Elt.getOpcode() != ISD::Constant &&
5143         Elt.getOpcode() != ISD::ConstantFP)
5144       IsAllConstants = false;
5145     if (X86::isZeroNode(Elt))
5146       NumZero++;
5147     else {
5148       NonZeros |= (1 << i);
5149       NumNonZero++;
5150     }
5151   }
5152
5153   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5154   if (NumNonZero == 0)
5155     return DAG.getUNDEF(VT);
5156
5157   // Special case for single non-zero, non-undef, element.
5158   if (NumNonZero == 1) {
5159     unsigned Idx = CountTrailingZeros_32(NonZeros);
5160     SDValue Item = Op.getOperand(Idx);
5161
5162     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5163     // the value are obviously zero, truncate the value to i32 and do the
5164     // insertion that way.  Only do this if the value is non-constant or if the
5165     // value is a constant being inserted into element 0.  It is cheaper to do
5166     // a constant pool load than it is to do a movd + shuffle.
5167     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5168         (!IsAllConstants || Idx == 0)) {
5169       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5170         // Handle SSE only.
5171         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5172         EVT VecVT = MVT::v4i32;
5173         unsigned VecElts = 4;
5174
5175         // Truncate the value (which may itself be a constant) to i32, and
5176         // convert it to a vector with movd (S2V+shuffle to zero extend).
5177         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5178         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5179         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5180                                            Subtarget->hasXMMInt(), DAG);
5181
5182         // Now we have our 32-bit value zero extended in the low element of
5183         // a vector.  If Idx != 0, swizzle it into place.
5184         if (Idx != 0) {
5185           SmallVector<int, 4> Mask;
5186           Mask.push_back(Idx);
5187           for (unsigned i = 1; i != VecElts; ++i)
5188             Mask.push_back(i);
5189           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5190                                       DAG.getUNDEF(Item.getValueType()),
5191                                       &Mask[0]);
5192         }
5193         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5194       }
5195     }
5196
5197     // If we have a constant or non-constant insertion into the low element of
5198     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5199     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5200     // depending on what the source datatype is.
5201     if (Idx == 0) {
5202       if (NumZero == 0) {
5203         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5204       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5205           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5206         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5207         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5208         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5209                                            DAG);
5210       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5211         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5212         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5213         EVT MiddleVT = MVT::v4i32;
5214         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5215         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5216                                            Subtarget->hasXMMInt(), DAG);
5217         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5218       }
5219     }
5220
5221     // Is it a vector logical left shift?
5222     if (NumElems == 2 && Idx == 1 &&
5223         X86::isZeroNode(Op.getOperand(0)) &&
5224         !X86::isZeroNode(Op.getOperand(1))) {
5225       unsigned NumBits = VT.getSizeInBits();
5226       return getVShift(true, VT,
5227                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5228                                    VT, Op.getOperand(1)),
5229                        NumBits/2, DAG, *this, dl);
5230     }
5231
5232     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5233       return SDValue();
5234
5235     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5236     // is a non-constant being inserted into an element other than the low one,
5237     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5238     // movd/movss) to move this into the low element, then shuffle it into
5239     // place.
5240     if (EVTBits == 32) {
5241       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5242
5243       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5244       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5245                                          Subtarget->hasXMMInt(), DAG);
5246       SmallVector<int, 8> MaskVec;
5247       for (unsigned i = 0; i < NumElems; i++)
5248         MaskVec.push_back(i == Idx ? 0 : 1);
5249       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5250     }
5251   }
5252
5253   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5254   if (Values.size() == 1) {
5255     if (EVTBits == 32) {
5256       // Instead of a shuffle like this:
5257       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5258       // Check if it's possible to issue this instead.
5259       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5260       unsigned Idx = CountTrailingZeros_32(NonZeros);
5261       SDValue Item = Op.getOperand(Idx);
5262       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5263         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5264     }
5265     return SDValue();
5266   }
5267
5268   // A vector full of immediates; various special cases are already
5269   // handled, so this is best done with a single constant-pool load.
5270   if (IsAllConstants)
5271     return SDValue();
5272
5273   // For AVX-length vectors, build the individual 128-bit pieces and use
5274   // shuffles to put them in place.
5275   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5276     SmallVector<SDValue, 32> V;
5277     for (unsigned i = 0; i < NumElems; ++i)
5278       V.push_back(Op.getOperand(i));
5279
5280     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5281
5282     // Build both the lower and upper subvector.
5283     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5284     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5285                                 NumElems/2);
5286
5287     // Recreate the wider vector with the lower and upper part.
5288     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5289                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5290     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5291                               DAG, dl);
5292   }
5293
5294   // Let legalizer expand 2-wide build_vectors.
5295   if (EVTBits == 64) {
5296     if (NumNonZero == 1) {
5297       // One half is zero or undef.
5298       unsigned Idx = CountTrailingZeros_32(NonZeros);
5299       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5300                                  Op.getOperand(Idx));
5301       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5302                                          Subtarget->hasXMMInt(), DAG);
5303     }
5304     return SDValue();
5305   }
5306
5307   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5308   if (EVTBits == 8 && NumElems == 16) {
5309     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5310                                         *this);
5311     if (V.getNode()) return V;
5312   }
5313
5314   if (EVTBits == 16 && NumElems == 8) {
5315     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5316                                       *this);
5317     if (V.getNode()) return V;
5318   }
5319
5320   // If element VT is == 32 bits, turn it into a number of shuffles.
5321   SmallVector<SDValue, 8> V;
5322   V.resize(NumElems);
5323   if (NumElems == 4 && NumZero > 0) {
5324     for (unsigned i = 0; i < 4; ++i) {
5325       bool isZero = !(NonZeros & (1 << i));
5326       if (isZero)
5327         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5328       else
5329         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5330     }
5331
5332     for (unsigned i = 0; i < 2; ++i) {
5333       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5334         default: break;
5335         case 0:
5336           V[i] = V[i*2];  // Must be a zero vector.
5337           break;
5338         case 1:
5339           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5340           break;
5341         case 2:
5342           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5343           break;
5344         case 3:
5345           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5346           break;
5347       }
5348     }
5349
5350     SmallVector<int, 8> MaskVec;
5351     bool Reverse = (NonZeros & 0x3) == 2;
5352     for (unsigned i = 0; i < 2; ++i)
5353       MaskVec.push_back(Reverse ? 1-i : i);
5354     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5355     for (unsigned i = 0; i < 2; ++i)
5356       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5357     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5358   }
5359
5360   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5361     // Check for a build vector of consecutive loads.
5362     for (unsigned i = 0; i < NumElems; ++i)
5363       V[i] = Op.getOperand(i);
5364
5365     // Check for elements which are consecutive loads.
5366     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5367     if (LD.getNode())
5368       return LD;
5369
5370     // For SSE 4.1, use insertps to put the high elements into the low element.
5371     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5372       SDValue Result;
5373       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5374         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5375       else
5376         Result = DAG.getUNDEF(VT);
5377
5378       for (unsigned i = 1; i < NumElems; ++i) {
5379         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5380         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5381                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5382       }
5383       return Result;
5384     }
5385
5386     // Otherwise, expand into a number of unpckl*, start by extending each of
5387     // our (non-undef) elements to the full vector width with the element in the
5388     // bottom slot of the vector (which generates no code for SSE).
5389     for (unsigned i = 0; i < NumElems; ++i) {
5390       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5391         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5392       else
5393         V[i] = DAG.getUNDEF(VT);
5394     }
5395
5396     // Next, we iteratively mix elements, e.g. for v4f32:
5397     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5398     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5399     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5400     unsigned EltStride = NumElems >> 1;
5401     while (EltStride != 0) {
5402       for (unsigned i = 0; i < EltStride; ++i) {
5403         // If V[i+EltStride] is undef and this is the first round of mixing,
5404         // then it is safe to just drop this shuffle: V[i] is already in the
5405         // right place, the one element (since it's the first round) being
5406         // inserted as undef can be dropped.  This isn't safe for successive
5407         // rounds because they will permute elements within both vectors.
5408         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5409             EltStride == NumElems/2)
5410           continue;
5411
5412         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5413       }
5414       EltStride >>= 1;
5415     }
5416     return V[0];
5417   }
5418   return SDValue();
5419 }
5420
5421 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5422 // them in a MMX register.  This is better than doing a stack convert.
5423 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5424   DebugLoc dl = Op.getDebugLoc();
5425   EVT ResVT = Op.getValueType();
5426
5427   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5428          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5429   int Mask[2];
5430   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5431   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5432   InVec = Op.getOperand(1);
5433   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5434     unsigned NumElts = ResVT.getVectorNumElements();
5435     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5436     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5437                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5438   } else {
5439     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5440     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5441     Mask[0] = 0; Mask[1] = 2;
5442     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5443   }
5444   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5445 }
5446
5447 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5448 // to create 256-bit vectors from two other 128-bit ones.
5449 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5450   DebugLoc dl = Op.getDebugLoc();
5451   EVT ResVT = Op.getValueType();
5452
5453   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5454
5455   SDValue V1 = Op.getOperand(0);
5456   SDValue V2 = Op.getOperand(1);
5457   unsigned NumElems = ResVT.getVectorNumElements();
5458
5459   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5460                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5461   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5462                             DAG, dl);
5463 }
5464
5465 SDValue
5466 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5467   EVT ResVT = Op.getValueType();
5468
5469   assert(Op.getNumOperands() == 2);
5470   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5471          "Unsupported CONCAT_VECTORS for value type");
5472
5473   // We support concatenate two MMX registers and place them in a MMX register.
5474   // This is better than doing a stack convert.
5475   if (ResVT.is128BitVector())
5476     return LowerMMXCONCAT_VECTORS(Op, DAG);
5477
5478   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5479   // from two other 128-bit ones.
5480   return LowerAVXCONCAT_VECTORS(Op, DAG);
5481 }
5482
5483 // v8i16 shuffles - Prefer shuffles in the following order:
5484 // 1. [all]   pshuflw, pshufhw, optional move
5485 // 2. [ssse3] 1 x pshufb
5486 // 3. [ssse3] 2 x pshufb + 1 x por
5487 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5488 SDValue
5489 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5490                                             SelectionDAG &DAG) const {
5491   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5492   SDValue V1 = SVOp->getOperand(0);
5493   SDValue V2 = SVOp->getOperand(1);
5494   DebugLoc dl = SVOp->getDebugLoc();
5495   SmallVector<int, 8> MaskVals;
5496
5497   // Determine if more than 1 of the words in each of the low and high quadwords
5498   // of the result come from the same quadword of one of the two inputs.  Undef
5499   // mask values count as coming from any quadword, for better codegen.
5500   unsigned LoQuad[] = { 0, 0, 0, 0 };
5501   unsigned HiQuad[] = { 0, 0, 0, 0 };
5502   BitVector InputQuads(4);
5503   for (unsigned i = 0; i < 8; ++i) {
5504     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5505     int EltIdx = SVOp->getMaskElt(i);
5506     MaskVals.push_back(EltIdx);
5507     if (EltIdx < 0) {
5508       ++Quad[0];
5509       ++Quad[1];
5510       ++Quad[2];
5511       ++Quad[3];
5512       continue;
5513     }
5514     ++Quad[EltIdx / 4];
5515     InputQuads.set(EltIdx / 4);
5516   }
5517
5518   int BestLoQuad = -1;
5519   unsigned MaxQuad = 1;
5520   for (unsigned i = 0; i < 4; ++i) {
5521     if (LoQuad[i] > MaxQuad) {
5522       BestLoQuad = i;
5523       MaxQuad = LoQuad[i];
5524     }
5525   }
5526
5527   int BestHiQuad = -1;
5528   MaxQuad = 1;
5529   for (unsigned i = 0; i < 4; ++i) {
5530     if (HiQuad[i] > MaxQuad) {
5531       BestHiQuad = i;
5532       MaxQuad = HiQuad[i];
5533     }
5534   }
5535
5536   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5537   // of the two input vectors, shuffle them into one input vector so only a
5538   // single pshufb instruction is necessary. If There are more than 2 input
5539   // quads, disable the next transformation since it does not help SSSE3.
5540   bool V1Used = InputQuads[0] || InputQuads[1];
5541   bool V2Used = InputQuads[2] || InputQuads[3];
5542   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5543     if (InputQuads.count() == 2 && V1Used && V2Used) {
5544       BestLoQuad = InputQuads.find_first();
5545       BestHiQuad = InputQuads.find_next(BestLoQuad);
5546     }
5547     if (InputQuads.count() > 2) {
5548       BestLoQuad = -1;
5549       BestHiQuad = -1;
5550     }
5551   }
5552
5553   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5554   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5555   // words from all 4 input quadwords.
5556   SDValue NewV;
5557   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5558     SmallVector<int, 8> MaskV;
5559     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5560     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5561     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5562                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5563                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5564     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5565
5566     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5567     // source words for the shuffle, to aid later transformations.
5568     bool AllWordsInNewV = true;
5569     bool InOrder[2] = { true, true };
5570     for (unsigned i = 0; i != 8; ++i) {
5571       int idx = MaskVals[i];
5572       if (idx != (int)i)
5573         InOrder[i/4] = false;
5574       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5575         continue;
5576       AllWordsInNewV = false;
5577       break;
5578     }
5579
5580     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5581     if (AllWordsInNewV) {
5582       for (int i = 0; i != 8; ++i) {
5583         int idx = MaskVals[i];
5584         if (idx < 0)
5585           continue;
5586         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5587         if ((idx != i) && idx < 4)
5588           pshufhw = false;
5589         if ((idx != i) && idx > 3)
5590           pshuflw = false;
5591       }
5592       V1 = NewV;
5593       V2Used = false;
5594       BestLoQuad = 0;
5595       BestHiQuad = 1;
5596     }
5597
5598     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5599     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5600     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5601       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5602       unsigned TargetMask = 0;
5603       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5604                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5605       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5606                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5607       V1 = NewV.getOperand(0);
5608       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5609     }
5610   }
5611
5612   // If we have SSSE3, and all words of the result are from 1 input vector,
5613   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5614   // is present, fall back to case 4.
5615   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5616     SmallVector<SDValue,16> pshufbMask;
5617
5618     // If we have elements from both input vectors, set the high bit of the
5619     // shuffle mask element to zero out elements that come from V2 in the V1
5620     // mask, and elements that come from V1 in the V2 mask, so that the two
5621     // results can be OR'd together.
5622     bool TwoInputs = V1Used && V2Used;
5623     for (unsigned i = 0; i != 8; ++i) {
5624       int EltIdx = MaskVals[i] * 2;
5625       if (TwoInputs && (EltIdx >= 16)) {
5626         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5627         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5628         continue;
5629       }
5630       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5631       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5632     }
5633     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5634     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5635                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5636                                  MVT::v16i8, &pshufbMask[0], 16));
5637     if (!TwoInputs)
5638       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5639
5640     // Calculate the shuffle mask for the second input, shuffle it, and
5641     // OR it with the first shuffled input.
5642     pshufbMask.clear();
5643     for (unsigned i = 0; i != 8; ++i) {
5644       int EltIdx = MaskVals[i] * 2;
5645       if (EltIdx < 16) {
5646         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5647         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5648         continue;
5649       }
5650       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5651       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5652     }
5653     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5654     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5655                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5656                                  MVT::v16i8, &pshufbMask[0], 16));
5657     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5658     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5659   }
5660
5661   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5662   // and update MaskVals with new element order.
5663   BitVector InOrder(8);
5664   if (BestLoQuad >= 0) {
5665     SmallVector<int, 8> MaskV;
5666     for (int i = 0; i != 4; ++i) {
5667       int idx = MaskVals[i];
5668       if (idx < 0) {
5669         MaskV.push_back(-1);
5670         InOrder.set(i);
5671       } else if ((idx / 4) == BestLoQuad) {
5672         MaskV.push_back(idx & 3);
5673         InOrder.set(i);
5674       } else {
5675         MaskV.push_back(-1);
5676       }
5677     }
5678     for (unsigned i = 4; i != 8; ++i)
5679       MaskV.push_back(i);
5680     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5681                                 &MaskV[0]);
5682
5683     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5684         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5685       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5686                                NewV.getOperand(0),
5687                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5688                                DAG);
5689   }
5690
5691   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5692   // and update MaskVals with the new element order.
5693   if (BestHiQuad >= 0) {
5694     SmallVector<int, 8> MaskV;
5695     for (unsigned i = 0; i != 4; ++i)
5696       MaskV.push_back(i);
5697     for (unsigned i = 4; i != 8; ++i) {
5698       int idx = MaskVals[i];
5699       if (idx < 0) {
5700         MaskV.push_back(-1);
5701         InOrder.set(i);
5702       } else if ((idx / 4) == BestHiQuad) {
5703         MaskV.push_back((idx & 3) + 4);
5704         InOrder.set(i);
5705       } else {
5706         MaskV.push_back(-1);
5707       }
5708     }
5709     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5710                                 &MaskV[0]);
5711
5712     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5713         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5714       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5715                               NewV.getOperand(0),
5716                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5717                               DAG);
5718   }
5719
5720   // In case BestHi & BestLo were both -1, which means each quadword has a word
5721   // from each of the four input quadwords, calculate the InOrder bitvector now
5722   // before falling through to the insert/extract cleanup.
5723   if (BestLoQuad == -1 && BestHiQuad == -1) {
5724     NewV = V1;
5725     for (int i = 0; i != 8; ++i)
5726       if (MaskVals[i] < 0 || MaskVals[i] == i)
5727         InOrder.set(i);
5728   }
5729
5730   // The other elements are put in the right place using pextrw and pinsrw.
5731   for (unsigned i = 0; i != 8; ++i) {
5732     if (InOrder[i])
5733       continue;
5734     int EltIdx = MaskVals[i];
5735     if (EltIdx < 0)
5736       continue;
5737     SDValue ExtOp = (EltIdx < 8)
5738     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5739                   DAG.getIntPtrConstant(EltIdx))
5740     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5741                   DAG.getIntPtrConstant(EltIdx - 8));
5742     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5743                        DAG.getIntPtrConstant(i));
5744   }
5745   return NewV;
5746 }
5747
5748 // v16i8 shuffles - Prefer shuffles in the following order:
5749 // 1. [ssse3] 1 x pshufb
5750 // 2. [ssse3] 2 x pshufb + 1 x por
5751 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5752 static
5753 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5754                                  SelectionDAG &DAG,
5755                                  const X86TargetLowering &TLI) {
5756   SDValue V1 = SVOp->getOperand(0);
5757   SDValue V2 = SVOp->getOperand(1);
5758   DebugLoc dl = SVOp->getDebugLoc();
5759   SmallVector<int, 16> MaskVals;
5760   SVOp->getMask(MaskVals);
5761
5762   // If we have SSSE3, case 1 is generated when all result bytes come from
5763   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5764   // present, fall back to case 3.
5765   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5766   bool V1Only = true;
5767   bool V2Only = true;
5768   for (unsigned i = 0; i < 16; ++i) {
5769     int EltIdx = MaskVals[i];
5770     if (EltIdx < 0)
5771       continue;
5772     if (EltIdx < 16)
5773       V2Only = false;
5774     else
5775       V1Only = false;
5776   }
5777
5778   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5779   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5780     SmallVector<SDValue,16> pshufbMask;
5781
5782     // If all result elements are from one input vector, then only translate
5783     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5784     //
5785     // Otherwise, we have elements from both input vectors, and must zero out
5786     // elements that come from V2 in the first mask, and V1 in the second mask
5787     // so that we can OR them together.
5788     bool TwoInputs = !(V1Only || V2Only);
5789     for (unsigned i = 0; i != 16; ++i) {
5790       int EltIdx = MaskVals[i];
5791       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5792         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5793         continue;
5794       }
5795       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5796     }
5797     // If all the elements are from V2, assign it to V1 and return after
5798     // building the first pshufb.
5799     if (V2Only)
5800       V1 = V2;
5801     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5802                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5803                                  MVT::v16i8, &pshufbMask[0], 16));
5804     if (!TwoInputs)
5805       return V1;
5806
5807     // Calculate the shuffle mask for the second input, shuffle it, and
5808     // OR it with the first shuffled input.
5809     pshufbMask.clear();
5810     for (unsigned i = 0; i != 16; ++i) {
5811       int EltIdx = MaskVals[i];
5812       if (EltIdx < 16) {
5813         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5814         continue;
5815       }
5816       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5817     }
5818     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5819                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5820                                  MVT::v16i8, &pshufbMask[0], 16));
5821     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5822   }
5823
5824   // No SSSE3 - Calculate in place words and then fix all out of place words
5825   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5826   // the 16 different words that comprise the two doublequadword input vectors.
5827   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5828   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5829   SDValue NewV = V2Only ? V2 : V1;
5830   for (int i = 0; i != 8; ++i) {
5831     int Elt0 = MaskVals[i*2];
5832     int Elt1 = MaskVals[i*2+1];
5833
5834     // This word of the result is all undef, skip it.
5835     if (Elt0 < 0 && Elt1 < 0)
5836       continue;
5837
5838     // This word of the result is already in the correct place, skip it.
5839     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5840       continue;
5841     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5842       continue;
5843
5844     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5845     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5846     SDValue InsElt;
5847
5848     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5849     // using a single extract together, load it and store it.
5850     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5851       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5852                            DAG.getIntPtrConstant(Elt1 / 2));
5853       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5854                         DAG.getIntPtrConstant(i));
5855       continue;
5856     }
5857
5858     // If Elt1 is defined, extract it from the appropriate source.  If the
5859     // source byte is not also odd, shift the extracted word left 8 bits
5860     // otherwise clear the bottom 8 bits if we need to do an or.
5861     if (Elt1 >= 0) {
5862       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5863                            DAG.getIntPtrConstant(Elt1 / 2));
5864       if ((Elt1 & 1) == 0)
5865         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5866                              DAG.getConstant(8,
5867                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5868       else if (Elt0 >= 0)
5869         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5870                              DAG.getConstant(0xFF00, MVT::i16));
5871     }
5872     // If Elt0 is defined, extract it from the appropriate source.  If the
5873     // source byte is not also even, shift the extracted word right 8 bits. If
5874     // Elt1 was also defined, OR the extracted values together before
5875     // inserting them in the result.
5876     if (Elt0 >= 0) {
5877       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5878                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5879       if ((Elt0 & 1) != 0)
5880         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5881                               DAG.getConstant(8,
5882                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5883       else if (Elt1 >= 0)
5884         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5885                              DAG.getConstant(0x00FF, MVT::i16));
5886       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5887                          : InsElt0;
5888     }
5889     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5890                        DAG.getIntPtrConstant(i));
5891   }
5892   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5893 }
5894
5895 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5896 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5897 /// done when every pair / quad of shuffle mask elements point to elements in
5898 /// the right sequence. e.g.
5899 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5900 static
5901 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5902                                  SelectionDAG &DAG, DebugLoc dl) {
5903   EVT VT = SVOp->getValueType(0);
5904   SDValue V1 = SVOp->getOperand(0);
5905   SDValue V2 = SVOp->getOperand(1);
5906   unsigned NumElems = VT.getVectorNumElements();
5907   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5908   EVT NewVT;
5909   switch (VT.getSimpleVT().SimpleTy) {
5910   default: assert(false && "Unexpected!");
5911   case MVT::v4f32: NewVT = MVT::v2f64; break;
5912   case MVT::v4i32: NewVT = MVT::v2i64; break;
5913   case MVT::v8i16: NewVT = MVT::v4i32; break;
5914   case MVT::v16i8: NewVT = MVT::v4i32; break;
5915   }
5916
5917   int Scale = NumElems / NewWidth;
5918   SmallVector<int, 8> MaskVec;
5919   for (unsigned i = 0; i < NumElems; i += Scale) {
5920     int StartIdx = -1;
5921     for (int j = 0; j < Scale; ++j) {
5922       int EltIdx = SVOp->getMaskElt(i+j);
5923       if (EltIdx < 0)
5924         continue;
5925       if (StartIdx == -1)
5926         StartIdx = EltIdx - (EltIdx % Scale);
5927       if (EltIdx != StartIdx + j)
5928         return SDValue();
5929     }
5930     if (StartIdx == -1)
5931       MaskVec.push_back(-1);
5932     else
5933       MaskVec.push_back(StartIdx / Scale);
5934   }
5935
5936   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5937   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5938   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5939 }
5940
5941 /// getVZextMovL - Return a zero-extending vector move low node.
5942 ///
5943 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5944                             SDValue SrcOp, SelectionDAG &DAG,
5945                             const X86Subtarget *Subtarget, DebugLoc dl) {
5946   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5947     LoadSDNode *LD = NULL;
5948     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5949       LD = dyn_cast<LoadSDNode>(SrcOp);
5950     if (!LD) {
5951       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5952       // instead.
5953       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5954       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5955           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5956           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5957           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5958         // PR2108
5959         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5960         return DAG.getNode(ISD::BITCAST, dl, VT,
5961                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5962                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5963                                                    OpVT,
5964                                                    SrcOp.getOperand(0)
5965                                                           .getOperand(0))));
5966       }
5967     }
5968   }
5969
5970   return DAG.getNode(ISD::BITCAST, dl, VT,
5971                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5972                                  DAG.getNode(ISD::BITCAST, dl,
5973                                              OpVT, SrcOp)));
5974 }
5975
5976 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5977 /// shuffle node referes to only one lane in the sources.
5978 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5979   EVT VT = SVOp->getValueType(0);
5980   int NumElems = VT.getVectorNumElements();
5981   int HalfSize = NumElems/2;
5982   SmallVector<int, 16> M;
5983   SVOp->getMask(M);
5984   bool MatchA = false, MatchB = false;
5985
5986   for (int l = 0; l < NumElems*2; l += HalfSize) {
5987     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5988       MatchA = true;
5989       break;
5990     }
5991   }
5992
5993   for (int l = 0; l < NumElems*2; l += HalfSize) {
5994     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5995       MatchB = true;
5996       break;
5997     }
5998   }
5999
6000   return MatchA && MatchB;
6001 }
6002
6003 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6004 /// which could not be matched by any known target speficic shuffle
6005 static SDValue
6006 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6007   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6008     // If each half of a vector shuffle node referes to only one lane in the
6009     // source vectors, extract each used 128-bit lane and shuffle them using
6010     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6011     // the work to the legalizer.
6012     DebugLoc dl = SVOp->getDebugLoc();
6013     EVT VT = SVOp->getValueType(0);
6014     int NumElems = VT.getVectorNumElements();
6015     int HalfSize = NumElems/2;
6016
6017     // Extract the reference for each half
6018     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6019     int FstVecOpNum = 0, SndVecOpNum = 0;
6020     for (int i = 0; i < HalfSize; ++i) {
6021       int Elt = SVOp->getMaskElt(i);
6022       if (SVOp->getMaskElt(i) < 0)
6023         continue;
6024       FstVecOpNum = Elt/NumElems;
6025       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6026       break;
6027     }
6028     for (int i = HalfSize; i < NumElems; ++i) {
6029       int Elt = SVOp->getMaskElt(i);
6030       if (SVOp->getMaskElt(i) < 0)
6031         continue;
6032       SndVecOpNum = Elt/NumElems;
6033       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6034       break;
6035     }
6036
6037     // Extract the subvectors
6038     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6039                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6040     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6041                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6042
6043     // Generate 128-bit shuffles
6044     SmallVector<int, 16> MaskV1, MaskV2;
6045     for (int i = 0; i < HalfSize; ++i) {
6046       int Elt = SVOp->getMaskElt(i);
6047       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6048     }
6049     for (int i = HalfSize; i < NumElems; ++i) {
6050       int Elt = SVOp->getMaskElt(i);
6051       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6052     }
6053
6054     EVT NVT = V1.getValueType();
6055     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6056     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6057
6058     // Concatenate the result back
6059     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6060                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6061     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6062                               DAG, dl);
6063   }
6064
6065   return SDValue();
6066 }
6067
6068 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6069 /// 4 elements, and match them with several different shuffle types.
6070 static SDValue
6071 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6072   SDValue V1 = SVOp->getOperand(0);
6073   SDValue V2 = SVOp->getOperand(1);
6074   DebugLoc dl = SVOp->getDebugLoc();
6075   EVT VT = SVOp->getValueType(0);
6076
6077   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6078
6079   SmallVector<std::pair<int, int>, 8> Locs;
6080   Locs.resize(4);
6081   SmallVector<int, 8> Mask1(4U, -1);
6082   SmallVector<int, 8> PermMask;
6083   SVOp->getMask(PermMask);
6084
6085   unsigned NumHi = 0;
6086   unsigned NumLo = 0;
6087   for (unsigned i = 0; i != 4; ++i) {
6088     int Idx = PermMask[i];
6089     if (Idx < 0) {
6090       Locs[i] = std::make_pair(-1, -1);
6091     } else {
6092       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6093       if (Idx < 4) {
6094         Locs[i] = std::make_pair(0, NumLo);
6095         Mask1[NumLo] = Idx;
6096         NumLo++;
6097       } else {
6098         Locs[i] = std::make_pair(1, NumHi);
6099         if (2+NumHi < 4)
6100           Mask1[2+NumHi] = Idx;
6101         NumHi++;
6102       }
6103     }
6104   }
6105
6106   if (NumLo <= 2 && NumHi <= 2) {
6107     // If no more than two elements come from either vector. This can be
6108     // implemented with two shuffles. First shuffle gather the elements.
6109     // The second shuffle, which takes the first shuffle as both of its
6110     // vector operands, put the elements into the right order.
6111     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6112
6113     SmallVector<int, 8> Mask2(4U, -1);
6114
6115     for (unsigned i = 0; i != 4; ++i) {
6116       if (Locs[i].first == -1)
6117         continue;
6118       else {
6119         unsigned Idx = (i < 2) ? 0 : 4;
6120         Idx += Locs[i].first * 2 + Locs[i].second;
6121         Mask2[i] = Idx;
6122       }
6123     }
6124
6125     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6126   } else if (NumLo == 3 || NumHi == 3) {
6127     // Otherwise, we must have three elements from one vector, call it X, and
6128     // one element from the other, call it Y.  First, use a shufps to build an
6129     // intermediate vector with the one element from Y and the element from X
6130     // that will be in the same half in the final destination (the indexes don't
6131     // matter). Then, use a shufps to build the final vector, taking the half
6132     // containing the element from Y from the intermediate, and the other half
6133     // from X.
6134     if (NumHi == 3) {
6135       // Normalize it so the 3 elements come from V1.
6136       CommuteVectorShuffleMask(PermMask, VT);
6137       std::swap(V1, V2);
6138     }
6139
6140     // Find the element from V2.
6141     unsigned HiIndex;
6142     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6143       int Val = PermMask[HiIndex];
6144       if (Val < 0)
6145         continue;
6146       if (Val >= 4)
6147         break;
6148     }
6149
6150     Mask1[0] = PermMask[HiIndex];
6151     Mask1[1] = -1;
6152     Mask1[2] = PermMask[HiIndex^1];
6153     Mask1[3] = -1;
6154     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6155
6156     if (HiIndex >= 2) {
6157       Mask1[0] = PermMask[0];
6158       Mask1[1] = PermMask[1];
6159       Mask1[2] = HiIndex & 1 ? 6 : 4;
6160       Mask1[3] = HiIndex & 1 ? 4 : 6;
6161       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6162     } else {
6163       Mask1[0] = HiIndex & 1 ? 2 : 0;
6164       Mask1[1] = HiIndex & 1 ? 0 : 2;
6165       Mask1[2] = PermMask[2];
6166       Mask1[3] = PermMask[3];
6167       if (Mask1[2] >= 0)
6168         Mask1[2] += 4;
6169       if (Mask1[3] >= 0)
6170         Mask1[3] += 4;
6171       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6172     }
6173   }
6174
6175   // Break it into (shuffle shuffle_hi, shuffle_lo).
6176   Locs.clear();
6177   Locs.resize(4);
6178   SmallVector<int,8> LoMask(4U, -1);
6179   SmallVector<int,8> HiMask(4U, -1);
6180
6181   SmallVector<int,8> *MaskPtr = &LoMask;
6182   unsigned MaskIdx = 0;
6183   unsigned LoIdx = 0;
6184   unsigned HiIdx = 2;
6185   for (unsigned i = 0; i != 4; ++i) {
6186     if (i == 2) {
6187       MaskPtr = &HiMask;
6188       MaskIdx = 1;
6189       LoIdx = 0;
6190       HiIdx = 2;
6191     }
6192     int Idx = PermMask[i];
6193     if (Idx < 0) {
6194       Locs[i] = std::make_pair(-1, -1);
6195     } else if (Idx < 4) {
6196       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6197       (*MaskPtr)[LoIdx] = Idx;
6198       LoIdx++;
6199     } else {
6200       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6201       (*MaskPtr)[HiIdx] = Idx;
6202       HiIdx++;
6203     }
6204   }
6205
6206   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6207   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6208   SmallVector<int, 8> MaskOps;
6209   for (unsigned i = 0; i != 4; ++i) {
6210     if (Locs[i].first == -1) {
6211       MaskOps.push_back(-1);
6212     } else {
6213       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6214       MaskOps.push_back(Idx);
6215     }
6216   }
6217   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6218 }
6219
6220 static bool MayFoldVectorLoad(SDValue V) {
6221   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6222     V = V.getOperand(0);
6223   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6224     V = V.getOperand(0);
6225   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6226       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6227     // BUILD_VECTOR (load), undef
6228     V = V.getOperand(0);
6229   if (MayFoldLoad(V))
6230     return true;
6231   return false;
6232 }
6233
6234 // FIXME: the version above should always be used. Since there's
6235 // a bug where several vector shuffles can't be folded because the
6236 // DAG is not updated during lowering and a node claims to have two
6237 // uses while it only has one, use this version, and let isel match
6238 // another instruction if the load really happens to have more than
6239 // one use. Remove this version after this bug get fixed.
6240 // rdar://8434668, PR8156
6241 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6242   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6243     V = V.getOperand(0);
6244   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6245     V = V.getOperand(0);
6246   if (ISD::isNormalLoad(V.getNode()))
6247     return true;
6248   return false;
6249 }
6250
6251 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6252 /// a vector extract, and if both can be later optimized into a single load.
6253 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6254 /// here because otherwise a target specific shuffle node is going to be
6255 /// emitted for this shuffle, and the optimization not done.
6256 /// FIXME: This is probably not the best approach, but fix the problem
6257 /// until the right path is decided.
6258 static
6259 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6260                                          const TargetLowering &TLI) {
6261   EVT VT = V.getValueType();
6262   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6263
6264   // Be sure that the vector shuffle is present in a pattern like this:
6265   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6266   if (!V.hasOneUse())
6267     return false;
6268
6269   SDNode *N = *V.getNode()->use_begin();
6270   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6271     return false;
6272
6273   SDValue EltNo = N->getOperand(1);
6274   if (!isa<ConstantSDNode>(EltNo))
6275     return false;
6276
6277   // If the bit convert changed the number of elements, it is unsafe
6278   // to examine the mask.
6279   bool HasShuffleIntoBitcast = false;
6280   if (V.getOpcode() == ISD::BITCAST) {
6281     EVT SrcVT = V.getOperand(0).getValueType();
6282     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6283       return false;
6284     V = V.getOperand(0);
6285     HasShuffleIntoBitcast = true;
6286   }
6287
6288   // Select the input vector, guarding against out of range extract vector.
6289   unsigned NumElems = VT.getVectorNumElements();
6290   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6291   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6292   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6293
6294   // Skip one more bit_convert if necessary
6295   if (V.getOpcode() == ISD::BITCAST)
6296     V = V.getOperand(0);
6297
6298   if (ISD::isNormalLoad(V.getNode())) {
6299     // Is the original load suitable?
6300     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6301
6302     // FIXME: avoid the multi-use bug that is preventing lots of
6303     // of foldings to be detected, this is still wrong of course, but
6304     // give the temporary desired behavior, and if it happens that
6305     // the load has real more uses, during isel it will not fold, and
6306     // will generate poor code.
6307     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6308       return false;
6309
6310     if (!HasShuffleIntoBitcast)
6311       return true;
6312
6313     // If there's a bitcast before the shuffle, check if the load type and
6314     // alignment is valid.
6315     unsigned Align = LN0->getAlignment();
6316     unsigned NewAlign =
6317       TLI.getTargetData()->getABITypeAlignment(
6318                                     VT.getTypeForEVT(*DAG.getContext()));
6319
6320     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6321       return false;
6322   }
6323
6324   return true;
6325 }
6326
6327 static
6328 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6329   EVT VT = Op.getValueType();
6330
6331   // Canonizalize to v2f64.
6332   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6333   return DAG.getNode(ISD::BITCAST, dl, VT,
6334                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6335                                           V1, DAG));
6336 }
6337
6338 static
6339 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6340                         bool HasXMMInt) {
6341   SDValue V1 = Op.getOperand(0);
6342   SDValue V2 = Op.getOperand(1);
6343   EVT VT = Op.getValueType();
6344
6345   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6346
6347   if (HasXMMInt && VT == MVT::v2f64)
6348     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6349
6350   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6351   return DAG.getNode(ISD::BITCAST, dl, VT,
6352                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6353                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6354                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6355 }
6356
6357 static
6358 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6359   SDValue V1 = Op.getOperand(0);
6360   SDValue V2 = Op.getOperand(1);
6361   EVT VT = Op.getValueType();
6362
6363   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6364          "unsupported shuffle type");
6365
6366   if (V2.getOpcode() == ISD::UNDEF)
6367     V2 = V1;
6368
6369   // v4i32 or v4f32
6370   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6371 }
6372
6373 static inline unsigned getSHUFPOpcode(EVT VT) {
6374   switch(VT.getSimpleVT().SimpleTy) {
6375   case MVT::v8i32: // Use fp unit for int unpack.
6376   case MVT::v8f32:
6377   case MVT::v4i32: // Use fp unit for int unpack.
6378   case MVT::v4f32: return X86ISD::SHUFPS;
6379   case MVT::v4i64: // Use fp unit for int unpack.
6380   case MVT::v4f64:
6381   case MVT::v2i64: // Use fp unit for int unpack.
6382   case MVT::v2f64: return X86ISD::SHUFPD;
6383   default:
6384     llvm_unreachable("Unknown type for shufp*");
6385   }
6386   return 0;
6387 }
6388
6389 static
6390 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6391   SDValue V1 = Op.getOperand(0);
6392   SDValue V2 = Op.getOperand(1);
6393   EVT VT = Op.getValueType();
6394   unsigned NumElems = VT.getVectorNumElements();
6395
6396   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6397   // operand of these instructions is only memory, so check if there's a
6398   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6399   // same masks.
6400   bool CanFoldLoad = false;
6401
6402   // Trivial case, when V2 comes from a load.
6403   if (MayFoldVectorLoad(V2))
6404     CanFoldLoad = true;
6405
6406   // When V1 is a load, it can be folded later into a store in isel, example:
6407   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6408   //    turns into:
6409   //  (MOVLPSmr addr:$src1, VR128:$src2)
6410   // So, recognize this potential and also use MOVLPS or MOVLPD
6411   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6412     CanFoldLoad = true;
6413
6414   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6415   if (CanFoldLoad) {
6416     if (HasXMMInt && NumElems == 2)
6417       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6418
6419     if (NumElems == 4)
6420       // If we don't care about the second element, procede to use movss.
6421       if (SVOp->getMaskElt(1) != -1)
6422         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6423   }
6424
6425   // movl and movlp will both match v2i64, but v2i64 is never matched by
6426   // movl earlier because we make it strict to avoid messing with the movlp load
6427   // folding logic (see the code above getMOVLP call). Match it here then,
6428   // this is horrible, but will stay like this until we move all shuffle
6429   // matching to x86 specific nodes. Note that for the 1st condition all
6430   // types are matched with movsd.
6431   if (HasXMMInt) {
6432     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6433     // as to remove this logic from here, as much as possible
6434     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6435       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6436     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6437   }
6438
6439   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6440
6441   // Invert the operand order and use SHUFPS to match it.
6442   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6443                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6444 }
6445
6446 static inline unsigned getUNPCKLOpcode(EVT VT) {
6447   switch(VT.getSimpleVT().SimpleTy) {
6448   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6449   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6450   case MVT::v4f32: return X86ISD::UNPCKLPS;
6451   case MVT::v2f64: return X86ISD::UNPCKLPD;
6452   case MVT::v8i32: // Use fp unit for int unpack.
6453   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6454   case MVT::v4i64: // Use fp unit for int unpack.
6455   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6456   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6457   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6458   default:
6459     llvm_unreachable("Unknown type for unpckl");
6460   }
6461   return 0;
6462 }
6463
6464 static inline unsigned getUNPCKHOpcode(EVT VT) {
6465   switch(VT.getSimpleVT().SimpleTy) {
6466   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6467   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6468   case MVT::v4f32: return X86ISD::UNPCKHPS;
6469   case MVT::v2f64: return X86ISD::UNPCKHPD;
6470   case MVT::v8i32: // Use fp unit for int unpack.
6471   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6472   case MVT::v4i64: // Use fp unit for int unpack.
6473   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6474   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6475   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6476   default:
6477     llvm_unreachable("Unknown type for unpckh");
6478   }
6479   return 0;
6480 }
6481
6482 static inline unsigned getVPERMILOpcode(EVT VT) {
6483   switch(VT.getSimpleVT().SimpleTy) {
6484   case MVT::v4i32:
6485   case MVT::v4f32: return X86ISD::VPERMILPS;
6486   case MVT::v2i64:
6487   case MVT::v2f64: return X86ISD::VPERMILPD;
6488   case MVT::v8i32:
6489   case MVT::v8f32: return X86ISD::VPERMILPSY;
6490   case MVT::v4i64:
6491   case MVT::v4f64: return X86ISD::VPERMILPDY;
6492   default:
6493     llvm_unreachable("Unknown type for vpermil");
6494   }
6495   return 0;
6496 }
6497
6498 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6499 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6500 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6501 static bool isVectorBroadcast(SDValue &Op) {
6502   EVT VT = Op.getValueType();
6503   bool Is256 = VT.getSizeInBits() == 256;
6504
6505   assert((VT.getSizeInBits() == 128 || Is256) &&
6506          "Unsupported type for vbroadcast node");
6507
6508   SDValue V = Op;
6509   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6510     V = V.getOperand(0);
6511
6512   if (Is256 && !(V.hasOneUse() &&
6513                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6514                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6515     return false;
6516
6517   if (Is256)
6518     V = V.getOperand(1);
6519
6520   if (!V.hasOneUse())
6521     return false;
6522
6523   // Check the source scalar_to_vector type. 256-bit broadcasts are
6524   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6525   // for 32-bit scalars.
6526   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6527     return false;
6528
6529   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6530   if (ScalarSize != 32 && ScalarSize != 64)
6531     return false;
6532   if (!Is256 && ScalarSize == 64)
6533     return false;
6534
6535   V = V.getOperand(0);
6536   if (!MayFoldLoad(V))
6537     return false;
6538
6539   // Return the load node
6540   Op = V;
6541   return true;
6542 }
6543
6544 static
6545 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6546                                const TargetLowering &TLI,
6547                                const X86Subtarget *Subtarget) {
6548   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6549   EVT VT = Op.getValueType();
6550   DebugLoc dl = Op.getDebugLoc();
6551   SDValue V1 = Op.getOperand(0);
6552   SDValue V2 = Op.getOperand(1);
6553
6554   if (isZeroShuffle(SVOp))
6555     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6556
6557   // Handle splat operations
6558   if (SVOp->isSplat()) {
6559     unsigned NumElem = VT.getVectorNumElements();
6560     int Size = VT.getSizeInBits();
6561     // Special case, this is the only place now where it's allowed to return
6562     // a vector_shuffle operation without using a target specific node, because
6563     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6564     // this be moved to DAGCombine instead?
6565     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6566       return Op;
6567
6568     // Use vbroadcast whenever the splat comes from a foldable load
6569     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6570       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6571
6572     // Handle splats by matching through known shuffle masks
6573     if ((Size == 128 && NumElem <= 4) ||
6574         (Size == 256 && NumElem < 8))
6575       return SDValue();
6576
6577     // All remaning splats are promoted to target supported vector shuffles.
6578     return PromoteSplat(SVOp, DAG);
6579   }
6580
6581   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6582   // do it!
6583   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6584     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6585     if (NewOp.getNode())
6586       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6587   } else if ((VT == MVT::v4i32 ||
6588              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6589     // FIXME: Figure out a cleaner way to do this.
6590     // Try to make use of movq to zero out the top part.
6591     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6592       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6593       if (NewOp.getNode()) {
6594         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6595           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6596                               DAG, Subtarget, dl);
6597       }
6598     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6599       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6600       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6601         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6602                             DAG, Subtarget, dl);
6603     }
6604   }
6605   return SDValue();
6606 }
6607
6608 SDValue
6609 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6610   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6611   SDValue V1 = Op.getOperand(0);
6612   SDValue V2 = Op.getOperand(1);
6613   EVT VT = Op.getValueType();
6614   DebugLoc dl = Op.getDebugLoc();
6615   unsigned NumElems = VT.getVectorNumElements();
6616   bool isMMX = VT.getSizeInBits() == 64;
6617   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6618   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6619   bool V1IsSplat = false;
6620   bool V2IsSplat = false;
6621   bool HasXMMInt = Subtarget->hasXMMInt();
6622   MachineFunction &MF = DAG.getMachineFunction();
6623   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6624
6625   // Shuffle operations on MMX not supported.
6626   if (isMMX)
6627     return Op;
6628
6629   // Vector shuffle lowering takes 3 steps:
6630   //
6631   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6632   //    narrowing and commutation of operands should be handled.
6633   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6634   //    shuffle nodes.
6635   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6636   //    so the shuffle can be broken into other shuffles and the legalizer can
6637   //    try the lowering again.
6638   //
6639   // The general ideia is that no vector_shuffle operation should be left to
6640   // be matched during isel, all of them must be converted to a target specific
6641   // node here.
6642
6643   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6644   // narrowing and commutation of operands should be handled. The actual code
6645   // doesn't include all of those, work in progress...
6646   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6647   if (NewOp.getNode())
6648     return NewOp;
6649
6650   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6651   // unpckh_undef). Only use pshufd if speed is more important than size.
6652   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6653     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6654   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6655     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6656
6657   if (X86::isMOVDDUPMask(SVOp) &&
6658       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6659       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6660     return getMOVDDup(Op, dl, V1, DAG);
6661
6662   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6663     return getMOVHighToLow(Op, dl, DAG);
6664
6665   // Use to match splats
6666   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6667       (VT == MVT::v2f64 || VT == MVT::v2i64))
6668     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6669
6670   if (X86::isPSHUFDMask(SVOp)) {
6671     // The actual implementation will match the mask in the if above and then
6672     // during isel it can match several different instructions, not only pshufd
6673     // as its name says, sad but true, emulate the behavior for now...
6674     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6675         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6676
6677     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6678
6679     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6680       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6681
6682     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6683                                 TargetMask, DAG);
6684   }
6685
6686   // Check if this can be converted into a logical shift.
6687   bool isLeft = false;
6688   unsigned ShAmt = 0;
6689   SDValue ShVal;
6690   bool isShift = getSubtarget()->hasXMMInt() &&
6691                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6692   if (isShift && ShVal.hasOneUse()) {
6693     // If the shifted value has multiple uses, it may be cheaper to use
6694     // v_set0 + movlhps or movhlps, etc.
6695     EVT EltVT = VT.getVectorElementType();
6696     ShAmt *= EltVT.getSizeInBits();
6697     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6698   }
6699
6700   if (X86::isMOVLMask(SVOp)) {
6701     if (V1IsUndef)
6702       return V2;
6703     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6704       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6705     if (!X86::isMOVLPMask(SVOp)) {
6706       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6707         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6708
6709       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6710         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6711     }
6712   }
6713
6714   // FIXME: fold these into legal mask.
6715   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6716     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6717
6718   if (X86::isMOVHLPSMask(SVOp))
6719     return getMOVHighToLow(Op, dl, DAG);
6720
6721   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6722     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6723
6724   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6725     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6726
6727   if (X86::isMOVLPMask(SVOp))
6728     return getMOVLP(Op, dl, DAG, HasXMMInt);
6729
6730   if (ShouldXformToMOVHLPS(SVOp) ||
6731       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6732     return CommuteVectorShuffle(SVOp, DAG);
6733
6734   if (isShift) {
6735     // No better options. Use a vshl / vsrl.
6736     EVT EltVT = VT.getVectorElementType();
6737     ShAmt *= EltVT.getSizeInBits();
6738     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6739   }
6740
6741   bool Commuted = false;
6742   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6743   // 1,1,1,1 -> v8i16 though.
6744   V1IsSplat = isSplatVector(V1.getNode());
6745   V2IsSplat = isSplatVector(V2.getNode());
6746
6747   // Canonicalize the splat or undef, if present, to be on the RHS.
6748   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6749     Op = CommuteVectorShuffle(SVOp, DAG);
6750     SVOp = cast<ShuffleVectorSDNode>(Op);
6751     V1 = SVOp->getOperand(0);
6752     V2 = SVOp->getOperand(1);
6753     std::swap(V1IsSplat, V2IsSplat);
6754     std::swap(V1IsUndef, V2IsUndef);
6755     Commuted = true;
6756   }
6757
6758   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6759     // Shuffling low element of v1 into undef, just return v1.
6760     if (V2IsUndef)
6761       return V1;
6762     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6763     // the instruction selector will not match, so get a canonical MOVL with
6764     // swapped operands to undo the commute.
6765     return getMOVL(DAG, dl, VT, V2, V1);
6766   }
6767
6768   if (X86::isUNPCKLMask(SVOp))
6769     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6770
6771   if (X86::isUNPCKHMask(SVOp))
6772     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6773
6774   if (V2IsSplat) {
6775     // Normalize mask so all entries that point to V2 points to its first
6776     // element then try to match unpck{h|l} again. If match, return a
6777     // new vector_shuffle with the corrected mask.
6778     SDValue NewMask = NormalizeMask(SVOp, DAG);
6779     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6780     if (NSVOp != SVOp) {
6781       if (X86::isUNPCKLMask(NSVOp, true)) {
6782         return NewMask;
6783       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6784         return NewMask;
6785       }
6786     }
6787   }
6788
6789   if (Commuted) {
6790     // Commute is back and try unpck* again.
6791     // FIXME: this seems wrong.
6792     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6793     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6794
6795     if (X86::isUNPCKLMask(NewSVOp))
6796       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6797
6798     if (X86::isUNPCKHMask(NewSVOp))
6799       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6800   }
6801
6802   // Normalize the node to match x86 shuffle ops if needed
6803   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6804     return CommuteVectorShuffle(SVOp, DAG);
6805
6806   // The checks below are all present in isShuffleMaskLegal, but they are
6807   // inlined here right now to enable us to directly emit target specific
6808   // nodes, and remove one by one until they don't return Op anymore.
6809   SmallVector<int, 16> M;
6810   SVOp->getMask(M);
6811
6812   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6813     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6814                                 X86::getShufflePALIGNRImmediate(SVOp),
6815                                 DAG);
6816
6817   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6818       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6819     if (VT == MVT::v2f64)
6820       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6821     if (VT == MVT::v2i64)
6822       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6823   }
6824
6825   if (isPSHUFHWMask(M, VT))
6826     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6827                                 X86::getShufflePSHUFHWImmediate(SVOp),
6828                                 DAG);
6829
6830   if (isPSHUFLWMask(M, VT))
6831     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6832                                 X86::getShufflePSHUFLWImmediate(SVOp),
6833                                 DAG);
6834
6835   if (isSHUFPMask(M, VT))
6836     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6837                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6838
6839   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6840     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6841   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6842     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6843
6844   //===--------------------------------------------------------------------===//
6845   // Generate target specific nodes for 128 or 256-bit shuffles only
6846   // supported in the AVX instruction set.
6847   //
6848
6849   // Handle VMOVDDUPY permutations
6850   if (isMOVDDUPYMask(SVOp, Subtarget))
6851     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6852
6853   // Handle VPERMILPS* permutations
6854   if (isVPERMILPSMask(M, VT, Subtarget))
6855     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6856                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6857
6858   // Handle VPERMILPD* permutations
6859   if (isVPERMILPDMask(M, VT, Subtarget))
6860     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6861                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6862
6863   // Handle VPERM2F128 permutations
6864   if (isVPERM2F128Mask(M, VT, Subtarget))
6865     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6866                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6867
6868   // Handle VSHUFPSY permutations
6869   if (isVSHUFPSYMask(M, VT, Subtarget))
6870     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6871                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6872
6873   // Handle VSHUFPDY permutations
6874   if (isVSHUFPDYMask(M, VT, Subtarget))
6875     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6876                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6877
6878   //===--------------------------------------------------------------------===//
6879   // Since no target specific shuffle was selected for this generic one,
6880   // lower it into other known shuffles. FIXME: this isn't true yet, but
6881   // this is the plan.
6882   //
6883
6884   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6885   if (VT == MVT::v8i16) {
6886     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6887     if (NewOp.getNode())
6888       return NewOp;
6889   }
6890
6891   if (VT == MVT::v16i8) {
6892     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6893     if (NewOp.getNode())
6894       return NewOp;
6895   }
6896
6897   // Handle all 128-bit wide vectors with 4 elements, and match them with
6898   // several different shuffle types.
6899   if (NumElems == 4 && VT.getSizeInBits() == 128)
6900     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6901
6902   // Handle general 256-bit shuffles
6903   if (VT.is256BitVector())
6904     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6905
6906   return SDValue();
6907 }
6908
6909 SDValue
6910 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6911                                                 SelectionDAG &DAG) const {
6912   EVT VT = Op.getValueType();
6913   DebugLoc dl = Op.getDebugLoc();
6914
6915   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6916     return SDValue();
6917
6918   if (VT.getSizeInBits() == 8) {
6919     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6920                                     Op.getOperand(0), Op.getOperand(1));
6921     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6922                                     DAG.getValueType(VT));
6923     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6924   } else if (VT.getSizeInBits() == 16) {
6925     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6926     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6927     if (Idx == 0)
6928       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6929                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6930                                      DAG.getNode(ISD::BITCAST, dl,
6931                                                  MVT::v4i32,
6932                                                  Op.getOperand(0)),
6933                                      Op.getOperand(1)));
6934     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6935                                     Op.getOperand(0), Op.getOperand(1));
6936     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6937                                     DAG.getValueType(VT));
6938     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6939   } else if (VT == MVT::f32) {
6940     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6941     // the result back to FR32 register. It's only worth matching if the
6942     // result has a single use which is a store or a bitcast to i32.  And in
6943     // the case of a store, it's not worth it if the index is a constant 0,
6944     // because a MOVSSmr can be used instead, which is smaller and faster.
6945     if (!Op.hasOneUse())
6946       return SDValue();
6947     SDNode *User = *Op.getNode()->use_begin();
6948     if ((User->getOpcode() != ISD::STORE ||
6949          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6950           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6951         (User->getOpcode() != ISD::BITCAST ||
6952          User->getValueType(0) != MVT::i32))
6953       return SDValue();
6954     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6955                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6956                                               Op.getOperand(0)),
6957                                               Op.getOperand(1));
6958     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6959   } else if (VT == MVT::i32) {
6960     // ExtractPS works with constant index.
6961     if (isa<ConstantSDNode>(Op.getOperand(1)))
6962       return Op;
6963   }
6964   return SDValue();
6965 }
6966
6967
6968 SDValue
6969 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6970                                            SelectionDAG &DAG) const {
6971   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6972     return SDValue();
6973
6974   SDValue Vec = Op.getOperand(0);
6975   EVT VecVT = Vec.getValueType();
6976
6977   // If this is a 256-bit vector result, first extract the 128-bit vector and
6978   // then extract the element from the 128-bit vector.
6979   if (VecVT.getSizeInBits() == 256) {
6980     DebugLoc dl = Op.getNode()->getDebugLoc();
6981     unsigned NumElems = VecVT.getVectorNumElements();
6982     SDValue Idx = Op.getOperand(1);
6983     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6984
6985     // Get the 128-bit vector.
6986     bool Upper = IdxVal >= NumElems/2;
6987     Vec = Extract128BitVector(Vec,
6988                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6989
6990     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6991                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6992   }
6993
6994   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6995
6996   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6997     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6998     if (Res.getNode())
6999       return Res;
7000   }
7001
7002   EVT VT = Op.getValueType();
7003   DebugLoc dl = Op.getDebugLoc();
7004   // TODO: handle v16i8.
7005   if (VT.getSizeInBits() == 16) {
7006     SDValue Vec = Op.getOperand(0);
7007     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7008     if (Idx == 0)
7009       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7010                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7011                                      DAG.getNode(ISD::BITCAST, dl,
7012                                                  MVT::v4i32, Vec),
7013                                      Op.getOperand(1)));
7014     // Transform it so it match pextrw which produces a 32-bit result.
7015     EVT EltVT = MVT::i32;
7016     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7017                                     Op.getOperand(0), Op.getOperand(1));
7018     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7019                                     DAG.getValueType(VT));
7020     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7021   } else if (VT.getSizeInBits() == 32) {
7022     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7023     if (Idx == 0)
7024       return Op;
7025
7026     // SHUFPS the element to the lowest double word, then movss.
7027     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7028     EVT VVT = Op.getOperand(0).getValueType();
7029     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7030                                        DAG.getUNDEF(VVT), Mask);
7031     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7032                        DAG.getIntPtrConstant(0));
7033   } else if (VT.getSizeInBits() == 64) {
7034     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7035     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7036     //        to match extract_elt for f64.
7037     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7038     if (Idx == 0)
7039       return Op;
7040
7041     // UNPCKHPD the element to the lowest double word, then movsd.
7042     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7043     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7044     int Mask[2] = { 1, -1 };
7045     EVT VVT = Op.getOperand(0).getValueType();
7046     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7047                                        DAG.getUNDEF(VVT), Mask);
7048     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7049                        DAG.getIntPtrConstant(0));
7050   }
7051
7052   return SDValue();
7053 }
7054
7055 SDValue
7056 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7057                                                SelectionDAG &DAG) const {
7058   EVT VT = Op.getValueType();
7059   EVT EltVT = VT.getVectorElementType();
7060   DebugLoc dl = Op.getDebugLoc();
7061
7062   SDValue N0 = Op.getOperand(0);
7063   SDValue N1 = Op.getOperand(1);
7064   SDValue N2 = Op.getOperand(2);
7065
7066   if (VT.getSizeInBits() == 256)
7067     return SDValue();
7068
7069   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7070       isa<ConstantSDNode>(N2)) {
7071     unsigned Opc;
7072     if (VT == MVT::v8i16)
7073       Opc = X86ISD::PINSRW;
7074     else if (VT == MVT::v16i8)
7075       Opc = X86ISD::PINSRB;
7076     else
7077       Opc = X86ISD::PINSRB;
7078
7079     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7080     // argument.
7081     if (N1.getValueType() != MVT::i32)
7082       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7083     if (N2.getValueType() != MVT::i32)
7084       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7085     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7086   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7087     // Bits [7:6] of the constant are the source select.  This will always be
7088     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7089     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7090     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7091     // Bits [5:4] of the constant are the destination select.  This is the
7092     //  value of the incoming immediate.
7093     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7094     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7095     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7096     // Create this as a scalar to vector..
7097     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7098     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7099   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7100     // PINSR* works with constant index.
7101     return Op;
7102   }
7103   return SDValue();
7104 }
7105
7106 SDValue
7107 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7108   EVT VT = Op.getValueType();
7109   EVT EltVT = VT.getVectorElementType();
7110
7111   DebugLoc dl = Op.getDebugLoc();
7112   SDValue N0 = Op.getOperand(0);
7113   SDValue N1 = Op.getOperand(1);
7114   SDValue N2 = Op.getOperand(2);
7115
7116   // If this is a 256-bit vector result, first extract the 128-bit vector,
7117   // insert the element into the extracted half and then place it back.
7118   if (VT.getSizeInBits() == 256) {
7119     if (!isa<ConstantSDNode>(N2))
7120       return SDValue();
7121
7122     // Get the desired 128-bit vector half.
7123     unsigned NumElems = VT.getVectorNumElements();
7124     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7125     bool Upper = IdxVal >= NumElems/2;
7126     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7127     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7128
7129     // Insert the element into the desired half.
7130     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7131                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7132
7133     // Insert the changed part back to the 256-bit vector
7134     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7135   }
7136
7137   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7138     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7139
7140   if (EltVT == MVT::i8)
7141     return SDValue();
7142
7143   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7144     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7145     // as its second argument.
7146     if (N1.getValueType() != MVT::i32)
7147       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7148     if (N2.getValueType() != MVT::i32)
7149       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7150     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7151   }
7152   return SDValue();
7153 }
7154
7155 SDValue
7156 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7157   LLVMContext *Context = DAG.getContext();
7158   DebugLoc dl = Op.getDebugLoc();
7159   EVT OpVT = Op.getValueType();
7160
7161   // If this is a 256-bit vector result, first insert into a 128-bit
7162   // vector and then insert into the 256-bit vector.
7163   if (OpVT.getSizeInBits() > 128) {
7164     // Insert into a 128-bit vector.
7165     EVT VT128 = EVT::getVectorVT(*Context,
7166                                  OpVT.getVectorElementType(),
7167                                  OpVT.getVectorNumElements() / 2);
7168
7169     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7170
7171     // Insert the 128-bit vector.
7172     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7173                               DAG.getConstant(0, MVT::i32),
7174                               DAG, dl);
7175   }
7176
7177   if (Op.getValueType() == MVT::v1i64 &&
7178       Op.getOperand(0).getValueType() == MVT::i64)
7179     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7180
7181   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7182   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7183          "Expected an SSE type!");
7184   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7185                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7186 }
7187
7188 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7189 // a simple subregister reference or explicit instructions to grab
7190 // upper bits of a vector.
7191 SDValue
7192 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7193   if (Subtarget->hasAVX()) {
7194     DebugLoc dl = Op.getNode()->getDebugLoc();
7195     SDValue Vec = Op.getNode()->getOperand(0);
7196     SDValue Idx = Op.getNode()->getOperand(1);
7197
7198     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7199         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7200         return Extract128BitVector(Vec, Idx, DAG, dl);
7201     }
7202   }
7203   return SDValue();
7204 }
7205
7206 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7207 // simple superregister reference or explicit instructions to insert
7208 // the upper bits of a vector.
7209 SDValue
7210 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7211   if (Subtarget->hasAVX()) {
7212     DebugLoc dl = Op.getNode()->getDebugLoc();
7213     SDValue Vec = Op.getNode()->getOperand(0);
7214     SDValue SubVec = Op.getNode()->getOperand(1);
7215     SDValue Idx = Op.getNode()->getOperand(2);
7216
7217     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7218         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7219       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7220     }
7221   }
7222   return SDValue();
7223 }
7224
7225 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7226 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7227 // one of the above mentioned nodes. It has to be wrapped because otherwise
7228 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7229 // be used to form addressing mode. These wrapped nodes will be selected
7230 // into MOV32ri.
7231 SDValue
7232 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7233   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7234
7235   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7236   // global base reg.
7237   unsigned char OpFlag = 0;
7238   unsigned WrapperKind = X86ISD::Wrapper;
7239   CodeModel::Model M = getTargetMachine().getCodeModel();
7240
7241   if (Subtarget->isPICStyleRIPRel() &&
7242       (M == CodeModel::Small || M == CodeModel::Kernel))
7243     WrapperKind = X86ISD::WrapperRIP;
7244   else if (Subtarget->isPICStyleGOT())
7245     OpFlag = X86II::MO_GOTOFF;
7246   else if (Subtarget->isPICStyleStubPIC())
7247     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7248
7249   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7250                                              CP->getAlignment(),
7251                                              CP->getOffset(), OpFlag);
7252   DebugLoc DL = CP->getDebugLoc();
7253   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7254   // With PIC, the address is actually $g + Offset.
7255   if (OpFlag) {
7256     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7257                          DAG.getNode(X86ISD::GlobalBaseReg,
7258                                      DebugLoc(), getPointerTy()),
7259                          Result);
7260   }
7261
7262   return Result;
7263 }
7264
7265 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7266   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7267
7268   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7269   // global base reg.
7270   unsigned char OpFlag = 0;
7271   unsigned WrapperKind = X86ISD::Wrapper;
7272   CodeModel::Model M = getTargetMachine().getCodeModel();
7273
7274   if (Subtarget->isPICStyleRIPRel() &&
7275       (M == CodeModel::Small || M == CodeModel::Kernel))
7276     WrapperKind = X86ISD::WrapperRIP;
7277   else if (Subtarget->isPICStyleGOT())
7278     OpFlag = X86II::MO_GOTOFF;
7279   else if (Subtarget->isPICStyleStubPIC())
7280     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7281
7282   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7283                                           OpFlag);
7284   DebugLoc DL = JT->getDebugLoc();
7285   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7286
7287   // With PIC, the address is actually $g + Offset.
7288   if (OpFlag)
7289     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7290                          DAG.getNode(X86ISD::GlobalBaseReg,
7291                                      DebugLoc(), getPointerTy()),
7292                          Result);
7293
7294   return Result;
7295 }
7296
7297 SDValue
7298 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7299   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7300
7301   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7302   // global base reg.
7303   unsigned char OpFlag = 0;
7304   unsigned WrapperKind = X86ISD::Wrapper;
7305   CodeModel::Model M = getTargetMachine().getCodeModel();
7306
7307   if (Subtarget->isPICStyleRIPRel() &&
7308       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7309     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7310       OpFlag = X86II::MO_GOTPCREL;
7311     WrapperKind = X86ISD::WrapperRIP;
7312   } else if (Subtarget->isPICStyleGOT()) {
7313     OpFlag = X86II::MO_GOT;
7314   } else if (Subtarget->isPICStyleStubPIC()) {
7315     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7316   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7317     OpFlag = X86II::MO_DARWIN_NONLAZY;
7318   }
7319
7320   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7321
7322   DebugLoc DL = Op.getDebugLoc();
7323   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7324
7325
7326   // With PIC, the address is actually $g + Offset.
7327   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7328       !Subtarget->is64Bit()) {
7329     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7330                          DAG.getNode(X86ISD::GlobalBaseReg,
7331                                      DebugLoc(), getPointerTy()),
7332                          Result);
7333   }
7334
7335   // For symbols that require a load from a stub to get the address, emit the
7336   // load.
7337   if (isGlobalStubReference(OpFlag))
7338     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7339                          MachinePointerInfo::getGOT(), false, false, false, 0);
7340
7341   return Result;
7342 }
7343
7344 SDValue
7345 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7346   // Create the TargetBlockAddressAddress node.
7347   unsigned char OpFlags =
7348     Subtarget->ClassifyBlockAddressReference();
7349   CodeModel::Model M = getTargetMachine().getCodeModel();
7350   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7351   DebugLoc dl = Op.getDebugLoc();
7352   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7353                                        /*isTarget=*/true, OpFlags);
7354
7355   if (Subtarget->isPICStyleRIPRel() &&
7356       (M == CodeModel::Small || M == CodeModel::Kernel))
7357     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7358   else
7359     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7360
7361   // With PIC, the address is actually $g + Offset.
7362   if (isGlobalRelativeToPICBase(OpFlags)) {
7363     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7364                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7365                          Result);
7366   }
7367
7368   return Result;
7369 }
7370
7371 SDValue
7372 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7373                                       int64_t Offset,
7374                                       SelectionDAG &DAG) const {
7375   // Create the TargetGlobalAddress node, folding in the constant
7376   // offset if it is legal.
7377   unsigned char OpFlags =
7378     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7379   CodeModel::Model M = getTargetMachine().getCodeModel();
7380   SDValue Result;
7381   if (OpFlags == X86II::MO_NO_FLAG &&
7382       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7383     // A direct static reference to a global.
7384     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7385     Offset = 0;
7386   } else {
7387     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7388   }
7389
7390   if (Subtarget->isPICStyleRIPRel() &&
7391       (M == CodeModel::Small || M == CodeModel::Kernel))
7392     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7393   else
7394     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7395
7396   // With PIC, the address is actually $g + Offset.
7397   if (isGlobalRelativeToPICBase(OpFlags)) {
7398     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7399                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7400                          Result);
7401   }
7402
7403   // For globals that require a load from a stub to get the address, emit the
7404   // load.
7405   if (isGlobalStubReference(OpFlags))
7406     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7407                          MachinePointerInfo::getGOT(), false, false, false, 0);
7408
7409   // If there was a non-zero offset that we didn't fold, create an explicit
7410   // addition for it.
7411   if (Offset != 0)
7412     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7413                          DAG.getConstant(Offset, getPointerTy()));
7414
7415   return Result;
7416 }
7417
7418 SDValue
7419 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7420   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7421   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7422   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7423 }
7424
7425 static SDValue
7426 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7427            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7428            unsigned char OperandFlags) {
7429   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7430   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7431   DebugLoc dl = GA->getDebugLoc();
7432   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7433                                            GA->getValueType(0),
7434                                            GA->getOffset(),
7435                                            OperandFlags);
7436   if (InFlag) {
7437     SDValue Ops[] = { Chain,  TGA, *InFlag };
7438     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7439   } else {
7440     SDValue Ops[]  = { Chain, TGA };
7441     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7442   }
7443
7444   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7445   MFI->setAdjustsStack(true);
7446
7447   SDValue Flag = Chain.getValue(1);
7448   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7449 }
7450
7451 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7452 static SDValue
7453 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7454                                 const EVT PtrVT) {
7455   SDValue InFlag;
7456   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7457   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7458                                      DAG.getNode(X86ISD::GlobalBaseReg,
7459                                                  DebugLoc(), PtrVT), InFlag);
7460   InFlag = Chain.getValue(1);
7461
7462   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7463 }
7464
7465 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7466 static SDValue
7467 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7468                                 const EVT PtrVT) {
7469   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7470                     X86::RAX, X86II::MO_TLSGD);
7471 }
7472
7473 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7474 // "local exec" model.
7475 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7476                                    const EVT PtrVT, TLSModel::Model model,
7477                                    bool is64Bit) {
7478   DebugLoc dl = GA->getDebugLoc();
7479
7480   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7481   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7482                                                          is64Bit ? 257 : 256));
7483
7484   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7485                                       DAG.getIntPtrConstant(0),
7486                                       MachinePointerInfo(Ptr),
7487                                       false, false, false, 0);
7488
7489   unsigned char OperandFlags = 0;
7490   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7491   // initialexec.
7492   unsigned WrapperKind = X86ISD::Wrapper;
7493   if (model == TLSModel::LocalExec) {
7494     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7495   } else if (is64Bit) {
7496     assert(model == TLSModel::InitialExec);
7497     OperandFlags = X86II::MO_GOTTPOFF;
7498     WrapperKind = X86ISD::WrapperRIP;
7499   } else {
7500     assert(model == TLSModel::InitialExec);
7501     OperandFlags = X86II::MO_INDNTPOFF;
7502   }
7503
7504   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7505   // exec)
7506   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7507                                            GA->getValueType(0),
7508                                            GA->getOffset(), OperandFlags);
7509   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7510
7511   if (model == TLSModel::InitialExec)
7512     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7513                          MachinePointerInfo::getGOT(), false, false, false, 0);
7514
7515   // The address of the thread local variable is the add of the thread
7516   // pointer with the offset of the variable.
7517   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7518 }
7519
7520 SDValue
7521 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7522
7523   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7524   const GlobalValue *GV = GA->getGlobal();
7525
7526   if (Subtarget->isTargetELF()) {
7527     // TODO: implement the "local dynamic" model
7528     // TODO: implement the "initial exec"model for pic executables
7529
7530     // If GV is an alias then use the aliasee for determining
7531     // thread-localness.
7532     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7533       GV = GA->resolveAliasedGlobal(false);
7534
7535     TLSModel::Model model
7536       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7537
7538     switch (model) {
7539       case TLSModel::GeneralDynamic:
7540       case TLSModel::LocalDynamic: // not implemented
7541         if (Subtarget->is64Bit())
7542           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7543         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7544
7545       case TLSModel::InitialExec:
7546       case TLSModel::LocalExec:
7547         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7548                                    Subtarget->is64Bit());
7549     }
7550   } else if (Subtarget->isTargetDarwin()) {
7551     // Darwin only has one model of TLS.  Lower to that.
7552     unsigned char OpFlag = 0;
7553     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7554                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7555
7556     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7557     // global base reg.
7558     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7559                   !Subtarget->is64Bit();
7560     if (PIC32)
7561       OpFlag = X86II::MO_TLVP_PIC_BASE;
7562     else
7563       OpFlag = X86II::MO_TLVP;
7564     DebugLoc DL = Op.getDebugLoc();
7565     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7566                                                 GA->getValueType(0),
7567                                                 GA->getOffset(), OpFlag);
7568     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7569
7570     // With PIC32, the address is actually $g + Offset.
7571     if (PIC32)
7572       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7573                            DAG.getNode(X86ISD::GlobalBaseReg,
7574                                        DebugLoc(), getPointerTy()),
7575                            Offset);
7576
7577     // Lowering the machine isd will make sure everything is in the right
7578     // location.
7579     SDValue Chain = DAG.getEntryNode();
7580     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7581     SDValue Args[] = { Chain, Offset };
7582     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7583
7584     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7585     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7586     MFI->setAdjustsStack(true);
7587
7588     // And our return value (tls address) is in the standard call return value
7589     // location.
7590     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7591     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7592                               Chain.getValue(1));
7593   }
7594
7595   assert(false &&
7596          "TLS not implemented for this target.");
7597
7598   llvm_unreachable("Unreachable");
7599   return SDValue();
7600 }
7601
7602
7603 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7604 /// take a 2 x i32 value to shift plus a shift amount.
7605 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7606   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7607   EVT VT = Op.getValueType();
7608   unsigned VTBits = VT.getSizeInBits();
7609   DebugLoc dl = Op.getDebugLoc();
7610   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7611   SDValue ShOpLo = Op.getOperand(0);
7612   SDValue ShOpHi = Op.getOperand(1);
7613   SDValue ShAmt  = Op.getOperand(2);
7614   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7615                                      DAG.getConstant(VTBits - 1, MVT::i8))
7616                        : DAG.getConstant(0, VT);
7617
7618   SDValue Tmp2, Tmp3;
7619   if (Op.getOpcode() == ISD::SHL_PARTS) {
7620     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7621     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7622   } else {
7623     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7624     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7625   }
7626
7627   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7628                                 DAG.getConstant(VTBits, MVT::i8));
7629   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7630                              AndNode, DAG.getConstant(0, MVT::i8));
7631
7632   SDValue Hi, Lo;
7633   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7634   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7635   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7636
7637   if (Op.getOpcode() == ISD::SHL_PARTS) {
7638     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7639     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7640   } else {
7641     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7642     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7643   }
7644
7645   SDValue Ops[2] = { Lo, Hi };
7646   return DAG.getMergeValues(Ops, 2, dl);
7647 }
7648
7649 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7650                                            SelectionDAG &DAG) const {
7651   EVT SrcVT = Op.getOperand(0).getValueType();
7652
7653   if (SrcVT.isVector())
7654     return SDValue();
7655
7656   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7657          "Unknown SINT_TO_FP to lower!");
7658
7659   // These are really Legal; return the operand so the caller accepts it as
7660   // Legal.
7661   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7662     return Op;
7663   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7664       Subtarget->is64Bit()) {
7665     return Op;
7666   }
7667
7668   DebugLoc dl = Op.getDebugLoc();
7669   unsigned Size = SrcVT.getSizeInBits()/8;
7670   MachineFunction &MF = DAG.getMachineFunction();
7671   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7672   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7673   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7674                                StackSlot,
7675                                MachinePointerInfo::getFixedStack(SSFI),
7676                                false, false, 0);
7677   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7678 }
7679
7680 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7681                                      SDValue StackSlot,
7682                                      SelectionDAG &DAG) const {
7683   // Build the FILD
7684   DebugLoc DL = Op.getDebugLoc();
7685   SDVTList Tys;
7686   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7687   if (useSSE)
7688     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7689   else
7690     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7691
7692   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7693
7694   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7695   MachineMemOperand *MMO;
7696   if (FI) {
7697     int SSFI = FI->getIndex();
7698     MMO =
7699       DAG.getMachineFunction()
7700       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7701                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7702   } else {
7703     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7704     StackSlot = StackSlot.getOperand(1);
7705   }
7706   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7707   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7708                                            X86ISD::FILD, DL,
7709                                            Tys, Ops, array_lengthof(Ops),
7710                                            SrcVT, MMO);
7711
7712   if (useSSE) {
7713     Chain = Result.getValue(1);
7714     SDValue InFlag = Result.getValue(2);
7715
7716     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7717     // shouldn't be necessary except that RFP cannot be live across
7718     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7719     MachineFunction &MF = DAG.getMachineFunction();
7720     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7721     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7722     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7723     Tys = DAG.getVTList(MVT::Other);
7724     SDValue Ops[] = {
7725       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7726     };
7727     MachineMemOperand *MMO =
7728       DAG.getMachineFunction()
7729       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7730                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7731
7732     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7733                                     Ops, array_lengthof(Ops),
7734                                     Op.getValueType(), MMO);
7735     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7736                          MachinePointerInfo::getFixedStack(SSFI),
7737                          false, false, false, 0);
7738   }
7739
7740   return Result;
7741 }
7742
7743 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7744 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7745                                                SelectionDAG &DAG) const {
7746   // This algorithm is not obvious. Here it is in C code, more or less:
7747   /*
7748     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7749       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7750       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7751
7752       // Copy ints to xmm registers.
7753       __m128i xh = _mm_cvtsi32_si128( hi );
7754       __m128i xl = _mm_cvtsi32_si128( lo );
7755
7756       // Combine into low half of a single xmm register.
7757       __m128i x = _mm_unpacklo_epi32( xh, xl );
7758       __m128d d;
7759       double sd;
7760
7761       // Merge in appropriate exponents to give the integer bits the right
7762       // magnitude.
7763       x = _mm_unpacklo_epi32( x, exp );
7764
7765       // Subtract away the biases to deal with the IEEE-754 double precision
7766       // implicit 1.
7767       d = _mm_sub_pd( (__m128d) x, bias );
7768
7769       // All conversions up to here are exact. The correctly rounded result is
7770       // calculated using the current rounding mode using the following
7771       // horizontal add.
7772       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7773       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7774                                 // store doesn't really need to be here (except
7775                                 // maybe to zero the other double)
7776       return sd;
7777     }
7778   */
7779
7780   DebugLoc dl = Op.getDebugLoc();
7781   LLVMContext *Context = DAG.getContext();
7782
7783   // Build some magic constants.
7784   std::vector<Constant*> CV0;
7785   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7786   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7787   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7788   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7789   Constant *C0 = ConstantVector::get(CV0);
7790   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7791
7792   std::vector<Constant*> CV1;
7793   CV1.push_back(
7794     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7795   CV1.push_back(
7796     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7797   Constant *C1 = ConstantVector::get(CV1);
7798   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7799
7800   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7801                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7802                                         Op.getOperand(0),
7803                                         DAG.getIntPtrConstant(1)));
7804   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7805                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7806                                         Op.getOperand(0),
7807                                         DAG.getIntPtrConstant(0)));
7808   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7809   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7810                               MachinePointerInfo::getConstantPool(),
7811                               false, false, false, 16);
7812   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7813   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7814   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7815                               MachinePointerInfo::getConstantPool(),
7816                               false, false, false, 16);
7817   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7818
7819   // Add the halves; easiest way is to swap them into another reg first.
7820   int ShufMask[2] = { 1, -1 };
7821   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7822                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7823   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7824   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7825                      DAG.getIntPtrConstant(0));
7826 }
7827
7828 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7829 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7830                                                SelectionDAG &DAG) const {
7831   DebugLoc dl = Op.getDebugLoc();
7832   // FP constant to bias correct the final result.
7833   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7834                                    MVT::f64);
7835
7836   // Load the 32-bit value into an XMM register.
7837   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7838                              Op.getOperand(0));
7839
7840   // Zero out the upper parts of the register.
7841   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7842                                      DAG);
7843
7844   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7845                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7846                      DAG.getIntPtrConstant(0));
7847
7848   // Or the load with the bias.
7849   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7850                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7851                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7852                                                    MVT::v2f64, Load)),
7853                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7854                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7855                                                    MVT::v2f64, Bias)));
7856   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7857                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7858                    DAG.getIntPtrConstant(0));
7859
7860   // Subtract the bias.
7861   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7862
7863   // Handle final rounding.
7864   EVT DestVT = Op.getValueType();
7865
7866   if (DestVT.bitsLT(MVT::f64)) {
7867     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7868                        DAG.getIntPtrConstant(0));
7869   } else if (DestVT.bitsGT(MVT::f64)) {
7870     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7871   }
7872
7873   // Handle final rounding.
7874   return Sub;
7875 }
7876
7877 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7878                                            SelectionDAG &DAG) const {
7879   SDValue N0 = Op.getOperand(0);
7880   DebugLoc dl = Op.getDebugLoc();
7881
7882   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7883   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7884   // the optimization here.
7885   if (DAG.SignBitIsZero(N0))
7886     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7887
7888   EVT SrcVT = N0.getValueType();
7889   EVT DstVT = Op.getValueType();
7890   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7891     return LowerUINT_TO_FP_i64(Op, DAG);
7892   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7893     return LowerUINT_TO_FP_i32(Op, DAG);
7894
7895   // Make a 64-bit buffer, and use it to build an FILD.
7896   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7897   if (SrcVT == MVT::i32) {
7898     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7899     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7900                                      getPointerTy(), StackSlot, WordOff);
7901     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7902                                   StackSlot, MachinePointerInfo(),
7903                                   false, false, 0);
7904     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7905                                   OffsetSlot, MachinePointerInfo(),
7906                                   false, false, 0);
7907     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7908     return Fild;
7909   }
7910
7911   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7912   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7913                                 StackSlot, MachinePointerInfo(),
7914                                false, false, 0);
7915   // For i64 source, we need to add the appropriate power of 2 if the input
7916   // was negative.  This is the same as the optimization in
7917   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7918   // we must be careful to do the computation in x87 extended precision, not
7919   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7920   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7921   MachineMemOperand *MMO =
7922     DAG.getMachineFunction()
7923     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7924                           MachineMemOperand::MOLoad, 8, 8);
7925
7926   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7927   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7928   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7929                                          MVT::i64, MMO);
7930
7931   APInt FF(32, 0x5F800000ULL);
7932
7933   // Check whether the sign bit is set.
7934   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7935                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7936                                  ISD::SETLT);
7937
7938   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7939   SDValue FudgePtr = DAG.getConstantPool(
7940                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7941                                          getPointerTy());
7942
7943   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7944   SDValue Zero = DAG.getIntPtrConstant(0);
7945   SDValue Four = DAG.getIntPtrConstant(4);
7946   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7947                                Zero, Four);
7948   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7949
7950   // Load the value out, extending it from f32 to f80.
7951   // FIXME: Avoid the extend by constructing the right constant pool?
7952   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7953                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7954                                  MVT::f32, false, false, 4);
7955   // Extend everything to 80 bits to force it to be done on x87.
7956   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7957   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7958 }
7959
7960 std::pair<SDValue,SDValue> X86TargetLowering::
7961 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7962   DebugLoc DL = Op.getDebugLoc();
7963
7964   EVT DstTy = Op.getValueType();
7965
7966   if (!IsSigned) {
7967     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7968     DstTy = MVT::i64;
7969   }
7970
7971   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7972          DstTy.getSimpleVT() >= MVT::i16 &&
7973          "Unknown FP_TO_SINT to lower!");
7974
7975   // These are really Legal.
7976   if (DstTy == MVT::i32 &&
7977       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7978     return std::make_pair(SDValue(), SDValue());
7979   if (Subtarget->is64Bit() &&
7980       DstTy == MVT::i64 &&
7981       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7982     return std::make_pair(SDValue(), SDValue());
7983
7984   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7985   // stack slot.
7986   MachineFunction &MF = DAG.getMachineFunction();
7987   unsigned MemSize = DstTy.getSizeInBits()/8;
7988   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7989   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7990
7991
7992
7993   unsigned Opc;
7994   switch (DstTy.getSimpleVT().SimpleTy) {
7995   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7996   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7997   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7998   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7999   }
8000
8001   SDValue Chain = DAG.getEntryNode();
8002   SDValue Value = Op.getOperand(0);
8003   EVT TheVT = Op.getOperand(0).getValueType();
8004   if (isScalarFPTypeInSSEReg(TheVT)) {
8005     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8006     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8007                          MachinePointerInfo::getFixedStack(SSFI),
8008                          false, false, 0);
8009     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8010     SDValue Ops[] = {
8011       Chain, StackSlot, DAG.getValueType(TheVT)
8012     };
8013
8014     MachineMemOperand *MMO =
8015       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8016                               MachineMemOperand::MOLoad, MemSize, MemSize);
8017     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8018                                     DstTy, MMO);
8019     Chain = Value.getValue(1);
8020     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8021     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8022   }
8023
8024   MachineMemOperand *MMO =
8025     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8026                             MachineMemOperand::MOStore, MemSize, MemSize);
8027
8028   // Build the FP_TO_INT*_IN_MEM
8029   SDValue Ops[] = { Chain, Value, StackSlot };
8030   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8031                                          Ops, 3, DstTy, MMO);
8032
8033   return std::make_pair(FIST, StackSlot);
8034 }
8035
8036 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8037                                            SelectionDAG &DAG) const {
8038   if (Op.getValueType().isVector())
8039     return SDValue();
8040
8041   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8042   SDValue FIST = Vals.first, StackSlot = Vals.second;
8043   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8044   if (FIST.getNode() == 0) return Op;
8045
8046   // Load the result.
8047   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8048                      FIST, StackSlot, MachinePointerInfo(),
8049                      false, false, false, 0);
8050 }
8051
8052 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8053                                            SelectionDAG &DAG) const {
8054   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8055   SDValue FIST = Vals.first, StackSlot = Vals.second;
8056   assert(FIST.getNode() && "Unexpected failure");
8057
8058   // Load the result.
8059   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8060                      FIST, StackSlot, MachinePointerInfo(),
8061                      false, false, false, 0);
8062 }
8063
8064 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8065                                      SelectionDAG &DAG) const {
8066   LLVMContext *Context = DAG.getContext();
8067   DebugLoc dl = Op.getDebugLoc();
8068   EVT VT = Op.getValueType();
8069   EVT EltVT = VT;
8070   if (VT.isVector())
8071     EltVT = VT.getVectorElementType();
8072   std::vector<Constant*> CV;
8073   if (EltVT == MVT::f64) {
8074     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8075     CV.push_back(C);
8076     CV.push_back(C);
8077   } else {
8078     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8079     CV.push_back(C);
8080     CV.push_back(C);
8081     CV.push_back(C);
8082     CV.push_back(C);
8083   }
8084   Constant *C = ConstantVector::get(CV);
8085   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8086   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8087                              MachinePointerInfo::getConstantPool(),
8088                              false, false, false, 16);
8089   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8090 }
8091
8092 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8093   LLVMContext *Context = DAG.getContext();
8094   DebugLoc dl = Op.getDebugLoc();
8095   EVT VT = Op.getValueType();
8096   EVT EltVT = VT;
8097   if (VT.isVector())
8098     EltVT = VT.getVectorElementType();
8099   std::vector<Constant*> CV;
8100   if (EltVT == MVT::f64) {
8101     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8102     CV.push_back(C);
8103     CV.push_back(C);
8104   } else {
8105     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8106     CV.push_back(C);
8107     CV.push_back(C);
8108     CV.push_back(C);
8109     CV.push_back(C);
8110   }
8111   Constant *C = ConstantVector::get(CV);
8112   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8113   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8114                              MachinePointerInfo::getConstantPool(),
8115                              false, false, false, 16);
8116   if (VT.isVector()) {
8117     return DAG.getNode(ISD::BITCAST, dl, VT,
8118                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8119                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8120                                 Op.getOperand(0)),
8121                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8122   } else {
8123     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8124   }
8125 }
8126
8127 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8128   LLVMContext *Context = DAG.getContext();
8129   SDValue Op0 = Op.getOperand(0);
8130   SDValue Op1 = Op.getOperand(1);
8131   DebugLoc dl = Op.getDebugLoc();
8132   EVT VT = Op.getValueType();
8133   EVT SrcVT = Op1.getValueType();
8134
8135   // If second operand is smaller, extend it first.
8136   if (SrcVT.bitsLT(VT)) {
8137     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8138     SrcVT = VT;
8139   }
8140   // And if it is bigger, shrink it first.
8141   if (SrcVT.bitsGT(VT)) {
8142     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8143     SrcVT = VT;
8144   }
8145
8146   // At this point the operands and the result should have the same
8147   // type, and that won't be f80 since that is not custom lowered.
8148
8149   // First get the sign bit of second operand.
8150   std::vector<Constant*> CV;
8151   if (SrcVT == MVT::f64) {
8152     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8153     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8154   } else {
8155     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8156     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8157     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8158     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8159   }
8160   Constant *C = ConstantVector::get(CV);
8161   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8162   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8163                               MachinePointerInfo::getConstantPool(),
8164                               false, false, false, 16);
8165   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8166
8167   // Shift sign bit right or left if the two operands have different types.
8168   if (SrcVT.bitsGT(VT)) {
8169     // Op0 is MVT::f32, Op1 is MVT::f64.
8170     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8171     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8172                           DAG.getConstant(32, MVT::i32));
8173     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8174     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8175                           DAG.getIntPtrConstant(0));
8176   }
8177
8178   // Clear first operand sign bit.
8179   CV.clear();
8180   if (VT == MVT::f64) {
8181     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8182     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8183   } else {
8184     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8185     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8186     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8187     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8188   }
8189   C = ConstantVector::get(CV);
8190   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8191   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8192                               MachinePointerInfo::getConstantPool(),
8193                               false, false, false, 16);
8194   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8195
8196   // Or the value with the sign bit.
8197   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8198 }
8199
8200 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8201   SDValue N0 = Op.getOperand(0);
8202   DebugLoc dl = Op.getDebugLoc();
8203   EVT VT = Op.getValueType();
8204
8205   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8206   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8207                                   DAG.getConstant(1, VT));
8208   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8209 }
8210
8211 /// Emit nodes that will be selected as "test Op0,Op0", or something
8212 /// equivalent.
8213 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8214                                     SelectionDAG &DAG) const {
8215   DebugLoc dl = Op.getDebugLoc();
8216
8217   // CF and OF aren't always set the way we want. Determine which
8218   // of these we need.
8219   bool NeedCF = false;
8220   bool NeedOF = false;
8221   switch (X86CC) {
8222   default: break;
8223   case X86::COND_A: case X86::COND_AE:
8224   case X86::COND_B: case X86::COND_BE:
8225     NeedCF = true;
8226     break;
8227   case X86::COND_G: case X86::COND_GE:
8228   case X86::COND_L: case X86::COND_LE:
8229   case X86::COND_O: case X86::COND_NO:
8230     NeedOF = true;
8231     break;
8232   }
8233
8234   // See if we can use the EFLAGS value from the operand instead of
8235   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8236   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8237   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8238     // Emit a CMP with 0, which is the TEST pattern.
8239     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8240                        DAG.getConstant(0, Op.getValueType()));
8241
8242   unsigned Opcode = 0;
8243   unsigned NumOperands = 0;
8244   switch (Op.getNode()->getOpcode()) {
8245   case ISD::ADD:
8246     // Due to an isel shortcoming, be conservative if this add is likely to be
8247     // selected as part of a load-modify-store instruction. When the root node
8248     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8249     // uses of other nodes in the match, such as the ADD in this case. This
8250     // leads to the ADD being left around and reselected, with the result being
8251     // two adds in the output.  Alas, even if none our users are stores, that
8252     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8253     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8254     // climbing the DAG back to the root, and it doesn't seem to be worth the
8255     // effort.
8256     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8257            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8258       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8259         goto default_case;
8260
8261     if (ConstantSDNode *C =
8262         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8263       // An add of one will be selected as an INC.
8264       if (C->getAPIntValue() == 1) {
8265         Opcode = X86ISD::INC;
8266         NumOperands = 1;
8267         break;
8268       }
8269
8270       // An add of negative one (subtract of one) will be selected as a DEC.
8271       if (C->getAPIntValue().isAllOnesValue()) {
8272         Opcode = X86ISD::DEC;
8273         NumOperands = 1;
8274         break;
8275       }
8276     }
8277
8278     // Otherwise use a regular EFLAGS-setting add.
8279     Opcode = X86ISD::ADD;
8280     NumOperands = 2;
8281     break;
8282   case ISD::AND: {
8283     // If the primary and result isn't used, don't bother using X86ISD::AND,
8284     // because a TEST instruction will be better.
8285     bool NonFlagUse = false;
8286     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8287            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8288       SDNode *User = *UI;
8289       unsigned UOpNo = UI.getOperandNo();
8290       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8291         // Look pass truncate.
8292         UOpNo = User->use_begin().getOperandNo();
8293         User = *User->use_begin();
8294       }
8295
8296       if (User->getOpcode() != ISD::BRCOND &&
8297           User->getOpcode() != ISD::SETCC &&
8298           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8299         NonFlagUse = true;
8300         break;
8301       }
8302     }
8303
8304     if (!NonFlagUse)
8305       break;
8306   }
8307     // FALL THROUGH
8308   case ISD::SUB:
8309   case ISD::OR:
8310   case ISD::XOR:
8311     // Due to the ISEL shortcoming noted above, be conservative if this op is
8312     // likely to be selected as part of a load-modify-store instruction.
8313     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8314            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8315       if (UI->getOpcode() == ISD::STORE)
8316         goto default_case;
8317
8318     // Otherwise use a regular EFLAGS-setting instruction.
8319     switch (Op.getNode()->getOpcode()) {
8320     default: llvm_unreachable("unexpected operator!");
8321     case ISD::SUB: Opcode = X86ISD::SUB; break;
8322     case ISD::OR:  Opcode = X86ISD::OR;  break;
8323     case ISD::XOR: Opcode = X86ISD::XOR; break;
8324     case ISD::AND: Opcode = X86ISD::AND; break;
8325     }
8326
8327     NumOperands = 2;
8328     break;
8329   case X86ISD::ADD:
8330   case X86ISD::SUB:
8331   case X86ISD::INC:
8332   case X86ISD::DEC:
8333   case X86ISD::OR:
8334   case X86ISD::XOR:
8335   case X86ISD::AND:
8336     return SDValue(Op.getNode(), 1);
8337   default:
8338   default_case:
8339     break;
8340   }
8341
8342   if (Opcode == 0)
8343     // Emit a CMP with 0, which is the TEST pattern.
8344     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8345                        DAG.getConstant(0, Op.getValueType()));
8346
8347   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8348   SmallVector<SDValue, 4> Ops;
8349   for (unsigned i = 0; i != NumOperands; ++i)
8350     Ops.push_back(Op.getOperand(i));
8351
8352   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8353   DAG.ReplaceAllUsesWith(Op, New);
8354   return SDValue(New.getNode(), 1);
8355 }
8356
8357 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8358 /// equivalent.
8359 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8360                                    SelectionDAG &DAG) const {
8361   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8362     if (C->getAPIntValue() == 0)
8363       return EmitTest(Op0, X86CC, DAG);
8364
8365   DebugLoc dl = Op0.getDebugLoc();
8366   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8367 }
8368
8369 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8370 /// if it's possible.
8371 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8372                                      DebugLoc dl, SelectionDAG &DAG) const {
8373   SDValue Op0 = And.getOperand(0);
8374   SDValue Op1 = And.getOperand(1);
8375   if (Op0.getOpcode() == ISD::TRUNCATE)
8376     Op0 = Op0.getOperand(0);
8377   if (Op1.getOpcode() == ISD::TRUNCATE)
8378     Op1 = Op1.getOperand(0);
8379
8380   SDValue LHS, RHS;
8381   if (Op1.getOpcode() == ISD::SHL)
8382     std::swap(Op0, Op1);
8383   if (Op0.getOpcode() == ISD::SHL) {
8384     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8385       if (And00C->getZExtValue() == 1) {
8386         // If we looked past a truncate, check that it's only truncating away
8387         // known zeros.
8388         unsigned BitWidth = Op0.getValueSizeInBits();
8389         unsigned AndBitWidth = And.getValueSizeInBits();
8390         if (BitWidth > AndBitWidth) {
8391           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8392           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8393           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8394             return SDValue();
8395         }
8396         LHS = Op1;
8397         RHS = Op0.getOperand(1);
8398       }
8399   } else if (Op1.getOpcode() == ISD::Constant) {
8400     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8401     SDValue AndLHS = Op0;
8402     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8403       LHS = AndLHS.getOperand(0);
8404       RHS = AndLHS.getOperand(1);
8405     }
8406   }
8407
8408   if (LHS.getNode()) {
8409     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8410     // instruction.  Since the shift amount is in-range-or-undefined, we know
8411     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8412     // the encoding for the i16 version is larger than the i32 version.
8413     // Also promote i16 to i32 for performance / code size reason.
8414     if (LHS.getValueType() == MVT::i8 ||
8415         LHS.getValueType() == MVT::i16)
8416       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8417
8418     // If the operand types disagree, extend the shift amount to match.  Since
8419     // BT ignores high bits (like shifts) we can use anyextend.
8420     if (LHS.getValueType() != RHS.getValueType())
8421       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8422
8423     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8424     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8425     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8426                        DAG.getConstant(Cond, MVT::i8), BT);
8427   }
8428
8429   return SDValue();
8430 }
8431
8432 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8433
8434   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8435
8436   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8437   SDValue Op0 = Op.getOperand(0);
8438   SDValue Op1 = Op.getOperand(1);
8439   DebugLoc dl = Op.getDebugLoc();
8440   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8441
8442   // Optimize to BT if possible.
8443   // Lower (X & (1 << N)) == 0 to BT(X, N).
8444   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8445   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8446   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8447       Op1.getOpcode() == ISD::Constant &&
8448       cast<ConstantSDNode>(Op1)->isNullValue() &&
8449       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8450     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8451     if (NewSetCC.getNode())
8452       return NewSetCC;
8453   }
8454
8455   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8456   // these.
8457   if (Op1.getOpcode() == ISD::Constant &&
8458       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8459        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8460       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8461
8462     // If the input is a setcc, then reuse the input setcc or use a new one with
8463     // the inverted condition.
8464     if (Op0.getOpcode() == X86ISD::SETCC) {
8465       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8466       bool Invert = (CC == ISD::SETNE) ^
8467         cast<ConstantSDNode>(Op1)->isNullValue();
8468       if (!Invert) return Op0;
8469
8470       CCode = X86::GetOppositeBranchCondition(CCode);
8471       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8472                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8473     }
8474   }
8475
8476   bool isFP = Op1.getValueType().isFloatingPoint();
8477   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8478   if (X86CC == X86::COND_INVALID)
8479     return SDValue();
8480
8481   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8482   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8483                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8484 }
8485
8486 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8487 // ones, and then concatenate the result back.
8488 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8489   EVT VT = Op.getValueType();
8490
8491   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8492          "Unsupported value type for operation");
8493
8494   int NumElems = VT.getVectorNumElements();
8495   DebugLoc dl = Op.getDebugLoc();
8496   SDValue CC = Op.getOperand(2);
8497   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8498   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8499
8500   // Extract the LHS vectors
8501   SDValue LHS = Op.getOperand(0);
8502   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8503   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8504
8505   // Extract the RHS vectors
8506   SDValue RHS = Op.getOperand(1);
8507   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8508   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8509
8510   // Issue the operation on the smaller types and concatenate the result back
8511   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8512   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8513   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8514                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8515                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8516 }
8517
8518
8519 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8520   SDValue Cond;
8521   SDValue Op0 = Op.getOperand(0);
8522   SDValue Op1 = Op.getOperand(1);
8523   SDValue CC = Op.getOperand(2);
8524   EVT VT = Op.getValueType();
8525   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8526   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8527   DebugLoc dl = Op.getDebugLoc();
8528
8529   if (isFP) {
8530     unsigned SSECC = 8;
8531     EVT EltVT = Op0.getValueType().getVectorElementType();
8532     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8533
8534     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8535     bool Swap = false;
8536
8537     // SSE Condition code mapping:
8538     //  0 - EQ
8539     //  1 - LT
8540     //  2 - LE
8541     //  3 - UNORD
8542     //  4 - NEQ
8543     //  5 - NLT
8544     //  6 - NLE
8545     //  7 - ORD
8546     switch (SetCCOpcode) {
8547     default: break;
8548     case ISD::SETOEQ:
8549     case ISD::SETEQ:  SSECC = 0; break;
8550     case ISD::SETOGT:
8551     case ISD::SETGT: Swap = true; // Fallthrough
8552     case ISD::SETLT:
8553     case ISD::SETOLT: SSECC = 1; break;
8554     case ISD::SETOGE:
8555     case ISD::SETGE: Swap = true; // Fallthrough
8556     case ISD::SETLE:
8557     case ISD::SETOLE: SSECC = 2; break;
8558     case ISD::SETUO:  SSECC = 3; break;
8559     case ISD::SETUNE:
8560     case ISD::SETNE:  SSECC = 4; break;
8561     case ISD::SETULE: Swap = true;
8562     case ISD::SETUGE: SSECC = 5; break;
8563     case ISD::SETULT: Swap = true;
8564     case ISD::SETUGT: SSECC = 6; break;
8565     case ISD::SETO:   SSECC = 7; break;
8566     }
8567     if (Swap)
8568       std::swap(Op0, Op1);
8569
8570     // In the two special cases we can't handle, emit two comparisons.
8571     if (SSECC == 8) {
8572       if (SetCCOpcode == ISD::SETUEQ) {
8573         SDValue UNORD, EQ;
8574         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8575         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8576         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8577       } else if (SetCCOpcode == ISD::SETONE) {
8578         SDValue ORD, NEQ;
8579         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8580         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8581         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8582       }
8583       llvm_unreachable("Illegal FP comparison");
8584     }
8585     // Handle all other FP comparisons here.
8586     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8587   }
8588
8589   // Break 256-bit integer vector compare into smaller ones.
8590   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8591     return Lower256IntVSETCC(Op, DAG);
8592
8593   // We are handling one of the integer comparisons here.  Since SSE only has
8594   // GT and EQ comparisons for integer, swapping operands and multiple
8595   // operations may be required for some comparisons.
8596   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8597   bool Swap = false, Invert = false, FlipSigns = false;
8598
8599   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8600   default: break;
8601   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8602   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8603   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8604   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8605   }
8606
8607   switch (SetCCOpcode) {
8608   default: break;
8609   case ISD::SETNE:  Invert = true;
8610   case ISD::SETEQ:  Opc = EQOpc; break;
8611   case ISD::SETLT:  Swap = true;
8612   case ISD::SETGT:  Opc = GTOpc; break;
8613   case ISD::SETGE:  Swap = true;
8614   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8615   case ISD::SETULT: Swap = true;
8616   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8617   case ISD::SETUGE: Swap = true;
8618   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8619   }
8620   if (Swap)
8621     std::swap(Op0, Op1);
8622
8623   // Check that the operation in question is available (most are plain SSE2,
8624   // but PCMPGTQ and PCMPEQQ have different requirements).
8625   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8626     return SDValue();
8627   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8628     return SDValue();
8629
8630   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8631   // bits of the inputs before performing those operations.
8632   if (FlipSigns) {
8633     EVT EltVT = VT.getVectorElementType();
8634     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8635                                       EltVT);
8636     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8637     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8638                                     SignBits.size());
8639     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8640     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8641   }
8642
8643   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8644
8645   // If the logical-not of the result is required, perform that now.
8646   if (Invert)
8647     Result = DAG.getNOT(dl, Result, VT);
8648
8649   return Result;
8650 }
8651
8652 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8653 static bool isX86LogicalCmp(SDValue Op) {
8654   unsigned Opc = Op.getNode()->getOpcode();
8655   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8656     return true;
8657   if (Op.getResNo() == 1 &&
8658       (Opc == X86ISD::ADD ||
8659        Opc == X86ISD::SUB ||
8660        Opc == X86ISD::ADC ||
8661        Opc == X86ISD::SBB ||
8662        Opc == X86ISD::SMUL ||
8663        Opc == X86ISD::UMUL ||
8664        Opc == X86ISD::INC ||
8665        Opc == X86ISD::DEC ||
8666        Opc == X86ISD::OR ||
8667        Opc == X86ISD::XOR ||
8668        Opc == X86ISD::AND))
8669     return true;
8670
8671   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8672     return true;
8673
8674   return false;
8675 }
8676
8677 static bool isZero(SDValue V) {
8678   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8679   return C && C->isNullValue();
8680 }
8681
8682 static bool isAllOnes(SDValue V) {
8683   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8684   return C && C->isAllOnesValue();
8685 }
8686
8687 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8688   bool addTest = true;
8689   SDValue Cond  = Op.getOperand(0);
8690   SDValue Op1 = Op.getOperand(1);
8691   SDValue Op2 = Op.getOperand(2);
8692   DebugLoc DL = Op.getDebugLoc();
8693   SDValue CC;
8694
8695   if (Cond.getOpcode() == ISD::SETCC) {
8696     SDValue NewCond = LowerSETCC(Cond, DAG);
8697     if (NewCond.getNode())
8698       Cond = NewCond;
8699   }
8700
8701   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8702   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8703   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8704   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8705   if (Cond.getOpcode() == X86ISD::SETCC &&
8706       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8707       isZero(Cond.getOperand(1).getOperand(1))) {
8708     SDValue Cmp = Cond.getOperand(1);
8709
8710     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8711
8712     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8713         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8714       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8715
8716       SDValue CmpOp0 = Cmp.getOperand(0);
8717       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8718                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8719
8720       SDValue Res =   // Res = 0 or -1.
8721         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8722                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8723
8724       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8725         Res = DAG.getNOT(DL, Res, Res.getValueType());
8726
8727       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8728       if (N2C == 0 || !N2C->isNullValue())
8729         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8730       return Res;
8731     }
8732   }
8733
8734   // Look past (and (setcc_carry (cmp ...)), 1).
8735   if (Cond.getOpcode() == ISD::AND &&
8736       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8737     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8738     if (C && C->getAPIntValue() == 1)
8739       Cond = Cond.getOperand(0);
8740   }
8741
8742   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8743   // setting operand in place of the X86ISD::SETCC.
8744   unsigned CondOpcode = Cond.getOpcode();
8745   if (CondOpcode == X86ISD::SETCC ||
8746       CondOpcode == X86ISD::SETCC_CARRY) {
8747     CC = Cond.getOperand(0);
8748
8749     SDValue Cmp = Cond.getOperand(1);
8750     unsigned Opc = Cmp.getOpcode();
8751     EVT VT = Op.getValueType();
8752
8753     bool IllegalFPCMov = false;
8754     if (VT.isFloatingPoint() && !VT.isVector() &&
8755         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8756       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8757
8758     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8759         Opc == X86ISD::BT) { // FIXME
8760       Cond = Cmp;
8761       addTest = false;
8762     }
8763   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8764              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8765              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8766               Cond.getOperand(0).getValueType() != MVT::i8)) {
8767     SDValue LHS = Cond.getOperand(0);
8768     SDValue RHS = Cond.getOperand(1);
8769     unsigned X86Opcode;
8770     unsigned X86Cond;
8771     SDVTList VTs;
8772     switch (CondOpcode) {
8773     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8774     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8775     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8776     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8777     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8778     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8779     default: llvm_unreachable("unexpected overflowing operator");
8780     }
8781     if (CondOpcode == ISD::UMULO)
8782       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8783                           MVT::i32);
8784     else
8785       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8786
8787     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8788
8789     if (CondOpcode == ISD::UMULO)
8790       Cond = X86Op.getValue(2);
8791     else
8792       Cond = X86Op.getValue(1);
8793
8794     CC = DAG.getConstant(X86Cond, MVT::i8);
8795     addTest = false;
8796   }
8797
8798   if (addTest) {
8799     // Look pass the truncate.
8800     if (Cond.getOpcode() == ISD::TRUNCATE)
8801       Cond = Cond.getOperand(0);
8802
8803     // We know the result of AND is compared against zero. Try to match
8804     // it to BT.
8805     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8806       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8807       if (NewSetCC.getNode()) {
8808         CC = NewSetCC.getOperand(0);
8809         Cond = NewSetCC.getOperand(1);
8810         addTest = false;
8811       }
8812     }
8813   }
8814
8815   if (addTest) {
8816     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8817     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8818   }
8819
8820   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8821   // a <  b ?  0 : -1 -> RES = setcc_carry
8822   // a >= b ? -1 :  0 -> RES = setcc_carry
8823   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8824   if (Cond.getOpcode() == X86ISD::CMP) {
8825     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8826
8827     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8828         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8829       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8830                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8831       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8832         return DAG.getNOT(DL, Res, Res.getValueType());
8833       return Res;
8834     }
8835   }
8836
8837   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8838   // condition is true.
8839   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8840   SDValue Ops[] = { Op2, Op1, CC, Cond };
8841   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8842 }
8843
8844 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8845 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8846 // from the AND / OR.
8847 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8848   Opc = Op.getOpcode();
8849   if (Opc != ISD::OR && Opc != ISD::AND)
8850     return false;
8851   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8852           Op.getOperand(0).hasOneUse() &&
8853           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8854           Op.getOperand(1).hasOneUse());
8855 }
8856
8857 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8858 // 1 and that the SETCC node has a single use.
8859 static bool isXor1OfSetCC(SDValue Op) {
8860   if (Op.getOpcode() != ISD::XOR)
8861     return false;
8862   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8863   if (N1C && N1C->getAPIntValue() == 1) {
8864     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8865       Op.getOperand(0).hasOneUse();
8866   }
8867   return false;
8868 }
8869
8870 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8871   bool addTest = true;
8872   SDValue Chain = Op.getOperand(0);
8873   SDValue Cond  = Op.getOperand(1);
8874   SDValue Dest  = Op.getOperand(2);
8875   DebugLoc dl = Op.getDebugLoc();
8876   SDValue CC;
8877   bool Inverted = false;
8878
8879   if (Cond.getOpcode() == ISD::SETCC) {
8880     // Check for setcc([su]{add,sub,mul}o == 0).
8881     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8882         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8883         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8884         Cond.getOperand(0).getResNo() == 1 &&
8885         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8886          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8887          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8888          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8889          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8890          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8891       Inverted = true;
8892       Cond = Cond.getOperand(0);
8893     } else {
8894       SDValue NewCond = LowerSETCC(Cond, DAG);
8895       if (NewCond.getNode())
8896         Cond = NewCond;
8897     }
8898   }
8899 #if 0
8900   // FIXME: LowerXALUO doesn't handle these!!
8901   else if (Cond.getOpcode() == X86ISD::ADD  ||
8902            Cond.getOpcode() == X86ISD::SUB  ||
8903            Cond.getOpcode() == X86ISD::SMUL ||
8904            Cond.getOpcode() == X86ISD::UMUL)
8905     Cond = LowerXALUO(Cond, DAG);
8906 #endif
8907
8908   // Look pass (and (setcc_carry (cmp ...)), 1).
8909   if (Cond.getOpcode() == ISD::AND &&
8910       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8911     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8912     if (C && C->getAPIntValue() == 1)
8913       Cond = Cond.getOperand(0);
8914   }
8915
8916   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8917   // setting operand in place of the X86ISD::SETCC.
8918   unsigned CondOpcode = Cond.getOpcode();
8919   if (CondOpcode == X86ISD::SETCC ||
8920       CondOpcode == X86ISD::SETCC_CARRY) {
8921     CC = Cond.getOperand(0);
8922
8923     SDValue Cmp = Cond.getOperand(1);
8924     unsigned Opc = Cmp.getOpcode();
8925     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8926     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8927       Cond = Cmp;
8928       addTest = false;
8929     } else {
8930       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8931       default: break;
8932       case X86::COND_O:
8933       case X86::COND_B:
8934         // These can only come from an arithmetic instruction with overflow,
8935         // e.g. SADDO, UADDO.
8936         Cond = Cond.getNode()->getOperand(1);
8937         addTest = false;
8938         break;
8939       }
8940     }
8941   }
8942   CondOpcode = Cond.getOpcode();
8943   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8944       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8945       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8946        Cond.getOperand(0).getValueType() != MVT::i8)) {
8947     SDValue LHS = Cond.getOperand(0);
8948     SDValue RHS = Cond.getOperand(1);
8949     unsigned X86Opcode;
8950     unsigned X86Cond;
8951     SDVTList VTs;
8952     switch (CondOpcode) {
8953     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8954     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8955     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8956     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8957     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8958     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8959     default: llvm_unreachable("unexpected overflowing operator");
8960     }
8961     if (Inverted)
8962       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8963     if (CondOpcode == ISD::UMULO)
8964       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8965                           MVT::i32);
8966     else
8967       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8968
8969     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8970
8971     if (CondOpcode == ISD::UMULO)
8972       Cond = X86Op.getValue(2);
8973     else
8974       Cond = X86Op.getValue(1);
8975
8976     CC = DAG.getConstant(X86Cond, MVT::i8);
8977     addTest = false;
8978   } else {
8979     unsigned CondOpc;
8980     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8981       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8982       if (CondOpc == ISD::OR) {
8983         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8984         // two branches instead of an explicit OR instruction with a
8985         // separate test.
8986         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8987             isX86LogicalCmp(Cmp)) {
8988           CC = Cond.getOperand(0).getOperand(0);
8989           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8990                               Chain, Dest, CC, Cmp);
8991           CC = Cond.getOperand(1).getOperand(0);
8992           Cond = Cmp;
8993           addTest = false;
8994         }
8995       } else { // ISD::AND
8996         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8997         // two branches instead of an explicit AND instruction with a
8998         // separate test. However, we only do this if this block doesn't
8999         // have a fall-through edge, because this requires an explicit
9000         // jmp when the condition is false.
9001         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9002             isX86LogicalCmp(Cmp) &&
9003             Op.getNode()->hasOneUse()) {
9004           X86::CondCode CCode =
9005             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9006           CCode = X86::GetOppositeBranchCondition(CCode);
9007           CC = DAG.getConstant(CCode, MVT::i8);
9008           SDNode *User = *Op.getNode()->use_begin();
9009           // Look for an unconditional branch following this conditional branch.
9010           // We need this because we need to reverse the successors in order
9011           // to implement FCMP_OEQ.
9012           if (User->getOpcode() == ISD::BR) {
9013             SDValue FalseBB = User->getOperand(1);
9014             SDNode *NewBR =
9015               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9016             assert(NewBR == User);
9017             (void)NewBR;
9018             Dest = FalseBB;
9019
9020             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9021                                 Chain, Dest, CC, Cmp);
9022             X86::CondCode CCode =
9023               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9024             CCode = X86::GetOppositeBranchCondition(CCode);
9025             CC = DAG.getConstant(CCode, MVT::i8);
9026             Cond = Cmp;
9027             addTest = false;
9028           }
9029         }
9030       }
9031     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9032       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9033       // It should be transformed during dag combiner except when the condition
9034       // is set by a arithmetics with overflow node.
9035       X86::CondCode CCode =
9036         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9037       CCode = X86::GetOppositeBranchCondition(CCode);
9038       CC = DAG.getConstant(CCode, MVT::i8);
9039       Cond = Cond.getOperand(0).getOperand(1);
9040       addTest = false;
9041     } else if (Cond.getOpcode() == ISD::SETCC &&
9042                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9043       // For FCMP_OEQ, we can emit
9044       // two branches instead of an explicit AND instruction with a
9045       // separate test. However, we only do this if this block doesn't
9046       // have a fall-through edge, because this requires an explicit
9047       // jmp when the condition is false.
9048       if (Op.getNode()->hasOneUse()) {
9049         SDNode *User = *Op.getNode()->use_begin();
9050         // Look for an unconditional branch following this conditional branch.
9051         // We need this because we need to reverse the successors in order
9052         // to implement FCMP_OEQ.
9053         if (User->getOpcode() == ISD::BR) {
9054           SDValue FalseBB = User->getOperand(1);
9055           SDNode *NewBR =
9056             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9057           assert(NewBR == User);
9058           (void)NewBR;
9059           Dest = FalseBB;
9060
9061           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9062                                     Cond.getOperand(0), Cond.getOperand(1));
9063           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9064           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9065                               Chain, Dest, CC, Cmp);
9066           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9067           Cond = Cmp;
9068           addTest = false;
9069         }
9070       }
9071     } else if (Cond.getOpcode() == ISD::SETCC &&
9072                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9073       // For FCMP_UNE, we can emit
9074       // two branches instead of an explicit AND instruction with a
9075       // separate test. However, we only do this if this block doesn't
9076       // have a fall-through edge, because this requires an explicit
9077       // jmp when the condition is false.
9078       if (Op.getNode()->hasOneUse()) {
9079         SDNode *User = *Op.getNode()->use_begin();
9080         // Look for an unconditional branch following this conditional branch.
9081         // We need this because we need to reverse the successors in order
9082         // to implement FCMP_UNE.
9083         if (User->getOpcode() == ISD::BR) {
9084           SDValue FalseBB = User->getOperand(1);
9085           SDNode *NewBR =
9086             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9087           assert(NewBR == User);
9088           (void)NewBR;
9089
9090           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9091                                     Cond.getOperand(0), Cond.getOperand(1));
9092           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9093           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9094                               Chain, Dest, CC, Cmp);
9095           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9096           Cond = Cmp;
9097           addTest = false;
9098           Dest = FalseBB;
9099         }
9100       }
9101     }
9102   }
9103
9104   if (addTest) {
9105     // Look pass the truncate.
9106     if (Cond.getOpcode() == ISD::TRUNCATE)
9107       Cond = Cond.getOperand(0);
9108
9109     // We know the result of AND is compared against zero. Try to match
9110     // it to BT.
9111     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9112       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9113       if (NewSetCC.getNode()) {
9114         CC = NewSetCC.getOperand(0);
9115         Cond = NewSetCC.getOperand(1);
9116         addTest = false;
9117       }
9118     }
9119   }
9120
9121   if (addTest) {
9122     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9123     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9124   }
9125   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9126                      Chain, Dest, CC, Cond);
9127 }
9128
9129
9130 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9131 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9132 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9133 // that the guard pages used by the OS virtual memory manager are allocated in
9134 // correct sequence.
9135 SDValue
9136 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9137                                            SelectionDAG &DAG) const {
9138   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9139           EnableSegmentedStacks) &&
9140          "This should be used only on Windows targets or when segmented stacks "
9141          "are being used");
9142   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9143   DebugLoc dl = Op.getDebugLoc();
9144
9145   // Get the inputs.
9146   SDValue Chain = Op.getOperand(0);
9147   SDValue Size  = Op.getOperand(1);
9148   // FIXME: Ensure alignment here
9149
9150   bool Is64Bit = Subtarget->is64Bit();
9151   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9152
9153   if (EnableSegmentedStacks) {
9154     MachineFunction &MF = DAG.getMachineFunction();
9155     MachineRegisterInfo &MRI = MF.getRegInfo();
9156
9157     if (Is64Bit) {
9158       // The 64 bit implementation of segmented stacks needs to clobber both r10
9159       // r11. This makes it impossible to use it along with nested parameters.
9160       const Function *F = MF.getFunction();
9161
9162       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9163            I != E; I++)
9164         if (I->hasNestAttr())
9165           report_fatal_error("Cannot use segmented stacks with functions that "
9166                              "have nested arguments.");
9167     }
9168
9169     const TargetRegisterClass *AddrRegClass =
9170       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9171     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9172     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9173     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9174                                 DAG.getRegister(Vreg, SPTy));
9175     SDValue Ops1[2] = { Value, Chain };
9176     return DAG.getMergeValues(Ops1, 2, dl);
9177   } else {
9178     SDValue Flag;
9179     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9180
9181     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9182     Flag = Chain.getValue(1);
9183     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9184
9185     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9186     Flag = Chain.getValue(1);
9187
9188     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9189
9190     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9191     return DAG.getMergeValues(Ops1, 2, dl);
9192   }
9193 }
9194
9195 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9196   MachineFunction &MF = DAG.getMachineFunction();
9197   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9198
9199   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9200   DebugLoc DL = Op.getDebugLoc();
9201
9202   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9203     // vastart just stores the address of the VarArgsFrameIndex slot into the
9204     // memory location argument.
9205     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9206                                    getPointerTy());
9207     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9208                         MachinePointerInfo(SV), false, false, 0);
9209   }
9210
9211   // __va_list_tag:
9212   //   gp_offset         (0 - 6 * 8)
9213   //   fp_offset         (48 - 48 + 8 * 16)
9214   //   overflow_arg_area (point to parameters coming in memory).
9215   //   reg_save_area
9216   SmallVector<SDValue, 8> MemOps;
9217   SDValue FIN = Op.getOperand(1);
9218   // Store gp_offset
9219   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9220                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9221                                                MVT::i32),
9222                                FIN, MachinePointerInfo(SV), false, false, 0);
9223   MemOps.push_back(Store);
9224
9225   // Store fp_offset
9226   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9227                     FIN, DAG.getIntPtrConstant(4));
9228   Store = DAG.getStore(Op.getOperand(0), DL,
9229                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9230                                        MVT::i32),
9231                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9232   MemOps.push_back(Store);
9233
9234   // Store ptr to overflow_arg_area
9235   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9236                     FIN, DAG.getIntPtrConstant(4));
9237   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9238                                     getPointerTy());
9239   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9240                        MachinePointerInfo(SV, 8),
9241                        false, false, 0);
9242   MemOps.push_back(Store);
9243
9244   // Store ptr to reg_save_area.
9245   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9246                     FIN, DAG.getIntPtrConstant(8));
9247   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9248                                     getPointerTy());
9249   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9250                        MachinePointerInfo(SV, 16), false, false, 0);
9251   MemOps.push_back(Store);
9252   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9253                      &MemOps[0], MemOps.size());
9254 }
9255
9256 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9257   assert(Subtarget->is64Bit() &&
9258          "LowerVAARG only handles 64-bit va_arg!");
9259   assert((Subtarget->isTargetLinux() ||
9260           Subtarget->isTargetDarwin()) &&
9261           "Unhandled target in LowerVAARG");
9262   assert(Op.getNode()->getNumOperands() == 4);
9263   SDValue Chain = Op.getOperand(0);
9264   SDValue SrcPtr = Op.getOperand(1);
9265   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9266   unsigned Align = Op.getConstantOperandVal(3);
9267   DebugLoc dl = Op.getDebugLoc();
9268
9269   EVT ArgVT = Op.getNode()->getValueType(0);
9270   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9271   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9272   uint8_t ArgMode;
9273
9274   // Decide which area this value should be read from.
9275   // TODO: Implement the AMD64 ABI in its entirety. This simple
9276   // selection mechanism works only for the basic types.
9277   if (ArgVT == MVT::f80) {
9278     llvm_unreachable("va_arg for f80 not yet implemented");
9279   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9280     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9281   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9282     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9283   } else {
9284     llvm_unreachable("Unhandled argument type in LowerVAARG");
9285   }
9286
9287   if (ArgMode == 2) {
9288     // Sanity Check: Make sure using fp_offset makes sense.
9289     assert(!UseSoftFloat &&
9290            !(DAG.getMachineFunction()
9291                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9292            Subtarget->hasXMM());
9293   }
9294
9295   // Insert VAARG_64 node into the DAG
9296   // VAARG_64 returns two values: Variable Argument Address, Chain
9297   SmallVector<SDValue, 11> InstOps;
9298   InstOps.push_back(Chain);
9299   InstOps.push_back(SrcPtr);
9300   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9301   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9302   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9303   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9304   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9305                                           VTs, &InstOps[0], InstOps.size(),
9306                                           MVT::i64,
9307                                           MachinePointerInfo(SV),
9308                                           /*Align=*/0,
9309                                           /*Volatile=*/false,
9310                                           /*ReadMem=*/true,
9311                                           /*WriteMem=*/true);
9312   Chain = VAARG.getValue(1);
9313
9314   // Load the next argument and return it
9315   return DAG.getLoad(ArgVT, dl,
9316                      Chain,
9317                      VAARG,
9318                      MachinePointerInfo(),
9319                      false, false, false, 0);
9320 }
9321
9322 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9323   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9324   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9325   SDValue Chain = Op.getOperand(0);
9326   SDValue DstPtr = Op.getOperand(1);
9327   SDValue SrcPtr = Op.getOperand(2);
9328   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9329   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9330   DebugLoc DL = Op.getDebugLoc();
9331
9332   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9333                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9334                        false,
9335                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9336 }
9337
9338 SDValue
9339 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9340   DebugLoc dl = Op.getDebugLoc();
9341   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9342   switch (IntNo) {
9343   default: return SDValue();    // Don't custom lower most intrinsics.
9344   // Comparison intrinsics.
9345   case Intrinsic::x86_sse_comieq_ss:
9346   case Intrinsic::x86_sse_comilt_ss:
9347   case Intrinsic::x86_sse_comile_ss:
9348   case Intrinsic::x86_sse_comigt_ss:
9349   case Intrinsic::x86_sse_comige_ss:
9350   case Intrinsic::x86_sse_comineq_ss:
9351   case Intrinsic::x86_sse_ucomieq_ss:
9352   case Intrinsic::x86_sse_ucomilt_ss:
9353   case Intrinsic::x86_sse_ucomile_ss:
9354   case Intrinsic::x86_sse_ucomigt_ss:
9355   case Intrinsic::x86_sse_ucomige_ss:
9356   case Intrinsic::x86_sse_ucomineq_ss:
9357   case Intrinsic::x86_sse2_comieq_sd:
9358   case Intrinsic::x86_sse2_comilt_sd:
9359   case Intrinsic::x86_sse2_comile_sd:
9360   case Intrinsic::x86_sse2_comigt_sd:
9361   case Intrinsic::x86_sse2_comige_sd:
9362   case Intrinsic::x86_sse2_comineq_sd:
9363   case Intrinsic::x86_sse2_ucomieq_sd:
9364   case Intrinsic::x86_sse2_ucomilt_sd:
9365   case Intrinsic::x86_sse2_ucomile_sd:
9366   case Intrinsic::x86_sse2_ucomigt_sd:
9367   case Intrinsic::x86_sse2_ucomige_sd:
9368   case Intrinsic::x86_sse2_ucomineq_sd: {
9369     unsigned Opc = 0;
9370     ISD::CondCode CC = ISD::SETCC_INVALID;
9371     switch (IntNo) {
9372     default: break;
9373     case Intrinsic::x86_sse_comieq_ss:
9374     case Intrinsic::x86_sse2_comieq_sd:
9375       Opc = X86ISD::COMI;
9376       CC = ISD::SETEQ;
9377       break;
9378     case Intrinsic::x86_sse_comilt_ss:
9379     case Intrinsic::x86_sse2_comilt_sd:
9380       Opc = X86ISD::COMI;
9381       CC = ISD::SETLT;
9382       break;
9383     case Intrinsic::x86_sse_comile_ss:
9384     case Intrinsic::x86_sse2_comile_sd:
9385       Opc = X86ISD::COMI;
9386       CC = ISD::SETLE;
9387       break;
9388     case Intrinsic::x86_sse_comigt_ss:
9389     case Intrinsic::x86_sse2_comigt_sd:
9390       Opc = X86ISD::COMI;
9391       CC = ISD::SETGT;
9392       break;
9393     case Intrinsic::x86_sse_comige_ss:
9394     case Intrinsic::x86_sse2_comige_sd:
9395       Opc = X86ISD::COMI;
9396       CC = ISD::SETGE;
9397       break;
9398     case Intrinsic::x86_sse_comineq_ss:
9399     case Intrinsic::x86_sse2_comineq_sd:
9400       Opc = X86ISD::COMI;
9401       CC = ISD::SETNE;
9402       break;
9403     case Intrinsic::x86_sse_ucomieq_ss:
9404     case Intrinsic::x86_sse2_ucomieq_sd:
9405       Opc = X86ISD::UCOMI;
9406       CC = ISD::SETEQ;
9407       break;
9408     case Intrinsic::x86_sse_ucomilt_ss:
9409     case Intrinsic::x86_sse2_ucomilt_sd:
9410       Opc = X86ISD::UCOMI;
9411       CC = ISD::SETLT;
9412       break;
9413     case Intrinsic::x86_sse_ucomile_ss:
9414     case Intrinsic::x86_sse2_ucomile_sd:
9415       Opc = X86ISD::UCOMI;
9416       CC = ISD::SETLE;
9417       break;
9418     case Intrinsic::x86_sse_ucomigt_ss:
9419     case Intrinsic::x86_sse2_ucomigt_sd:
9420       Opc = X86ISD::UCOMI;
9421       CC = ISD::SETGT;
9422       break;
9423     case Intrinsic::x86_sse_ucomige_ss:
9424     case Intrinsic::x86_sse2_ucomige_sd:
9425       Opc = X86ISD::UCOMI;
9426       CC = ISD::SETGE;
9427       break;
9428     case Intrinsic::x86_sse_ucomineq_ss:
9429     case Intrinsic::x86_sse2_ucomineq_sd:
9430       Opc = X86ISD::UCOMI;
9431       CC = ISD::SETNE;
9432       break;
9433     }
9434
9435     SDValue LHS = Op.getOperand(1);
9436     SDValue RHS = Op.getOperand(2);
9437     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9438     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9439     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9440     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9441                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9442     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9443   }
9444   // Arithmetic intrinsics.
9445   case Intrinsic::x86_sse3_hadd_ps:
9446   case Intrinsic::x86_sse3_hadd_pd:
9447   case Intrinsic::x86_avx_hadd_ps_256:
9448   case Intrinsic::x86_avx_hadd_pd_256:
9449     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9450                        Op.getOperand(1), Op.getOperand(2));
9451   case Intrinsic::x86_sse3_hsub_ps:
9452   case Intrinsic::x86_sse3_hsub_pd:
9453   case Intrinsic::x86_avx_hsub_ps_256:
9454   case Intrinsic::x86_avx_hsub_pd_256:
9455     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9456                        Op.getOperand(1), Op.getOperand(2));
9457   // ptest and testp intrinsics. The intrinsic these come from are designed to
9458   // return an integer value, not just an instruction so lower it to the ptest
9459   // or testp pattern and a setcc for the result.
9460   case Intrinsic::x86_sse41_ptestz:
9461   case Intrinsic::x86_sse41_ptestc:
9462   case Intrinsic::x86_sse41_ptestnzc:
9463   case Intrinsic::x86_avx_ptestz_256:
9464   case Intrinsic::x86_avx_ptestc_256:
9465   case Intrinsic::x86_avx_ptestnzc_256:
9466   case Intrinsic::x86_avx_vtestz_ps:
9467   case Intrinsic::x86_avx_vtestc_ps:
9468   case Intrinsic::x86_avx_vtestnzc_ps:
9469   case Intrinsic::x86_avx_vtestz_pd:
9470   case Intrinsic::x86_avx_vtestc_pd:
9471   case Intrinsic::x86_avx_vtestnzc_pd:
9472   case Intrinsic::x86_avx_vtestz_ps_256:
9473   case Intrinsic::x86_avx_vtestc_ps_256:
9474   case Intrinsic::x86_avx_vtestnzc_ps_256:
9475   case Intrinsic::x86_avx_vtestz_pd_256:
9476   case Intrinsic::x86_avx_vtestc_pd_256:
9477   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9478     bool IsTestPacked = false;
9479     unsigned X86CC = 0;
9480     switch (IntNo) {
9481     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9482     case Intrinsic::x86_avx_vtestz_ps:
9483     case Intrinsic::x86_avx_vtestz_pd:
9484     case Intrinsic::x86_avx_vtestz_ps_256:
9485     case Intrinsic::x86_avx_vtestz_pd_256:
9486       IsTestPacked = true; // Fallthrough
9487     case Intrinsic::x86_sse41_ptestz:
9488     case Intrinsic::x86_avx_ptestz_256:
9489       // ZF = 1
9490       X86CC = X86::COND_E;
9491       break;
9492     case Intrinsic::x86_avx_vtestc_ps:
9493     case Intrinsic::x86_avx_vtestc_pd:
9494     case Intrinsic::x86_avx_vtestc_ps_256:
9495     case Intrinsic::x86_avx_vtestc_pd_256:
9496       IsTestPacked = true; // Fallthrough
9497     case Intrinsic::x86_sse41_ptestc:
9498     case Intrinsic::x86_avx_ptestc_256:
9499       // CF = 1
9500       X86CC = X86::COND_B;
9501       break;
9502     case Intrinsic::x86_avx_vtestnzc_ps:
9503     case Intrinsic::x86_avx_vtestnzc_pd:
9504     case Intrinsic::x86_avx_vtestnzc_ps_256:
9505     case Intrinsic::x86_avx_vtestnzc_pd_256:
9506       IsTestPacked = true; // Fallthrough
9507     case Intrinsic::x86_sse41_ptestnzc:
9508     case Intrinsic::x86_avx_ptestnzc_256:
9509       // ZF and CF = 0
9510       X86CC = X86::COND_A;
9511       break;
9512     }
9513
9514     SDValue LHS = Op.getOperand(1);
9515     SDValue RHS = Op.getOperand(2);
9516     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9517     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9518     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9519     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9520     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9521   }
9522
9523   // Fix vector shift instructions where the last operand is a non-immediate
9524   // i32 value.
9525   case Intrinsic::x86_sse2_pslli_w:
9526   case Intrinsic::x86_sse2_pslli_d:
9527   case Intrinsic::x86_sse2_pslli_q:
9528   case Intrinsic::x86_sse2_psrli_w:
9529   case Intrinsic::x86_sse2_psrli_d:
9530   case Intrinsic::x86_sse2_psrli_q:
9531   case Intrinsic::x86_sse2_psrai_w:
9532   case Intrinsic::x86_sse2_psrai_d:
9533   case Intrinsic::x86_mmx_pslli_w:
9534   case Intrinsic::x86_mmx_pslli_d:
9535   case Intrinsic::x86_mmx_pslli_q:
9536   case Intrinsic::x86_mmx_psrli_w:
9537   case Intrinsic::x86_mmx_psrli_d:
9538   case Intrinsic::x86_mmx_psrli_q:
9539   case Intrinsic::x86_mmx_psrai_w:
9540   case Intrinsic::x86_mmx_psrai_d: {
9541     SDValue ShAmt = Op.getOperand(2);
9542     if (isa<ConstantSDNode>(ShAmt))
9543       return SDValue();
9544
9545     unsigned NewIntNo = 0;
9546     EVT ShAmtVT = MVT::v4i32;
9547     switch (IntNo) {
9548     case Intrinsic::x86_sse2_pslli_w:
9549       NewIntNo = Intrinsic::x86_sse2_psll_w;
9550       break;
9551     case Intrinsic::x86_sse2_pslli_d:
9552       NewIntNo = Intrinsic::x86_sse2_psll_d;
9553       break;
9554     case Intrinsic::x86_sse2_pslli_q:
9555       NewIntNo = Intrinsic::x86_sse2_psll_q;
9556       break;
9557     case Intrinsic::x86_sse2_psrli_w:
9558       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9559       break;
9560     case Intrinsic::x86_sse2_psrli_d:
9561       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9562       break;
9563     case Intrinsic::x86_sse2_psrli_q:
9564       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9565       break;
9566     case Intrinsic::x86_sse2_psrai_w:
9567       NewIntNo = Intrinsic::x86_sse2_psra_w;
9568       break;
9569     case Intrinsic::x86_sse2_psrai_d:
9570       NewIntNo = Intrinsic::x86_sse2_psra_d;
9571       break;
9572     default: {
9573       ShAmtVT = MVT::v2i32;
9574       switch (IntNo) {
9575       case Intrinsic::x86_mmx_pslli_w:
9576         NewIntNo = Intrinsic::x86_mmx_psll_w;
9577         break;
9578       case Intrinsic::x86_mmx_pslli_d:
9579         NewIntNo = Intrinsic::x86_mmx_psll_d;
9580         break;
9581       case Intrinsic::x86_mmx_pslli_q:
9582         NewIntNo = Intrinsic::x86_mmx_psll_q;
9583         break;
9584       case Intrinsic::x86_mmx_psrli_w:
9585         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9586         break;
9587       case Intrinsic::x86_mmx_psrli_d:
9588         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9589         break;
9590       case Intrinsic::x86_mmx_psrli_q:
9591         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9592         break;
9593       case Intrinsic::x86_mmx_psrai_w:
9594         NewIntNo = Intrinsic::x86_mmx_psra_w;
9595         break;
9596       case Intrinsic::x86_mmx_psrai_d:
9597         NewIntNo = Intrinsic::x86_mmx_psra_d;
9598         break;
9599       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9600       }
9601       break;
9602     }
9603     }
9604
9605     // The vector shift intrinsics with scalars uses 32b shift amounts but
9606     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9607     // to be zero.
9608     SDValue ShOps[4];
9609     ShOps[0] = ShAmt;
9610     ShOps[1] = DAG.getConstant(0, MVT::i32);
9611     if (ShAmtVT == MVT::v4i32) {
9612       ShOps[2] = DAG.getUNDEF(MVT::i32);
9613       ShOps[3] = DAG.getUNDEF(MVT::i32);
9614       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9615     } else {
9616       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9617 // FIXME this must be lowered to get rid of the invalid type.
9618     }
9619
9620     EVT VT = Op.getValueType();
9621     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9622     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9623                        DAG.getConstant(NewIntNo, MVT::i32),
9624                        Op.getOperand(1), ShAmt);
9625   }
9626   }
9627 }
9628
9629 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9630                                            SelectionDAG &DAG) const {
9631   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9632   MFI->setReturnAddressIsTaken(true);
9633
9634   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9635   DebugLoc dl = Op.getDebugLoc();
9636
9637   if (Depth > 0) {
9638     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9639     SDValue Offset =
9640       DAG.getConstant(TD->getPointerSize(),
9641                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9642     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9643                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9644                                    FrameAddr, Offset),
9645                        MachinePointerInfo(), false, false, false, 0);
9646   }
9647
9648   // Just load the return address.
9649   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9650   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9651                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9652 }
9653
9654 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9655   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9656   MFI->setFrameAddressIsTaken(true);
9657
9658   EVT VT = Op.getValueType();
9659   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9660   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9661   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9662   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9663   while (Depth--)
9664     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9665                             MachinePointerInfo(),
9666                             false, false, false, 0);
9667   return FrameAddr;
9668 }
9669
9670 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9671                                                      SelectionDAG &DAG) const {
9672   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9673 }
9674
9675 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9676   MachineFunction &MF = DAG.getMachineFunction();
9677   SDValue Chain     = Op.getOperand(0);
9678   SDValue Offset    = Op.getOperand(1);
9679   SDValue Handler   = Op.getOperand(2);
9680   DebugLoc dl       = Op.getDebugLoc();
9681
9682   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9683                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9684                                      getPointerTy());
9685   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9686
9687   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9688                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9689   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9690   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9691                        false, false, 0);
9692   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9693   MF.getRegInfo().addLiveOut(StoreAddrReg);
9694
9695   return DAG.getNode(X86ISD::EH_RETURN, dl,
9696                      MVT::Other,
9697                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9698 }
9699
9700 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9701                                                   SelectionDAG &DAG) const {
9702   return Op.getOperand(0);
9703 }
9704
9705 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9706                                                 SelectionDAG &DAG) const {
9707   SDValue Root = Op.getOperand(0);
9708   SDValue Trmp = Op.getOperand(1); // trampoline
9709   SDValue FPtr = Op.getOperand(2); // nested function
9710   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9711   DebugLoc dl  = Op.getDebugLoc();
9712
9713   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9714
9715   if (Subtarget->is64Bit()) {
9716     SDValue OutChains[6];
9717
9718     // Large code-model.
9719     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9720     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9721
9722     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9723     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9724
9725     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9726
9727     // Load the pointer to the nested function into R11.
9728     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9729     SDValue Addr = Trmp;
9730     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9731                                 Addr, MachinePointerInfo(TrmpAddr),
9732                                 false, false, 0);
9733
9734     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9735                        DAG.getConstant(2, MVT::i64));
9736     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9737                                 MachinePointerInfo(TrmpAddr, 2),
9738                                 false, false, 2);
9739
9740     // Load the 'nest' parameter value into R10.
9741     // R10 is specified in X86CallingConv.td
9742     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9743     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9744                        DAG.getConstant(10, MVT::i64));
9745     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9746                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9747                                 false, false, 0);
9748
9749     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9750                        DAG.getConstant(12, MVT::i64));
9751     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9752                                 MachinePointerInfo(TrmpAddr, 12),
9753                                 false, false, 2);
9754
9755     // Jump to the nested function.
9756     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9757     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9758                        DAG.getConstant(20, MVT::i64));
9759     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9760                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9761                                 false, false, 0);
9762
9763     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9764     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9765                        DAG.getConstant(22, MVT::i64));
9766     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9767                                 MachinePointerInfo(TrmpAddr, 22),
9768                                 false, false, 0);
9769
9770     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9771   } else {
9772     const Function *Func =
9773       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9774     CallingConv::ID CC = Func->getCallingConv();
9775     unsigned NestReg;
9776
9777     switch (CC) {
9778     default:
9779       llvm_unreachable("Unsupported calling convention");
9780     case CallingConv::C:
9781     case CallingConv::X86_StdCall: {
9782       // Pass 'nest' parameter in ECX.
9783       // Must be kept in sync with X86CallingConv.td
9784       NestReg = X86::ECX;
9785
9786       // Check that ECX wasn't needed by an 'inreg' parameter.
9787       FunctionType *FTy = Func->getFunctionType();
9788       const AttrListPtr &Attrs = Func->getAttributes();
9789
9790       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9791         unsigned InRegCount = 0;
9792         unsigned Idx = 1;
9793
9794         for (FunctionType::param_iterator I = FTy->param_begin(),
9795              E = FTy->param_end(); I != E; ++I, ++Idx)
9796           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9797             // FIXME: should only count parameters that are lowered to integers.
9798             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9799
9800         if (InRegCount > 2) {
9801           report_fatal_error("Nest register in use - reduce number of inreg"
9802                              " parameters!");
9803         }
9804       }
9805       break;
9806     }
9807     case CallingConv::X86_FastCall:
9808     case CallingConv::X86_ThisCall:
9809     case CallingConv::Fast:
9810       // Pass 'nest' parameter in EAX.
9811       // Must be kept in sync with X86CallingConv.td
9812       NestReg = X86::EAX;
9813       break;
9814     }
9815
9816     SDValue OutChains[4];
9817     SDValue Addr, Disp;
9818
9819     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9820                        DAG.getConstant(10, MVT::i32));
9821     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9822
9823     // This is storing the opcode for MOV32ri.
9824     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9825     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9826     OutChains[0] = DAG.getStore(Root, dl,
9827                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9828                                 Trmp, MachinePointerInfo(TrmpAddr),
9829                                 false, false, 0);
9830
9831     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9832                        DAG.getConstant(1, MVT::i32));
9833     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9834                                 MachinePointerInfo(TrmpAddr, 1),
9835                                 false, false, 1);
9836
9837     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9838     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9839                        DAG.getConstant(5, MVT::i32));
9840     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9841                                 MachinePointerInfo(TrmpAddr, 5),
9842                                 false, false, 1);
9843
9844     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9845                        DAG.getConstant(6, MVT::i32));
9846     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9847                                 MachinePointerInfo(TrmpAddr, 6),
9848                                 false, false, 1);
9849
9850     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9851   }
9852 }
9853
9854 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9855                                             SelectionDAG &DAG) const {
9856   /*
9857    The rounding mode is in bits 11:10 of FPSR, and has the following
9858    settings:
9859      00 Round to nearest
9860      01 Round to -inf
9861      10 Round to +inf
9862      11 Round to 0
9863
9864   FLT_ROUNDS, on the other hand, expects the following:
9865     -1 Undefined
9866      0 Round to 0
9867      1 Round to nearest
9868      2 Round to +inf
9869      3 Round to -inf
9870
9871   To perform the conversion, we do:
9872     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9873   */
9874
9875   MachineFunction &MF = DAG.getMachineFunction();
9876   const TargetMachine &TM = MF.getTarget();
9877   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9878   unsigned StackAlignment = TFI.getStackAlignment();
9879   EVT VT = Op.getValueType();
9880   DebugLoc DL = Op.getDebugLoc();
9881
9882   // Save FP Control Word to stack slot
9883   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9884   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9885
9886
9887   MachineMemOperand *MMO =
9888    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9889                            MachineMemOperand::MOStore, 2, 2);
9890
9891   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9892   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9893                                           DAG.getVTList(MVT::Other),
9894                                           Ops, 2, MVT::i16, MMO);
9895
9896   // Load FP Control Word from stack slot
9897   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9898                             MachinePointerInfo(), false, false, false, 0);
9899
9900   // Transform as necessary
9901   SDValue CWD1 =
9902     DAG.getNode(ISD::SRL, DL, MVT::i16,
9903                 DAG.getNode(ISD::AND, DL, MVT::i16,
9904                             CWD, DAG.getConstant(0x800, MVT::i16)),
9905                 DAG.getConstant(11, MVT::i8));
9906   SDValue CWD2 =
9907     DAG.getNode(ISD::SRL, DL, MVT::i16,
9908                 DAG.getNode(ISD::AND, DL, MVT::i16,
9909                             CWD, DAG.getConstant(0x400, MVT::i16)),
9910                 DAG.getConstant(9, MVT::i8));
9911
9912   SDValue RetVal =
9913     DAG.getNode(ISD::AND, DL, MVT::i16,
9914                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9915                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9916                             DAG.getConstant(1, MVT::i16)),
9917                 DAG.getConstant(3, MVT::i16));
9918
9919
9920   return DAG.getNode((VT.getSizeInBits() < 16 ?
9921                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9922 }
9923
9924 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9925   EVT VT = Op.getValueType();
9926   EVT OpVT = VT;
9927   unsigned NumBits = VT.getSizeInBits();
9928   DebugLoc dl = Op.getDebugLoc();
9929
9930   Op = Op.getOperand(0);
9931   if (VT == MVT::i8) {
9932     // Zero extend to i32 since there is not an i8 bsr.
9933     OpVT = MVT::i32;
9934     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9935   }
9936
9937   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9938   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9939   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9940
9941   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9942   SDValue Ops[] = {
9943     Op,
9944     DAG.getConstant(NumBits+NumBits-1, OpVT),
9945     DAG.getConstant(X86::COND_E, MVT::i8),
9946     Op.getValue(1)
9947   };
9948   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9949
9950   // Finally xor with NumBits-1.
9951   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9952
9953   if (VT == MVT::i8)
9954     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9955   return Op;
9956 }
9957
9958 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9959   EVT VT = Op.getValueType();
9960   EVT OpVT = VT;
9961   unsigned NumBits = VT.getSizeInBits();
9962   DebugLoc dl = Op.getDebugLoc();
9963
9964   Op = Op.getOperand(0);
9965   if (VT == MVT::i8) {
9966     OpVT = MVT::i32;
9967     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9968   }
9969
9970   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9971   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9972   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9973
9974   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9975   SDValue Ops[] = {
9976     Op,
9977     DAG.getConstant(NumBits, OpVT),
9978     DAG.getConstant(X86::COND_E, MVT::i8),
9979     Op.getValue(1)
9980   };
9981   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9982
9983   if (VT == MVT::i8)
9984     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9985   return Op;
9986 }
9987
9988 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9989 // ones, and then concatenate the result back.
9990 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9991   EVT VT = Op.getValueType();
9992
9993   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9994          "Unsupported value type for operation");
9995
9996   int NumElems = VT.getVectorNumElements();
9997   DebugLoc dl = Op.getDebugLoc();
9998   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9999   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10000
10001   // Extract the LHS vectors
10002   SDValue LHS = Op.getOperand(0);
10003   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10004   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10005
10006   // Extract the RHS vectors
10007   SDValue RHS = Op.getOperand(1);
10008   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10009   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10010
10011   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10012   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10013
10014   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10015                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10016                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10017 }
10018
10019 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10020   assert(Op.getValueType().getSizeInBits() == 256 &&
10021          Op.getValueType().isInteger() &&
10022          "Only handle AVX 256-bit vector integer operation");
10023   return Lower256IntArith(Op, DAG);
10024 }
10025
10026 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10027   assert(Op.getValueType().getSizeInBits() == 256 &&
10028          Op.getValueType().isInteger() &&
10029          "Only handle AVX 256-bit vector integer operation");
10030   return Lower256IntArith(Op, DAG);
10031 }
10032
10033 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10034   EVT VT = Op.getValueType();
10035
10036   // Decompose 256-bit ops into smaller 128-bit ops.
10037   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10038     return Lower256IntArith(Op, DAG);
10039
10040   DebugLoc dl = Op.getDebugLoc();
10041
10042   SDValue A = Op.getOperand(0);
10043   SDValue B = Op.getOperand(1);
10044
10045   if (VT == MVT::v4i64) {
10046     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10047
10048     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10049     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10050     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10051     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10052     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10053     //
10054     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10055     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10056     //  return AloBlo + AloBhi + AhiBlo;
10057
10058     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10059                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10060                          A, DAG.getConstant(32, MVT::i32));
10061     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10062                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10063                          B, DAG.getConstant(32, MVT::i32));
10064     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10065                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10066                          A, B);
10067     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10068                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10069                          A, Bhi);
10070     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10071                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10072                          Ahi, B);
10073     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10074                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10075                          AloBhi, DAG.getConstant(32, MVT::i32));
10076     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10077                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10078                          AhiBlo, DAG.getConstant(32, MVT::i32));
10079     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10080     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10081     return Res;
10082   }
10083
10084   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10085
10086   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10087   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10088   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10089   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10090   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10091   //
10092   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10093   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10094   //  return AloBlo + AloBhi + AhiBlo;
10095
10096   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10097                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10098                        A, DAG.getConstant(32, MVT::i32));
10099   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10100                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10101                        B, DAG.getConstant(32, MVT::i32));
10102   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10103                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10104                        A, B);
10105   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10106                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10107                        A, Bhi);
10108   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10109                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10110                        Ahi, B);
10111   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10112                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10113                        AloBhi, DAG.getConstant(32, MVT::i32));
10114   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10115                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10116                        AhiBlo, DAG.getConstant(32, MVT::i32));
10117   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10118   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10119   return Res;
10120 }
10121
10122 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10123
10124   EVT VT = Op.getValueType();
10125   DebugLoc dl = Op.getDebugLoc();
10126   SDValue R = Op.getOperand(0);
10127   SDValue Amt = Op.getOperand(1);
10128   LLVMContext *Context = DAG.getContext();
10129
10130   if (!Subtarget->hasXMMInt())
10131     return SDValue();
10132
10133   // Decompose 256-bit shifts into smaller 128-bit shifts.
10134   if (VT.getSizeInBits() == 256) {
10135     int NumElems = VT.getVectorNumElements();
10136     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10137     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10138
10139     // Extract the two vectors
10140     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10141     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10142                                      DAG, dl);
10143
10144     // Recreate the shift amount vectors
10145     SDValue Amt1, Amt2;
10146     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10147       // Constant shift amount
10148       SmallVector<SDValue, 4> Amt1Csts;
10149       SmallVector<SDValue, 4> Amt2Csts;
10150       for (int i = 0; i < NumElems/2; ++i)
10151         Amt1Csts.push_back(Amt->getOperand(i));
10152       for (int i = NumElems/2; i < NumElems; ++i)
10153         Amt2Csts.push_back(Amt->getOperand(i));
10154
10155       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10156                                  &Amt1Csts[0], NumElems/2);
10157       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10158                                  &Amt2Csts[0], NumElems/2);
10159     } else {
10160       // Variable shift amount
10161       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10162       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10163                                  DAG, dl);
10164     }
10165
10166     // Issue new vector shifts for the smaller types
10167     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10168     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10169
10170     // Concatenate the result back
10171     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10172   }
10173
10174   // Optimize shl/srl/sra with constant shift amount.
10175   if (isSplatVector(Amt.getNode())) {
10176     SDValue SclrAmt = Amt->getOperand(0);
10177     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10178       uint64_t ShiftAmt = C->getZExtValue();
10179
10180       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10181         // Make a large shift.
10182         SDValue SHL =
10183           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10184                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10185                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10186         // Zero out the rightmost bits.
10187         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10188                                                        MVT::i8));
10189         return DAG.getNode(ISD::AND, dl, VT, SHL,
10190                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10191       }
10192
10193       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10194        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10195                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10196                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10197
10198       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10199        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10200                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10201                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10202
10203       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10204        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10205                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10206                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10207
10208       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10209         // Make a large shift.
10210         SDValue SRL =
10211           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10212                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10213                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10214         // Zero out the leftmost bits.
10215         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10216                                                        MVT::i8));
10217         return DAG.getNode(ISD::AND, dl, VT, SRL,
10218                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10219       }
10220
10221       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10222        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10223                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10224                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10225
10226       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10227        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10228                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10229                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10230
10231       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10232        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10233                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10234                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10235
10236       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10237        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10238                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10239                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10240
10241       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10242        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10243                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10244                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10245
10246       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10247         if (ShiftAmt == 7) {
10248           // R s>> 7  ===  R s< 0
10249           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10250           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10251         }
10252
10253         // R s>> a === ((R u>> a) ^ m) - m
10254         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10255         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10256                                                        MVT::i8));
10257         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10258         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10259         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10260         return Res;
10261       }
10262     }
10263   }
10264
10265   // Lower SHL with variable shift amount.
10266   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10267     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10268                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10269                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10270
10271     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10272
10273     std::vector<Constant*> CV(4, CI);
10274     Constant *C = ConstantVector::get(CV);
10275     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10276     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10277                                  MachinePointerInfo::getConstantPool(),
10278                                  false, false, false, 16);
10279
10280     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10281     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10282     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10283     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10284   }
10285   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10286     // a = a << 5;
10287     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10288                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10289                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10290
10291     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10292     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10293
10294     std::vector<Constant*> CVM1(16, CM1);
10295     std::vector<Constant*> CVM2(16, CM2);
10296     Constant *C = ConstantVector::get(CVM1);
10297     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10298     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10299                             MachinePointerInfo::getConstantPool(),
10300                             false, false, false, 16);
10301
10302     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10303     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10304     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10305                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10306                     DAG.getConstant(4, MVT::i32));
10307     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10308     // a += a
10309     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10310
10311     C = ConstantVector::get(CVM2);
10312     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10313     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10314                     MachinePointerInfo::getConstantPool(),
10315                     false, false, false, 16);
10316
10317     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10318     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10319     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10320                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10321                     DAG.getConstant(2, MVT::i32));
10322     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10323     // a += a
10324     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10325
10326     // return pblendv(r, r+r, a);
10327     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10328                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10329     return R;
10330   }
10331   return SDValue();
10332 }
10333
10334 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10335   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10336   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10337   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10338   // has only one use.
10339   SDNode *N = Op.getNode();
10340   SDValue LHS = N->getOperand(0);
10341   SDValue RHS = N->getOperand(1);
10342   unsigned BaseOp = 0;
10343   unsigned Cond = 0;
10344   DebugLoc DL = Op.getDebugLoc();
10345   switch (Op.getOpcode()) {
10346   default: llvm_unreachable("Unknown ovf instruction!");
10347   case ISD::SADDO:
10348     // A subtract of one will be selected as a INC. Note that INC doesn't
10349     // set CF, so we can't do this for UADDO.
10350     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10351       if (C->isOne()) {
10352         BaseOp = X86ISD::INC;
10353         Cond = X86::COND_O;
10354         break;
10355       }
10356     BaseOp = X86ISD::ADD;
10357     Cond = X86::COND_O;
10358     break;
10359   case ISD::UADDO:
10360     BaseOp = X86ISD::ADD;
10361     Cond = X86::COND_B;
10362     break;
10363   case ISD::SSUBO:
10364     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10365     // set CF, so we can't do this for USUBO.
10366     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10367       if (C->isOne()) {
10368         BaseOp = X86ISD::DEC;
10369         Cond = X86::COND_O;
10370         break;
10371       }
10372     BaseOp = X86ISD::SUB;
10373     Cond = X86::COND_O;
10374     break;
10375   case ISD::USUBO:
10376     BaseOp = X86ISD::SUB;
10377     Cond = X86::COND_B;
10378     break;
10379   case ISD::SMULO:
10380     BaseOp = X86ISD::SMUL;
10381     Cond = X86::COND_O;
10382     break;
10383   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10384     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10385                                  MVT::i32);
10386     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10387
10388     SDValue SetCC =
10389       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10390                   DAG.getConstant(X86::COND_O, MVT::i32),
10391                   SDValue(Sum.getNode(), 2));
10392
10393     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10394   }
10395   }
10396
10397   // Also sets EFLAGS.
10398   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10399   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10400
10401   SDValue SetCC =
10402     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10403                 DAG.getConstant(Cond, MVT::i32),
10404                 SDValue(Sum.getNode(), 1));
10405
10406   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10407 }
10408
10409 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10410   DebugLoc dl = Op.getDebugLoc();
10411   SDNode* Node = Op.getNode();
10412   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10413   EVT VT = Node->getValueType(0);
10414   if (Subtarget->hasXMMInt() && VT.isVector()) {
10415     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10416                         ExtraVT.getScalarType().getSizeInBits();
10417     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10418
10419     unsigned SHLIntrinsicsID = 0;
10420     unsigned SRAIntrinsicsID = 0;
10421     switch (VT.getSimpleVT().SimpleTy) {
10422       default:
10423         return SDValue();
10424       case MVT::v4i32: {
10425         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10426         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10427         break;
10428       }
10429       case MVT::v8i16: {
10430         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10431         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10432         break;
10433       }
10434     }
10435
10436     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10437                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10438                          Node->getOperand(0), ShAmt);
10439
10440     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10441                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10442                        Tmp1, ShAmt);
10443   }
10444
10445   return SDValue();
10446 }
10447
10448
10449 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10450   DebugLoc dl = Op.getDebugLoc();
10451
10452   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10453   // There isn't any reason to disable it if the target processor supports it.
10454   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10455     SDValue Chain = Op.getOperand(0);
10456     SDValue Zero = DAG.getConstant(0, MVT::i32);
10457     SDValue Ops[] = {
10458       DAG.getRegister(X86::ESP, MVT::i32), // Base
10459       DAG.getTargetConstant(1, MVT::i8),   // Scale
10460       DAG.getRegister(0, MVT::i32),        // Index
10461       DAG.getTargetConstant(0, MVT::i32),  // Disp
10462       DAG.getRegister(0, MVT::i32),        // Segment.
10463       Zero,
10464       Chain
10465     };
10466     SDNode *Res =
10467       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10468                           array_lengthof(Ops));
10469     return SDValue(Res, 0);
10470   }
10471
10472   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10473   if (!isDev)
10474     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10475
10476   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10477   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10478   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10479   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10480
10481   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10482   if (!Op1 && !Op2 && !Op3 && Op4)
10483     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10484
10485   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10486   if (Op1 && !Op2 && !Op3 && !Op4)
10487     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10488
10489   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10490   //           (MFENCE)>;
10491   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10492 }
10493
10494 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10495                                              SelectionDAG &DAG) const {
10496   DebugLoc dl = Op.getDebugLoc();
10497   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10498     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10499   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10500     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10501
10502   // The only fence that needs an instruction is a sequentially-consistent
10503   // cross-thread fence.
10504   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10505     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10506     // no-sse2). There isn't any reason to disable it if the target processor
10507     // supports it.
10508     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10509       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10510
10511     SDValue Chain = Op.getOperand(0);
10512     SDValue Zero = DAG.getConstant(0, MVT::i32);
10513     SDValue Ops[] = {
10514       DAG.getRegister(X86::ESP, MVT::i32), // Base
10515       DAG.getTargetConstant(1, MVT::i8),   // Scale
10516       DAG.getRegister(0, MVT::i32),        // Index
10517       DAG.getTargetConstant(0, MVT::i32),  // Disp
10518       DAG.getRegister(0, MVT::i32),        // Segment.
10519       Zero,
10520       Chain
10521     };
10522     SDNode *Res =
10523       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10524                          array_lengthof(Ops));
10525     return SDValue(Res, 0);
10526   }
10527
10528   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10529   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10530 }
10531
10532
10533 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10534   EVT T = Op.getValueType();
10535   DebugLoc DL = Op.getDebugLoc();
10536   unsigned Reg = 0;
10537   unsigned size = 0;
10538   switch(T.getSimpleVT().SimpleTy) {
10539   default:
10540     assert(false && "Invalid value type!");
10541   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10542   case MVT::i16: Reg = X86::AX;  size = 2; break;
10543   case MVT::i32: Reg = X86::EAX; size = 4; break;
10544   case MVT::i64:
10545     assert(Subtarget->is64Bit() && "Node not type legal!");
10546     Reg = X86::RAX; size = 8;
10547     break;
10548   }
10549   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10550                                     Op.getOperand(2), SDValue());
10551   SDValue Ops[] = { cpIn.getValue(0),
10552                     Op.getOperand(1),
10553                     Op.getOperand(3),
10554                     DAG.getTargetConstant(size, MVT::i8),
10555                     cpIn.getValue(1) };
10556   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10557   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10558   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10559                                            Ops, 5, T, MMO);
10560   SDValue cpOut =
10561     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10562   return cpOut;
10563 }
10564
10565 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10566                                                  SelectionDAG &DAG) const {
10567   assert(Subtarget->is64Bit() && "Result not type legalized?");
10568   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10569   SDValue TheChain = Op.getOperand(0);
10570   DebugLoc dl = Op.getDebugLoc();
10571   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10572   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10573   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10574                                    rax.getValue(2));
10575   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10576                             DAG.getConstant(32, MVT::i8));
10577   SDValue Ops[] = {
10578     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10579     rdx.getValue(1)
10580   };
10581   return DAG.getMergeValues(Ops, 2, dl);
10582 }
10583
10584 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10585                                             SelectionDAG &DAG) const {
10586   EVT SrcVT = Op.getOperand(0).getValueType();
10587   EVT DstVT = Op.getValueType();
10588   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10589          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10590   assert((DstVT == MVT::i64 ||
10591           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10592          "Unexpected custom BITCAST");
10593   // i64 <=> MMX conversions are Legal.
10594   if (SrcVT==MVT::i64 && DstVT.isVector())
10595     return Op;
10596   if (DstVT==MVT::i64 && SrcVT.isVector())
10597     return Op;
10598   // MMX <=> MMX conversions are Legal.
10599   if (SrcVT.isVector() && DstVT.isVector())
10600     return Op;
10601   // All other conversions need to be expanded.
10602   return SDValue();
10603 }
10604
10605 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10606   SDNode *Node = Op.getNode();
10607   DebugLoc dl = Node->getDebugLoc();
10608   EVT T = Node->getValueType(0);
10609   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10610                               DAG.getConstant(0, T), Node->getOperand(2));
10611   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10612                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10613                        Node->getOperand(0),
10614                        Node->getOperand(1), negOp,
10615                        cast<AtomicSDNode>(Node)->getSrcValue(),
10616                        cast<AtomicSDNode>(Node)->getAlignment(),
10617                        cast<AtomicSDNode>(Node)->getOrdering(),
10618                        cast<AtomicSDNode>(Node)->getSynchScope());
10619 }
10620
10621 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10622   SDNode *Node = Op.getNode();
10623   DebugLoc dl = Node->getDebugLoc();
10624   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10625
10626   // Convert seq_cst store -> xchg
10627   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10628   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10629   //        (The only way to get a 16-byte store is cmpxchg16b)
10630   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10631   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10632       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10633     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10634                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10635                                  Node->getOperand(0),
10636                                  Node->getOperand(1), Node->getOperand(2),
10637                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10638                                  cast<AtomicSDNode>(Node)->getOrdering(),
10639                                  cast<AtomicSDNode>(Node)->getSynchScope());
10640     return Swap.getValue(1);
10641   }
10642   // Other atomic stores have a simple pattern.
10643   return Op;
10644 }
10645
10646 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10647   EVT VT = Op.getNode()->getValueType(0);
10648
10649   // Let legalize expand this if it isn't a legal type yet.
10650   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10651     return SDValue();
10652
10653   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10654
10655   unsigned Opc;
10656   bool ExtraOp = false;
10657   switch (Op.getOpcode()) {
10658   default: assert(0 && "Invalid code");
10659   case ISD::ADDC: Opc = X86ISD::ADD; break;
10660   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10661   case ISD::SUBC: Opc = X86ISD::SUB; break;
10662   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10663   }
10664
10665   if (!ExtraOp)
10666     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10667                        Op.getOperand(1));
10668   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10669                      Op.getOperand(1), Op.getOperand(2));
10670 }
10671
10672 /// LowerOperation - Provide custom lowering hooks for some operations.
10673 ///
10674 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10675   switch (Op.getOpcode()) {
10676   default: llvm_unreachable("Should not custom lower this!");
10677   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10678   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10679   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10680   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10681   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10682   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10683   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10684   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10685   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10686   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10687   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10688   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10689   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10690   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10691   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10692   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10693   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10694   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10695   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10696   case ISD::SHL_PARTS:
10697   case ISD::SRA_PARTS:
10698   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10699   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10700   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10701   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10702   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10703   case ISD::FABS:               return LowerFABS(Op, DAG);
10704   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10705   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10706   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10707   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10708   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10709   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10710   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10711   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10712   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10713   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10714   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10715   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10716   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10717   case ISD::FRAME_TO_ARGS_OFFSET:
10718                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10719   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10720   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10721   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10722   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10723   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10724   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10725   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10726   case ISD::MUL:                return LowerMUL(Op, DAG);
10727   case ISD::SRA:
10728   case ISD::SRL:
10729   case ISD::SHL:                return LowerShift(Op, DAG);
10730   case ISD::SADDO:
10731   case ISD::UADDO:
10732   case ISD::SSUBO:
10733   case ISD::USUBO:
10734   case ISD::SMULO:
10735   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10736   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10737   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10738   case ISD::ADDC:
10739   case ISD::ADDE:
10740   case ISD::SUBC:
10741   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10742   case ISD::ADD:                return LowerADD(Op, DAG);
10743   case ISD::SUB:                return LowerSUB(Op, DAG);
10744   }
10745 }
10746
10747 static void ReplaceATOMIC_LOAD(SDNode *Node,
10748                                   SmallVectorImpl<SDValue> &Results,
10749                                   SelectionDAG &DAG) {
10750   DebugLoc dl = Node->getDebugLoc();
10751   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10752
10753   // Convert wide load -> cmpxchg8b/cmpxchg16b
10754   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10755   //        (The only way to get a 16-byte load is cmpxchg16b)
10756   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10757   SDValue Zero = DAG.getConstant(0, VT);
10758   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10759                                Node->getOperand(0),
10760                                Node->getOperand(1), Zero, Zero,
10761                                cast<AtomicSDNode>(Node)->getMemOperand(),
10762                                cast<AtomicSDNode>(Node)->getOrdering(),
10763                                cast<AtomicSDNode>(Node)->getSynchScope());
10764   Results.push_back(Swap.getValue(0));
10765   Results.push_back(Swap.getValue(1));
10766 }
10767
10768 void X86TargetLowering::
10769 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10770                         SelectionDAG &DAG, unsigned NewOp) const {
10771   DebugLoc dl = Node->getDebugLoc();
10772   assert (Node->getValueType(0) == MVT::i64 &&
10773           "Only know how to expand i64 atomics");
10774
10775   SDValue Chain = Node->getOperand(0);
10776   SDValue In1 = Node->getOperand(1);
10777   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10778                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10779   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10780                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10781   SDValue Ops[] = { Chain, In1, In2L, In2H };
10782   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10783   SDValue Result =
10784     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10785                             cast<MemSDNode>(Node)->getMemOperand());
10786   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10787   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10788   Results.push_back(Result.getValue(2));
10789 }
10790
10791 /// ReplaceNodeResults - Replace a node with an illegal result type
10792 /// with a new node built out of custom code.
10793 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10794                                            SmallVectorImpl<SDValue>&Results,
10795                                            SelectionDAG &DAG) const {
10796   DebugLoc dl = N->getDebugLoc();
10797   switch (N->getOpcode()) {
10798   default:
10799     assert(false && "Do not know how to custom type legalize this operation!");
10800     return;
10801   case ISD::SIGN_EXTEND_INREG:
10802   case ISD::ADDC:
10803   case ISD::ADDE:
10804   case ISD::SUBC:
10805   case ISD::SUBE:
10806     // We don't want to expand or promote these.
10807     return;
10808   case ISD::FP_TO_SINT: {
10809     std::pair<SDValue,SDValue> Vals =
10810         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10811     SDValue FIST = Vals.first, StackSlot = Vals.second;
10812     if (FIST.getNode() != 0) {
10813       EVT VT = N->getValueType(0);
10814       // Return a load from the stack slot.
10815       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10816                                     MachinePointerInfo(), 
10817                                     false, false, false, 0));
10818     }
10819     return;
10820   }
10821   case ISD::READCYCLECOUNTER: {
10822     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10823     SDValue TheChain = N->getOperand(0);
10824     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10825     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10826                                      rd.getValue(1));
10827     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10828                                      eax.getValue(2));
10829     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10830     SDValue Ops[] = { eax, edx };
10831     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10832     Results.push_back(edx.getValue(1));
10833     return;
10834   }
10835   case ISD::ATOMIC_CMP_SWAP: {
10836     EVT T = N->getValueType(0);
10837     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10838     bool Regs64bit = T == MVT::i128;
10839     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10840     SDValue cpInL, cpInH;
10841     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10842                         DAG.getConstant(0, HalfT));
10843     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10844                         DAG.getConstant(1, HalfT));
10845     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10846                              Regs64bit ? X86::RAX : X86::EAX,
10847                              cpInL, SDValue());
10848     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10849                              Regs64bit ? X86::RDX : X86::EDX,
10850                              cpInH, cpInL.getValue(1));
10851     SDValue swapInL, swapInH;
10852     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10853                           DAG.getConstant(0, HalfT));
10854     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10855                           DAG.getConstant(1, HalfT));
10856     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10857                                Regs64bit ? X86::RBX : X86::EBX,
10858                                swapInL, cpInH.getValue(1));
10859     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10860                                Regs64bit ? X86::RCX : X86::ECX, 
10861                                swapInH, swapInL.getValue(1));
10862     SDValue Ops[] = { swapInH.getValue(0),
10863                       N->getOperand(1),
10864                       swapInH.getValue(1) };
10865     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10866     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10867     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10868                                   X86ISD::LCMPXCHG8_DAG;
10869     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10870                                              Ops, 3, T, MMO);
10871     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10872                                         Regs64bit ? X86::RAX : X86::EAX,
10873                                         HalfT, Result.getValue(1));
10874     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10875                                         Regs64bit ? X86::RDX : X86::EDX,
10876                                         HalfT, cpOutL.getValue(2));
10877     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10878     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10879     Results.push_back(cpOutH.getValue(1));
10880     return;
10881   }
10882   case ISD::ATOMIC_LOAD_ADD:
10883     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10884     return;
10885   case ISD::ATOMIC_LOAD_AND:
10886     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10887     return;
10888   case ISD::ATOMIC_LOAD_NAND:
10889     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10890     return;
10891   case ISD::ATOMIC_LOAD_OR:
10892     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10893     return;
10894   case ISD::ATOMIC_LOAD_SUB:
10895     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10896     return;
10897   case ISD::ATOMIC_LOAD_XOR:
10898     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10899     return;
10900   case ISD::ATOMIC_SWAP:
10901     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10902     return;
10903   case ISD::ATOMIC_LOAD:
10904     ReplaceATOMIC_LOAD(N, Results, DAG);
10905   }
10906 }
10907
10908 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10909   switch (Opcode) {
10910   default: return NULL;
10911   case X86ISD::BSF:                return "X86ISD::BSF";
10912   case X86ISD::BSR:                return "X86ISD::BSR";
10913   case X86ISD::SHLD:               return "X86ISD::SHLD";
10914   case X86ISD::SHRD:               return "X86ISD::SHRD";
10915   case X86ISD::FAND:               return "X86ISD::FAND";
10916   case X86ISD::FOR:                return "X86ISD::FOR";
10917   case X86ISD::FXOR:               return "X86ISD::FXOR";
10918   case X86ISD::FSRL:               return "X86ISD::FSRL";
10919   case X86ISD::FILD:               return "X86ISD::FILD";
10920   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10921   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10922   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10923   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10924   case X86ISD::FLD:                return "X86ISD::FLD";
10925   case X86ISD::FST:                return "X86ISD::FST";
10926   case X86ISD::CALL:               return "X86ISD::CALL";
10927   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10928   case X86ISD::BT:                 return "X86ISD::BT";
10929   case X86ISD::CMP:                return "X86ISD::CMP";
10930   case X86ISD::COMI:               return "X86ISD::COMI";
10931   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10932   case X86ISD::SETCC:              return "X86ISD::SETCC";
10933   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10934   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10935   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10936   case X86ISD::CMOV:               return "X86ISD::CMOV";
10937   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10938   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10939   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10940   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10941   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10942   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10943   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10944   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10945   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10946   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10947   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10948   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10949   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10950   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10951   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10952   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10953   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10954   case X86ISD::FMAX:               return "X86ISD::FMAX";
10955   case X86ISD::FMIN:               return "X86ISD::FMIN";
10956   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10957   case X86ISD::FRCP:               return "X86ISD::FRCP";
10958   case X86ISD::FHADD:              return "X86ISD::FHADD";
10959   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10960   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10961   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10962   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10963   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10964   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10965   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10966   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10967   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10968   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10969   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10970   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10971   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10972   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10973   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10974   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10975   case X86ISD::VSHL:               return "X86ISD::VSHL";
10976   case X86ISD::VSRL:               return "X86ISD::VSRL";
10977   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10978   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10979   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10980   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10981   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10982   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10983   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10984   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10985   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10986   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10987   case X86ISD::ADD:                return "X86ISD::ADD";
10988   case X86ISD::SUB:                return "X86ISD::SUB";
10989   case X86ISD::ADC:                return "X86ISD::ADC";
10990   case X86ISD::SBB:                return "X86ISD::SBB";
10991   case X86ISD::SMUL:               return "X86ISD::SMUL";
10992   case X86ISD::UMUL:               return "X86ISD::UMUL";
10993   case X86ISD::INC:                return "X86ISD::INC";
10994   case X86ISD::DEC:                return "X86ISD::DEC";
10995   case X86ISD::OR:                 return "X86ISD::OR";
10996   case X86ISD::XOR:                return "X86ISD::XOR";
10997   case X86ISD::AND:                return "X86ISD::AND";
10998   case X86ISD::ANDN:               return "X86ISD::ANDN";
10999   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11000   case X86ISD::PTEST:              return "X86ISD::PTEST";
11001   case X86ISD::TESTP:              return "X86ISD::TESTP";
11002   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11003   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11004   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11005   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11006   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11007   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11008   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11009   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11010   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11011   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11012   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11013   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11014   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11015   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11016   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11017   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11018   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11019   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11020   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11021   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11022   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11023   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11024   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11025   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
11026   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11027   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11028   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11029   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11030   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11031   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11032   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11033   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11034   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11035   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11036   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11037   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11038   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11039   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11040   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11041   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11042   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11043   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11044   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11045   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11046   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11047   }
11048 }
11049
11050 // isLegalAddressingMode - Return true if the addressing mode represented
11051 // by AM is legal for this target, for a load/store of the specified type.
11052 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11053                                               Type *Ty) const {
11054   // X86 supports extremely general addressing modes.
11055   CodeModel::Model M = getTargetMachine().getCodeModel();
11056   Reloc::Model R = getTargetMachine().getRelocationModel();
11057
11058   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11059   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11060     return false;
11061
11062   if (AM.BaseGV) {
11063     unsigned GVFlags =
11064       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11065
11066     // If a reference to this global requires an extra load, we can't fold it.
11067     if (isGlobalStubReference(GVFlags))
11068       return false;
11069
11070     // If BaseGV requires a register for the PIC base, we cannot also have a
11071     // BaseReg specified.
11072     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11073       return false;
11074
11075     // If lower 4G is not available, then we must use rip-relative addressing.
11076     if ((M != CodeModel::Small || R != Reloc::Static) &&
11077         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11078       return false;
11079   }
11080
11081   switch (AM.Scale) {
11082   case 0:
11083   case 1:
11084   case 2:
11085   case 4:
11086   case 8:
11087     // These scales always work.
11088     break;
11089   case 3:
11090   case 5:
11091   case 9:
11092     // These scales are formed with basereg+scalereg.  Only accept if there is
11093     // no basereg yet.
11094     if (AM.HasBaseReg)
11095       return false;
11096     break;
11097   default:  // Other stuff never works.
11098     return false;
11099   }
11100
11101   return true;
11102 }
11103
11104
11105 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11106   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11107     return false;
11108   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11109   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11110   if (NumBits1 <= NumBits2)
11111     return false;
11112   return true;
11113 }
11114
11115 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11116   if (!VT1.isInteger() || !VT2.isInteger())
11117     return false;
11118   unsigned NumBits1 = VT1.getSizeInBits();
11119   unsigned NumBits2 = VT2.getSizeInBits();
11120   if (NumBits1 <= NumBits2)
11121     return false;
11122   return true;
11123 }
11124
11125 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11126   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11127   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11128 }
11129
11130 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11131   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11132   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11133 }
11134
11135 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11136   // i16 instructions are longer (0x66 prefix) and potentially slower.
11137   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11138 }
11139
11140 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11141 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11142 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11143 /// are assumed to be legal.
11144 bool
11145 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11146                                       EVT VT) const {
11147   // Very little shuffling can be done for 64-bit vectors right now.
11148   if (VT.getSizeInBits() == 64)
11149     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11150
11151   // FIXME: pshufb, blends, shifts.
11152   return (VT.getVectorNumElements() == 2 ||
11153           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11154           isMOVLMask(M, VT) ||
11155           isSHUFPMask(M, VT) ||
11156           isPSHUFDMask(M, VT) ||
11157           isPSHUFHWMask(M, VT) ||
11158           isPSHUFLWMask(M, VT) ||
11159           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11160           isUNPCKLMask(M, VT) ||
11161           isUNPCKHMask(M, VT) ||
11162           isUNPCKL_v_undef_Mask(M, VT) ||
11163           isUNPCKH_v_undef_Mask(M, VT));
11164 }
11165
11166 bool
11167 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11168                                           EVT VT) const {
11169   unsigned NumElts = VT.getVectorNumElements();
11170   // FIXME: This collection of masks seems suspect.
11171   if (NumElts == 2)
11172     return true;
11173   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11174     return (isMOVLMask(Mask, VT)  ||
11175             isCommutedMOVLMask(Mask, VT, true) ||
11176             isSHUFPMask(Mask, VT) ||
11177             isCommutedSHUFPMask(Mask, VT));
11178   }
11179   return false;
11180 }
11181
11182 //===----------------------------------------------------------------------===//
11183 //                           X86 Scheduler Hooks
11184 //===----------------------------------------------------------------------===//
11185
11186 // private utility function
11187 MachineBasicBlock *
11188 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11189                                                        MachineBasicBlock *MBB,
11190                                                        unsigned regOpc,
11191                                                        unsigned immOpc,
11192                                                        unsigned LoadOpc,
11193                                                        unsigned CXchgOpc,
11194                                                        unsigned notOpc,
11195                                                        unsigned EAXreg,
11196                                                        TargetRegisterClass *RC,
11197                                                        bool invSrc) const {
11198   // For the atomic bitwise operator, we generate
11199   //   thisMBB:
11200   //   newMBB:
11201   //     ld  t1 = [bitinstr.addr]
11202   //     op  t2 = t1, [bitinstr.val]
11203   //     mov EAX = t1
11204   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11205   //     bz  newMBB
11206   //     fallthrough -->nextMBB
11207   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11208   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11209   MachineFunction::iterator MBBIter = MBB;
11210   ++MBBIter;
11211
11212   /// First build the CFG
11213   MachineFunction *F = MBB->getParent();
11214   MachineBasicBlock *thisMBB = MBB;
11215   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11216   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11217   F->insert(MBBIter, newMBB);
11218   F->insert(MBBIter, nextMBB);
11219
11220   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11221   nextMBB->splice(nextMBB->begin(), thisMBB,
11222                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11223                   thisMBB->end());
11224   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11225
11226   // Update thisMBB to fall through to newMBB
11227   thisMBB->addSuccessor(newMBB);
11228
11229   // newMBB jumps to itself and fall through to nextMBB
11230   newMBB->addSuccessor(nextMBB);
11231   newMBB->addSuccessor(newMBB);
11232
11233   // Insert instructions into newMBB based on incoming instruction
11234   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11235          "unexpected number of operands");
11236   DebugLoc dl = bInstr->getDebugLoc();
11237   MachineOperand& destOper = bInstr->getOperand(0);
11238   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11239   int numArgs = bInstr->getNumOperands() - 1;
11240   for (int i=0; i < numArgs; ++i)
11241     argOpers[i] = &bInstr->getOperand(i+1);
11242
11243   // x86 address has 4 operands: base, index, scale, and displacement
11244   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11245   int valArgIndx = lastAddrIndx + 1;
11246
11247   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11248   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11249   for (int i=0; i <= lastAddrIndx; ++i)
11250     (*MIB).addOperand(*argOpers[i]);
11251
11252   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11253   if (invSrc) {
11254     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11255   }
11256   else
11257     tt = t1;
11258
11259   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11260   assert((argOpers[valArgIndx]->isReg() ||
11261           argOpers[valArgIndx]->isImm()) &&
11262          "invalid operand");
11263   if (argOpers[valArgIndx]->isReg())
11264     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11265   else
11266     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11267   MIB.addReg(tt);
11268   (*MIB).addOperand(*argOpers[valArgIndx]);
11269
11270   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11271   MIB.addReg(t1);
11272
11273   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11274   for (int i=0; i <= lastAddrIndx; ++i)
11275     (*MIB).addOperand(*argOpers[i]);
11276   MIB.addReg(t2);
11277   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11278   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11279                     bInstr->memoperands_end());
11280
11281   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11282   MIB.addReg(EAXreg);
11283
11284   // insert branch
11285   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11286
11287   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11288   return nextMBB;
11289 }
11290
11291 // private utility function:  64 bit atomics on 32 bit host.
11292 MachineBasicBlock *
11293 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11294                                                        MachineBasicBlock *MBB,
11295                                                        unsigned regOpcL,
11296                                                        unsigned regOpcH,
11297                                                        unsigned immOpcL,
11298                                                        unsigned immOpcH,
11299                                                        bool invSrc) const {
11300   // For the atomic bitwise operator, we generate
11301   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11302   //     ld t1,t2 = [bitinstr.addr]
11303   //   newMBB:
11304   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11305   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11306   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11307   //     mov ECX, EBX <- t5, t6
11308   //     mov EAX, EDX <- t1, t2
11309   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11310   //     mov t3, t4 <- EAX, EDX
11311   //     bz  newMBB
11312   //     result in out1, out2
11313   //     fallthrough -->nextMBB
11314
11315   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11316   const unsigned LoadOpc = X86::MOV32rm;
11317   const unsigned NotOpc = X86::NOT32r;
11318   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11319   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11320   MachineFunction::iterator MBBIter = MBB;
11321   ++MBBIter;
11322
11323   /// First build the CFG
11324   MachineFunction *F = MBB->getParent();
11325   MachineBasicBlock *thisMBB = MBB;
11326   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11327   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11328   F->insert(MBBIter, newMBB);
11329   F->insert(MBBIter, nextMBB);
11330
11331   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11332   nextMBB->splice(nextMBB->begin(), thisMBB,
11333                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11334                   thisMBB->end());
11335   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11336
11337   // Update thisMBB to fall through to newMBB
11338   thisMBB->addSuccessor(newMBB);
11339
11340   // newMBB jumps to itself and fall through to nextMBB
11341   newMBB->addSuccessor(nextMBB);
11342   newMBB->addSuccessor(newMBB);
11343
11344   DebugLoc dl = bInstr->getDebugLoc();
11345   // Insert instructions into newMBB based on incoming instruction
11346   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11347   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11348          "unexpected number of operands");
11349   MachineOperand& dest1Oper = bInstr->getOperand(0);
11350   MachineOperand& dest2Oper = bInstr->getOperand(1);
11351   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11352   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11353     argOpers[i] = &bInstr->getOperand(i+2);
11354
11355     // We use some of the operands multiple times, so conservatively just
11356     // clear any kill flags that might be present.
11357     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11358       argOpers[i]->setIsKill(false);
11359   }
11360
11361   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11362   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11363
11364   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11365   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11366   for (int i=0; i <= lastAddrIndx; ++i)
11367     (*MIB).addOperand(*argOpers[i]);
11368   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11369   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11370   // add 4 to displacement.
11371   for (int i=0; i <= lastAddrIndx-2; ++i)
11372     (*MIB).addOperand(*argOpers[i]);
11373   MachineOperand newOp3 = *(argOpers[3]);
11374   if (newOp3.isImm())
11375     newOp3.setImm(newOp3.getImm()+4);
11376   else
11377     newOp3.setOffset(newOp3.getOffset()+4);
11378   (*MIB).addOperand(newOp3);
11379   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11380
11381   // t3/4 are defined later, at the bottom of the loop
11382   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11383   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11384   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11385     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11386   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11387     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11388
11389   // The subsequent operations should be using the destination registers of
11390   //the PHI instructions.
11391   if (invSrc) {
11392     t1 = F->getRegInfo().createVirtualRegister(RC);
11393     t2 = F->getRegInfo().createVirtualRegister(RC);
11394     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11395     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11396   } else {
11397     t1 = dest1Oper.getReg();
11398     t2 = dest2Oper.getReg();
11399   }
11400
11401   int valArgIndx = lastAddrIndx + 1;
11402   assert((argOpers[valArgIndx]->isReg() ||
11403           argOpers[valArgIndx]->isImm()) &&
11404          "invalid operand");
11405   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11406   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11407   if (argOpers[valArgIndx]->isReg())
11408     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11409   else
11410     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11411   if (regOpcL != X86::MOV32rr)
11412     MIB.addReg(t1);
11413   (*MIB).addOperand(*argOpers[valArgIndx]);
11414   assert(argOpers[valArgIndx + 1]->isReg() ==
11415          argOpers[valArgIndx]->isReg());
11416   assert(argOpers[valArgIndx + 1]->isImm() ==
11417          argOpers[valArgIndx]->isImm());
11418   if (argOpers[valArgIndx + 1]->isReg())
11419     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11420   else
11421     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11422   if (regOpcH != X86::MOV32rr)
11423     MIB.addReg(t2);
11424   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11425
11426   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11427   MIB.addReg(t1);
11428   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11429   MIB.addReg(t2);
11430
11431   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11432   MIB.addReg(t5);
11433   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11434   MIB.addReg(t6);
11435
11436   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11437   for (int i=0; i <= lastAddrIndx; ++i)
11438     (*MIB).addOperand(*argOpers[i]);
11439
11440   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11441   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11442                     bInstr->memoperands_end());
11443
11444   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11445   MIB.addReg(X86::EAX);
11446   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11447   MIB.addReg(X86::EDX);
11448
11449   // insert branch
11450   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11451
11452   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11453   return nextMBB;
11454 }
11455
11456 // private utility function
11457 MachineBasicBlock *
11458 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11459                                                       MachineBasicBlock *MBB,
11460                                                       unsigned cmovOpc) const {
11461   // For the atomic min/max operator, we generate
11462   //   thisMBB:
11463   //   newMBB:
11464   //     ld t1 = [min/max.addr]
11465   //     mov t2 = [min/max.val]
11466   //     cmp  t1, t2
11467   //     cmov[cond] t2 = t1
11468   //     mov EAX = t1
11469   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11470   //     bz   newMBB
11471   //     fallthrough -->nextMBB
11472   //
11473   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11474   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11475   MachineFunction::iterator MBBIter = MBB;
11476   ++MBBIter;
11477
11478   /// First build the CFG
11479   MachineFunction *F = MBB->getParent();
11480   MachineBasicBlock *thisMBB = MBB;
11481   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11482   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11483   F->insert(MBBIter, newMBB);
11484   F->insert(MBBIter, nextMBB);
11485
11486   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11487   nextMBB->splice(nextMBB->begin(), thisMBB,
11488                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11489                   thisMBB->end());
11490   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11491
11492   // Update thisMBB to fall through to newMBB
11493   thisMBB->addSuccessor(newMBB);
11494
11495   // newMBB jumps to newMBB and fall through to nextMBB
11496   newMBB->addSuccessor(nextMBB);
11497   newMBB->addSuccessor(newMBB);
11498
11499   DebugLoc dl = mInstr->getDebugLoc();
11500   // Insert instructions into newMBB based on incoming instruction
11501   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11502          "unexpected number of operands");
11503   MachineOperand& destOper = mInstr->getOperand(0);
11504   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11505   int numArgs = mInstr->getNumOperands() - 1;
11506   for (int i=0; i < numArgs; ++i)
11507     argOpers[i] = &mInstr->getOperand(i+1);
11508
11509   // x86 address has 4 operands: base, index, scale, and displacement
11510   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11511   int valArgIndx = lastAddrIndx + 1;
11512
11513   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11514   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11515   for (int i=0; i <= lastAddrIndx; ++i)
11516     (*MIB).addOperand(*argOpers[i]);
11517
11518   // We only support register and immediate values
11519   assert((argOpers[valArgIndx]->isReg() ||
11520           argOpers[valArgIndx]->isImm()) &&
11521          "invalid operand");
11522
11523   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11524   if (argOpers[valArgIndx]->isReg())
11525     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11526   else
11527     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11528   (*MIB).addOperand(*argOpers[valArgIndx]);
11529
11530   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11531   MIB.addReg(t1);
11532
11533   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11534   MIB.addReg(t1);
11535   MIB.addReg(t2);
11536
11537   // Generate movc
11538   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11539   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11540   MIB.addReg(t2);
11541   MIB.addReg(t1);
11542
11543   // Cmp and exchange if none has modified the memory location
11544   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11545   for (int i=0; i <= lastAddrIndx; ++i)
11546     (*MIB).addOperand(*argOpers[i]);
11547   MIB.addReg(t3);
11548   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11549   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11550                     mInstr->memoperands_end());
11551
11552   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11553   MIB.addReg(X86::EAX);
11554
11555   // insert branch
11556   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11557
11558   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11559   return nextMBB;
11560 }
11561
11562 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11563 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11564 // in the .td file.
11565 MachineBasicBlock *
11566 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11567                             unsigned numArgs, bool memArg) const {
11568   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11569          "Target must have SSE4.2 or AVX features enabled");
11570
11571   DebugLoc dl = MI->getDebugLoc();
11572   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11573   unsigned Opc;
11574   if (!Subtarget->hasAVX()) {
11575     if (memArg)
11576       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11577     else
11578       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11579   } else {
11580     if (memArg)
11581       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11582     else
11583       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11584   }
11585
11586   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11587   for (unsigned i = 0; i < numArgs; ++i) {
11588     MachineOperand &Op = MI->getOperand(i+1);
11589     if (!(Op.isReg() && Op.isImplicit()))
11590       MIB.addOperand(Op);
11591   }
11592   BuildMI(*BB, MI, dl,
11593     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11594              MI->getOperand(0).getReg())
11595     .addReg(X86::XMM0);
11596
11597   MI->eraseFromParent();
11598   return BB;
11599 }
11600
11601 MachineBasicBlock *
11602 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11603   DebugLoc dl = MI->getDebugLoc();
11604   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11605
11606   // Address into RAX/EAX, other two args into ECX, EDX.
11607   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11608   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11609   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11610   for (int i = 0; i < X86::AddrNumOperands; ++i)
11611     MIB.addOperand(MI->getOperand(i));
11612
11613   unsigned ValOps = X86::AddrNumOperands;
11614   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11615     .addReg(MI->getOperand(ValOps).getReg());
11616   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11617     .addReg(MI->getOperand(ValOps+1).getReg());
11618
11619   // The instruction doesn't actually take any operands though.
11620   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11621
11622   MI->eraseFromParent(); // The pseudo is gone now.
11623   return BB;
11624 }
11625
11626 MachineBasicBlock *
11627 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11628   DebugLoc dl = MI->getDebugLoc();
11629   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11630
11631   // First arg in ECX, the second in EAX.
11632   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11633     .addReg(MI->getOperand(0).getReg());
11634   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11635     .addReg(MI->getOperand(1).getReg());
11636
11637   // The instruction doesn't actually take any operands though.
11638   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11639
11640   MI->eraseFromParent(); // The pseudo is gone now.
11641   return BB;
11642 }
11643
11644 MachineBasicBlock *
11645 X86TargetLowering::EmitVAARG64WithCustomInserter(
11646                    MachineInstr *MI,
11647                    MachineBasicBlock *MBB) const {
11648   // Emit va_arg instruction on X86-64.
11649
11650   // Operands to this pseudo-instruction:
11651   // 0  ) Output        : destination address (reg)
11652   // 1-5) Input         : va_list address (addr, i64mem)
11653   // 6  ) ArgSize       : Size (in bytes) of vararg type
11654   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11655   // 8  ) Align         : Alignment of type
11656   // 9  ) EFLAGS (implicit-def)
11657
11658   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11659   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11660
11661   unsigned DestReg = MI->getOperand(0).getReg();
11662   MachineOperand &Base = MI->getOperand(1);
11663   MachineOperand &Scale = MI->getOperand(2);
11664   MachineOperand &Index = MI->getOperand(3);
11665   MachineOperand &Disp = MI->getOperand(4);
11666   MachineOperand &Segment = MI->getOperand(5);
11667   unsigned ArgSize = MI->getOperand(6).getImm();
11668   unsigned ArgMode = MI->getOperand(7).getImm();
11669   unsigned Align = MI->getOperand(8).getImm();
11670
11671   // Memory Reference
11672   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11673   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11674   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11675
11676   // Machine Information
11677   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11678   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11679   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11680   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11681   DebugLoc DL = MI->getDebugLoc();
11682
11683   // struct va_list {
11684   //   i32   gp_offset
11685   //   i32   fp_offset
11686   //   i64   overflow_area (address)
11687   //   i64   reg_save_area (address)
11688   // }
11689   // sizeof(va_list) = 24
11690   // alignment(va_list) = 8
11691
11692   unsigned TotalNumIntRegs = 6;
11693   unsigned TotalNumXMMRegs = 8;
11694   bool UseGPOffset = (ArgMode == 1);
11695   bool UseFPOffset = (ArgMode == 2);
11696   unsigned MaxOffset = TotalNumIntRegs * 8 +
11697                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11698
11699   /* Align ArgSize to a multiple of 8 */
11700   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11701   bool NeedsAlign = (Align > 8);
11702
11703   MachineBasicBlock *thisMBB = MBB;
11704   MachineBasicBlock *overflowMBB;
11705   MachineBasicBlock *offsetMBB;
11706   MachineBasicBlock *endMBB;
11707
11708   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11709   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11710   unsigned OffsetReg = 0;
11711
11712   if (!UseGPOffset && !UseFPOffset) {
11713     // If we only pull from the overflow region, we don't create a branch.
11714     // We don't need to alter control flow.
11715     OffsetDestReg = 0; // unused
11716     OverflowDestReg = DestReg;
11717
11718     offsetMBB = NULL;
11719     overflowMBB = thisMBB;
11720     endMBB = thisMBB;
11721   } else {
11722     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11723     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11724     // If not, pull from overflow_area. (branch to overflowMBB)
11725     //
11726     //       thisMBB
11727     //         |     .
11728     //         |        .
11729     //     offsetMBB   overflowMBB
11730     //         |        .
11731     //         |     .
11732     //        endMBB
11733
11734     // Registers for the PHI in endMBB
11735     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11736     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11737
11738     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11739     MachineFunction *MF = MBB->getParent();
11740     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11741     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11742     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11743
11744     MachineFunction::iterator MBBIter = MBB;
11745     ++MBBIter;
11746
11747     // Insert the new basic blocks
11748     MF->insert(MBBIter, offsetMBB);
11749     MF->insert(MBBIter, overflowMBB);
11750     MF->insert(MBBIter, endMBB);
11751
11752     // Transfer the remainder of MBB and its successor edges to endMBB.
11753     endMBB->splice(endMBB->begin(), thisMBB,
11754                     llvm::next(MachineBasicBlock::iterator(MI)),
11755                     thisMBB->end());
11756     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11757
11758     // Make offsetMBB and overflowMBB successors of thisMBB
11759     thisMBB->addSuccessor(offsetMBB);
11760     thisMBB->addSuccessor(overflowMBB);
11761
11762     // endMBB is a successor of both offsetMBB and overflowMBB
11763     offsetMBB->addSuccessor(endMBB);
11764     overflowMBB->addSuccessor(endMBB);
11765
11766     // Load the offset value into a register
11767     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11768     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11769       .addOperand(Base)
11770       .addOperand(Scale)
11771       .addOperand(Index)
11772       .addDisp(Disp, UseFPOffset ? 4 : 0)
11773       .addOperand(Segment)
11774       .setMemRefs(MMOBegin, MMOEnd);
11775
11776     // Check if there is enough room left to pull this argument.
11777     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11778       .addReg(OffsetReg)
11779       .addImm(MaxOffset + 8 - ArgSizeA8);
11780
11781     // Branch to "overflowMBB" if offset >= max
11782     // Fall through to "offsetMBB" otherwise
11783     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11784       .addMBB(overflowMBB);
11785   }
11786
11787   // In offsetMBB, emit code to use the reg_save_area.
11788   if (offsetMBB) {
11789     assert(OffsetReg != 0);
11790
11791     // Read the reg_save_area address.
11792     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11793     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11794       .addOperand(Base)
11795       .addOperand(Scale)
11796       .addOperand(Index)
11797       .addDisp(Disp, 16)
11798       .addOperand(Segment)
11799       .setMemRefs(MMOBegin, MMOEnd);
11800
11801     // Zero-extend the offset
11802     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11803       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11804         .addImm(0)
11805         .addReg(OffsetReg)
11806         .addImm(X86::sub_32bit);
11807
11808     // Add the offset to the reg_save_area to get the final address.
11809     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11810       .addReg(OffsetReg64)
11811       .addReg(RegSaveReg);
11812
11813     // Compute the offset for the next argument
11814     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11815     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11816       .addReg(OffsetReg)
11817       .addImm(UseFPOffset ? 16 : 8);
11818
11819     // Store it back into the va_list.
11820     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11821       .addOperand(Base)
11822       .addOperand(Scale)
11823       .addOperand(Index)
11824       .addDisp(Disp, UseFPOffset ? 4 : 0)
11825       .addOperand(Segment)
11826       .addReg(NextOffsetReg)
11827       .setMemRefs(MMOBegin, MMOEnd);
11828
11829     // Jump to endMBB
11830     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11831       .addMBB(endMBB);
11832   }
11833
11834   //
11835   // Emit code to use overflow area
11836   //
11837
11838   // Load the overflow_area address into a register.
11839   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11840   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11841     .addOperand(Base)
11842     .addOperand(Scale)
11843     .addOperand(Index)
11844     .addDisp(Disp, 8)
11845     .addOperand(Segment)
11846     .setMemRefs(MMOBegin, MMOEnd);
11847
11848   // If we need to align it, do so. Otherwise, just copy the address
11849   // to OverflowDestReg.
11850   if (NeedsAlign) {
11851     // Align the overflow address
11852     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11853     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11854
11855     // aligned_addr = (addr + (align-1)) & ~(align-1)
11856     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11857       .addReg(OverflowAddrReg)
11858       .addImm(Align-1);
11859
11860     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11861       .addReg(TmpReg)
11862       .addImm(~(uint64_t)(Align-1));
11863   } else {
11864     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11865       .addReg(OverflowAddrReg);
11866   }
11867
11868   // Compute the next overflow address after this argument.
11869   // (the overflow address should be kept 8-byte aligned)
11870   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11871   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11872     .addReg(OverflowDestReg)
11873     .addImm(ArgSizeA8);
11874
11875   // Store the new overflow address.
11876   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11877     .addOperand(Base)
11878     .addOperand(Scale)
11879     .addOperand(Index)
11880     .addDisp(Disp, 8)
11881     .addOperand(Segment)
11882     .addReg(NextAddrReg)
11883     .setMemRefs(MMOBegin, MMOEnd);
11884
11885   // If we branched, emit the PHI to the front of endMBB.
11886   if (offsetMBB) {
11887     BuildMI(*endMBB, endMBB->begin(), DL,
11888             TII->get(X86::PHI), DestReg)
11889       .addReg(OffsetDestReg).addMBB(offsetMBB)
11890       .addReg(OverflowDestReg).addMBB(overflowMBB);
11891   }
11892
11893   // Erase the pseudo instruction
11894   MI->eraseFromParent();
11895
11896   return endMBB;
11897 }
11898
11899 MachineBasicBlock *
11900 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11901                                                  MachineInstr *MI,
11902                                                  MachineBasicBlock *MBB) const {
11903   // Emit code to save XMM registers to the stack. The ABI says that the
11904   // number of registers to save is given in %al, so it's theoretically
11905   // possible to do an indirect jump trick to avoid saving all of them,
11906   // however this code takes a simpler approach and just executes all
11907   // of the stores if %al is non-zero. It's less code, and it's probably
11908   // easier on the hardware branch predictor, and stores aren't all that
11909   // expensive anyway.
11910
11911   // Create the new basic blocks. One block contains all the XMM stores,
11912   // and one block is the final destination regardless of whether any
11913   // stores were performed.
11914   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11915   MachineFunction *F = MBB->getParent();
11916   MachineFunction::iterator MBBIter = MBB;
11917   ++MBBIter;
11918   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11919   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11920   F->insert(MBBIter, XMMSaveMBB);
11921   F->insert(MBBIter, EndMBB);
11922
11923   // Transfer the remainder of MBB and its successor edges to EndMBB.
11924   EndMBB->splice(EndMBB->begin(), MBB,
11925                  llvm::next(MachineBasicBlock::iterator(MI)),
11926                  MBB->end());
11927   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11928
11929   // The original block will now fall through to the XMM save block.
11930   MBB->addSuccessor(XMMSaveMBB);
11931   // The XMMSaveMBB will fall through to the end block.
11932   XMMSaveMBB->addSuccessor(EndMBB);
11933
11934   // Now add the instructions.
11935   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11936   DebugLoc DL = MI->getDebugLoc();
11937
11938   unsigned CountReg = MI->getOperand(0).getReg();
11939   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11940   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11941
11942   if (!Subtarget->isTargetWin64()) {
11943     // If %al is 0, branch around the XMM save block.
11944     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11945     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11946     MBB->addSuccessor(EndMBB);
11947   }
11948
11949   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11950   // In the XMM save block, save all the XMM argument registers.
11951   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11952     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11953     MachineMemOperand *MMO =
11954       F->getMachineMemOperand(
11955           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11956         MachineMemOperand::MOStore,
11957         /*Size=*/16, /*Align=*/16);
11958     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11959       .addFrameIndex(RegSaveFrameIndex)
11960       .addImm(/*Scale=*/1)
11961       .addReg(/*IndexReg=*/0)
11962       .addImm(/*Disp=*/Offset)
11963       .addReg(/*Segment=*/0)
11964       .addReg(MI->getOperand(i).getReg())
11965       .addMemOperand(MMO);
11966   }
11967
11968   MI->eraseFromParent();   // The pseudo instruction is gone now.
11969
11970   return EndMBB;
11971 }
11972
11973 MachineBasicBlock *
11974 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11975                                      MachineBasicBlock *BB) const {
11976   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11977   DebugLoc DL = MI->getDebugLoc();
11978
11979   // To "insert" a SELECT_CC instruction, we actually have to insert the
11980   // diamond control-flow pattern.  The incoming instruction knows the
11981   // destination vreg to set, the condition code register to branch on, the
11982   // true/false values to select between, and a branch opcode to use.
11983   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11984   MachineFunction::iterator It = BB;
11985   ++It;
11986
11987   //  thisMBB:
11988   //  ...
11989   //   TrueVal = ...
11990   //   cmpTY ccX, r1, r2
11991   //   bCC copy1MBB
11992   //   fallthrough --> copy0MBB
11993   MachineBasicBlock *thisMBB = BB;
11994   MachineFunction *F = BB->getParent();
11995   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11996   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11997   F->insert(It, copy0MBB);
11998   F->insert(It, sinkMBB);
11999
12000   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12001   // live into the sink and copy blocks.
12002   if (!MI->killsRegister(X86::EFLAGS)) {
12003     copy0MBB->addLiveIn(X86::EFLAGS);
12004     sinkMBB->addLiveIn(X86::EFLAGS);
12005   }
12006
12007   // Transfer the remainder of BB and its successor edges to sinkMBB.
12008   sinkMBB->splice(sinkMBB->begin(), BB,
12009                   llvm::next(MachineBasicBlock::iterator(MI)),
12010                   BB->end());
12011   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12012
12013   // Add the true and fallthrough blocks as its successors.
12014   BB->addSuccessor(copy0MBB);
12015   BB->addSuccessor(sinkMBB);
12016
12017   // Create the conditional branch instruction.
12018   unsigned Opc =
12019     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12020   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12021
12022   //  copy0MBB:
12023   //   %FalseValue = ...
12024   //   # fallthrough to sinkMBB
12025   copy0MBB->addSuccessor(sinkMBB);
12026
12027   //  sinkMBB:
12028   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12029   //  ...
12030   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12031           TII->get(X86::PHI), MI->getOperand(0).getReg())
12032     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12033     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12034
12035   MI->eraseFromParent();   // The pseudo instruction is gone now.
12036   return sinkMBB;
12037 }
12038
12039 MachineBasicBlock *
12040 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12041                                         bool Is64Bit) const {
12042   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12043   DebugLoc DL = MI->getDebugLoc();
12044   MachineFunction *MF = BB->getParent();
12045   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12046
12047   assert(EnableSegmentedStacks);
12048
12049   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12050   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12051
12052   // BB:
12053   //  ... [Till the alloca]
12054   // If stacklet is not large enough, jump to mallocMBB
12055   //
12056   // bumpMBB:
12057   //  Allocate by subtracting from RSP
12058   //  Jump to continueMBB
12059   //
12060   // mallocMBB:
12061   //  Allocate by call to runtime
12062   //
12063   // continueMBB:
12064   //  ...
12065   //  [rest of original BB]
12066   //
12067
12068   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12069   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12070   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12071
12072   MachineRegisterInfo &MRI = MF->getRegInfo();
12073   const TargetRegisterClass *AddrRegClass =
12074     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12075
12076   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12077     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12078     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12079     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12080     sizeVReg = MI->getOperand(1).getReg(),
12081     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12082
12083   MachineFunction::iterator MBBIter = BB;
12084   ++MBBIter;
12085
12086   MF->insert(MBBIter, bumpMBB);
12087   MF->insert(MBBIter, mallocMBB);
12088   MF->insert(MBBIter, continueMBB);
12089
12090   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12091                       (MachineBasicBlock::iterator(MI)), BB->end());
12092   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12093
12094   // Add code to the main basic block to check if the stack limit has been hit,
12095   // and if so, jump to mallocMBB otherwise to bumpMBB.
12096   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12097   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12098     .addReg(tmpSPVReg).addReg(sizeVReg);
12099   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12100     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12101     .addReg(SPLimitVReg);
12102   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12103
12104   // bumpMBB simply decreases the stack pointer, since we know the current
12105   // stacklet has enough space.
12106   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12107     .addReg(SPLimitVReg);
12108   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12109     .addReg(SPLimitVReg);
12110   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12111
12112   // Calls into a routine in libgcc to allocate more space from the heap.
12113   if (Is64Bit) {
12114     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12115       .addReg(sizeVReg);
12116     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12117     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12118   } else {
12119     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12120       .addImm(12);
12121     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12122     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12123       .addExternalSymbol("__morestack_allocate_stack_space");
12124   }
12125
12126   if (!Is64Bit)
12127     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12128       .addImm(16);
12129
12130   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12131     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12132   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12133
12134   // Set up the CFG correctly.
12135   BB->addSuccessor(bumpMBB);
12136   BB->addSuccessor(mallocMBB);
12137   mallocMBB->addSuccessor(continueMBB);
12138   bumpMBB->addSuccessor(continueMBB);
12139
12140   // Take care of the PHI nodes.
12141   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12142           MI->getOperand(0).getReg())
12143     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12144     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12145
12146   // Delete the original pseudo instruction.
12147   MI->eraseFromParent();
12148
12149   // And we're done.
12150   return continueMBB;
12151 }
12152
12153 MachineBasicBlock *
12154 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12155                                           MachineBasicBlock *BB) const {
12156   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12157   DebugLoc DL = MI->getDebugLoc();
12158
12159   assert(!Subtarget->isTargetEnvMacho());
12160
12161   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12162   // non-trivial part is impdef of ESP.
12163
12164   if (Subtarget->isTargetWin64()) {
12165     if (Subtarget->isTargetCygMing()) {
12166       // ___chkstk(Mingw64):
12167       // Clobbers R10, R11, RAX and EFLAGS.
12168       // Updates RSP.
12169       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12170         .addExternalSymbol("___chkstk")
12171         .addReg(X86::RAX, RegState::Implicit)
12172         .addReg(X86::RSP, RegState::Implicit)
12173         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12174         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12175         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12176     } else {
12177       // __chkstk(MSVCRT): does not update stack pointer.
12178       // Clobbers R10, R11 and EFLAGS.
12179       // FIXME: RAX(allocated size) might be reused and not killed.
12180       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12181         .addExternalSymbol("__chkstk")
12182         .addReg(X86::RAX, RegState::Implicit)
12183         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12184       // RAX has the offset to subtracted from RSP.
12185       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12186         .addReg(X86::RSP)
12187         .addReg(X86::RAX);
12188     }
12189   } else {
12190     const char *StackProbeSymbol =
12191       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12192
12193     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12194       .addExternalSymbol(StackProbeSymbol)
12195       .addReg(X86::EAX, RegState::Implicit)
12196       .addReg(X86::ESP, RegState::Implicit)
12197       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12198       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12199       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12200   }
12201
12202   MI->eraseFromParent();   // The pseudo instruction is gone now.
12203   return BB;
12204 }
12205
12206 MachineBasicBlock *
12207 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12208                                       MachineBasicBlock *BB) const {
12209   // This is pretty easy.  We're taking the value that we received from
12210   // our load from the relocation, sticking it in either RDI (x86-64)
12211   // or EAX and doing an indirect call.  The return value will then
12212   // be in the normal return register.
12213   const X86InstrInfo *TII
12214     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12215   DebugLoc DL = MI->getDebugLoc();
12216   MachineFunction *F = BB->getParent();
12217
12218   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12219   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12220
12221   if (Subtarget->is64Bit()) {
12222     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12223                                       TII->get(X86::MOV64rm), X86::RDI)
12224     .addReg(X86::RIP)
12225     .addImm(0).addReg(0)
12226     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12227                       MI->getOperand(3).getTargetFlags())
12228     .addReg(0);
12229     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12230     addDirectMem(MIB, X86::RDI);
12231   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12232     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12233                                       TII->get(X86::MOV32rm), X86::EAX)
12234     .addReg(0)
12235     .addImm(0).addReg(0)
12236     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12237                       MI->getOperand(3).getTargetFlags())
12238     .addReg(0);
12239     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12240     addDirectMem(MIB, X86::EAX);
12241   } else {
12242     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12243                                       TII->get(X86::MOV32rm), X86::EAX)
12244     .addReg(TII->getGlobalBaseReg(F))
12245     .addImm(0).addReg(0)
12246     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12247                       MI->getOperand(3).getTargetFlags())
12248     .addReg(0);
12249     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12250     addDirectMem(MIB, X86::EAX);
12251   }
12252
12253   MI->eraseFromParent(); // The pseudo instruction is gone now.
12254   return BB;
12255 }
12256
12257 MachineBasicBlock *
12258 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12259                                                MachineBasicBlock *BB) const {
12260   switch (MI->getOpcode()) {
12261   default: assert(0 && "Unexpected instr type to insert");
12262   case X86::TAILJMPd64:
12263   case X86::TAILJMPr64:
12264   case X86::TAILJMPm64:
12265     assert(0 && "TAILJMP64 would not be touched here.");
12266   case X86::TCRETURNdi64:
12267   case X86::TCRETURNri64:
12268   case X86::TCRETURNmi64:
12269     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12270     // On AMD64, additional defs should be added before register allocation.
12271     if (!Subtarget->isTargetWin64()) {
12272       MI->addRegisterDefined(X86::RSI);
12273       MI->addRegisterDefined(X86::RDI);
12274       MI->addRegisterDefined(X86::XMM6);
12275       MI->addRegisterDefined(X86::XMM7);
12276       MI->addRegisterDefined(X86::XMM8);
12277       MI->addRegisterDefined(X86::XMM9);
12278       MI->addRegisterDefined(X86::XMM10);
12279       MI->addRegisterDefined(X86::XMM11);
12280       MI->addRegisterDefined(X86::XMM12);
12281       MI->addRegisterDefined(X86::XMM13);
12282       MI->addRegisterDefined(X86::XMM14);
12283       MI->addRegisterDefined(X86::XMM15);
12284     }
12285     return BB;
12286   case X86::WIN_ALLOCA:
12287     return EmitLoweredWinAlloca(MI, BB);
12288   case X86::SEG_ALLOCA_32:
12289     return EmitLoweredSegAlloca(MI, BB, false);
12290   case X86::SEG_ALLOCA_64:
12291     return EmitLoweredSegAlloca(MI, BB, true);
12292   case X86::TLSCall_32:
12293   case X86::TLSCall_64:
12294     return EmitLoweredTLSCall(MI, BB);
12295   case X86::CMOV_GR8:
12296   case X86::CMOV_FR32:
12297   case X86::CMOV_FR64:
12298   case X86::CMOV_V4F32:
12299   case X86::CMOV_V2F64:
12300   case X86::CMOV_V2I64:
12301   case X86::CMOV_V8F32:
12302   case X86::CMOV_V4F64:
12303   case X86::CMOV_V4I64:
12304   case X86::CMOV_GR16:
12305   case X86::CMOV_GR32:
12306   case X86::CMOV_RFP32:
12307   case X86::CMOV_RFP64:
12308   case X86::CMOV_RFP80:
12309     return EmitLoweredSelect(MI, BB);
12310
12311   case X86::FP32_TO_INT16_IN_MEM:
12312   case X86::FP32_TO_INT32_IN_MEM:
12313   case X86::FP32_TO_INT64_IN_MEM:
12314   case X86::FP64_TO_INT16_IN_MEM:
12315   case X86::FP64_TO_INT32_IN_MEM:
12316   case X86::FP64_TO_INT64_IN_MEM:
12317   case X86::FP80_TO_INT16_IN_MEM:
12318   case X86::FP80_TO_INT32_IN_MEM:
12319   case X86::FP80_TO_INT64_IN_MEM: {
12320     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12321     DebugLoc DL = MI->getDebugLoc();
12322
12323     // Change the floating point control register to use "round towards zero"
12324     // mode when truncating to an integer value.
12325     MachineFunction *F = BB->getParent();
12326     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12327     addFrameReference(BuildMI(*BB, MI, DL,
12328                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12329
12330     // Load the old value of the high byte of the control word...
12331     unsigned OldCW =
12332       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12333     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12334                       CWFrameIdx);
12335
12336     // Set the high part to be round to zero...
12337     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12338       .addImm(0xC7F);
12339
12340     // Reload the modified control word now...
12341     addFrameReference(BuildMI(*BB, MI, DL,
12342                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12343
12344     // Restore the memory image of control word to original value
12345     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12346       .addReg(OldCW);
12347
12348     // Get the X86 opcode to use.
12349     unsigned Opc;
12350     switch (MI->getOpcode()) {
12351     default: llvm_unreachable("illegal opcode!");
12352     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12353     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12354     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12355     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12356     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12357     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12358     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12359     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12360     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12361     }
12362
12363     X86AddressMode AM;
12364     MachineOperand &Op = MI->getOperand(0);
12365     if (Op.isReg()) {
12366       AM.BaseType = X86AddressMode::RegBase;
12367       AM.Base.Reg = Op.getReg();
12368     } else {
12369       AM.BaseType = X86AddressMode::FrameIndexBase;
12370       AM.Base.FrameIndex = Op.getIndex();
12371     }
12372     Op = MI->getOperand(1);
12373     if (Op.isImm())
12374       AM.Scale = Op.getImm();
12375     Op = MI->getOperand(2);
12376     if (Op.isImm())
12377       AM.IndexReg = Op.getImm();
12378     Op = MI->getOperand(3);
12379     if (Op.isGlobal()) {
12380       AM.GV = Op.getGlobal();
12381     } else {
12382       AM.Disp = Op.getImm();
12383     }
12384     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12385                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12386
12387     // Reload the original control word now.
12388     addFrameReference(BuildMI(*BB, MI, DL,
12389                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12390
12391     MI->eraseFromParent();   // The pseudo instruction is gone now.
12392     return BB;
12393   }
12394     // String/text processing lowering.
12395   case X86::PCMPISTRM128REG:
12396   case X86::VPCMPISTRM128REG:
12397     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12398   case X86::PCMPISTRM128MEM:
12399   case X86::VPCMPISTRM128MEM:
12400     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12401   case X86::PCMPESTRM128REG:
12402   case X86::VPCMPESTRM128REG:
12403     return EmitPCMP(MI, BB, 5, false /* in mem */);
12404   case X86::PCMPESTRM128MEM:
12405   case X86::VPCMPESTRM128MEM:
12406     return EmitPCMP(MI, BB, 5, true /* in mem */);
12407
12408     // Thread synchronization.
12409   case X86::MONITOR:
12410     return EmitMonitor(MI, BB);
12411   case X86::MWAIT:
12412     return EmitMwait(MI, BB);
12413
12414     // Atomic Lowering.
12415   case X86::ATOMAND32:
12416     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12417                                                X86::AND32ri, X86::MOV32rm,
12418                                                X86::LCMPXCHG32,
12419                                                X86::NOT32r, X86::EAX,
12420                                                X86::GR32RegisterClass);
12421   case X86::ATOMOR32:
12422     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12423                                                X86::OR32ri, X86::MOV32rm,
12424                                                X86::LCMPXCHG32,
12425                                                X86::NOT32r, X86::EAX,
12426                                                X86::GR32RegisterClass);
12427   case X86::ATOMXOR32:
12428     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12429                                                X86::XOR32ri, X86::MOV32rm,
12430                                                X86::LCMPXCHG32,
12431                                                X86::NOT32r, X86::EAX,
12432                                                X86::GR32RegisterClass);
12433   case X86::ATOMNAND32:
12434     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12435                                                X86::AND32ri, X86::MOV32rm,
12436                                                X86::LCMPXCHG32,
12437                                                X86::NOT32r, X86::EAX,
12438                                                X86::GR32RegisterClass, true);
12439   case X86::ATOMMIN32:
12440     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12441   case X86::ATOMMAX32:
12442     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12443   case X86::ATOMUMIN32:
12444     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12445   case X86::ATOMUMAX32:
12446     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12447
12448   case X86::ATOMAND16:
12449     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12450                                                X86::AND16ri, X86::MOV16rm,
12451                                                X86::LCMPXCHG16,
12452                                                X86::NOT16r, X86::AX,
12453                                                X86::GR16RegisterClass);
12454   case X86::ATOMOR16:
12455     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12456                                                X86::OR16ri, X86::MOV16rm,
12457                                                X86::LCMPXCHG16,
12458                                                X86::NOT16r, X86::AX,
12459                                                X86::GR16RegisterClass);
12460   case X86::ATOMXOR16:
12461     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12462                                                X86::XOR16ri, X86::MOV16rm,
12463                                                X86::LCMPXCHG16,
12464                                                X86::NOT16r, X86::AX,
12465                                                X86::GR16RegisterClass);
12466   case X86::ATOMNAND16:
12467     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12468                                                X86::AND16ri, X86::MOV16rm,
12469                                                X86::LCMPXCHG16,
12470                                                X86::NOT16r, X86::AX,
12471                                                X86::GR16RegisterClass, true);
12472   case X86::ATOMMIN16:
12473     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12474   case X86::ATOMMAX16:
12475     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12476   case X86::ATOMUMIN16:
12477     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12478   case X86::ATOMUMAX16:
12479     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12480
12481   case X86::ATOMAND8:
12482     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12483                                                X86::AND8ri, X86::MOV8rm,
12484                                                X86::LCMPXCHG8,
12485                                                X86::NOT8r, X86::AL,
12486                                                X86::GR8RegisterClass);
12487   case X86::ATOMOR8:
12488     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12489                                                X86::OR8ri, X86::MOV8rm,
12490                                                X86::LCMPXCHG8,
12491                                                X86::NOT8r, X86::AL,
12492                                                X86::GR8RegisterClass);
12493   case X86::ATOMXOR8:
12494     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12495                                                X86::XOR8ri, X86::MOV8rm,
12496                                                X86::LCMPXCHG8,
12497                                                X86::NOT8r, X86::AL,
12498                                                X86::GR8RegisterClass);
12499   case X86::ATOMNAND8:
12500     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12501                                                X86::AND8ri, X86::MOV8rm,
12502                                                X86::LCMPXCHG8,
12503                                                X86::NOT8r, X86::AL,
12504                                                X86::GR8RegisterClass, true);
12505   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12506   // This group is for 64-bit host.
12507   case X86::ATOMAND64:
12508     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12509                                                X86::AND64ri32, X86::MOV64rm,
12510                                                X86::LCMPXCHG64,
12511                                                X86::NOT64r, X86::RAX,
12512                                                X86::GR64RegisterClass);
12513   case X86::ATOMOR64:
12514     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12515                                                X86::OR64ri32, X86::MOV64rm,
12516                                                X86::LCMPXCHG64,
12517                                                X86::NOT64r, X86::RAX,
12518                                                X86::GR64RegisterClass);
12519   case X86::ATOMXOR64:
12520     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12521                                                X86::XOR64ri32, X86::MOV64rm,
12522                                                X86::LCMPXCHG64,
12523                                                X86::NOT64r, X86::RAX,
12524                                                X86::GR64RegisterClass);
12525   case X86::ATOMNAND64:
12526     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12527                                                X86::AND64ri32, X86::MOV64rm,
12528                                                X86::LCMPXCHG64,
12529                                                X86::NOT64r, X86::RAX,
12530                                                X86::GR64RegisterClass, true);
12531   case X86::ATOMMIN64:
12532     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12533   case X86::ATOMMAX64:
12534     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12535   case X86::ATOMUMIN64:
12536     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12537   case X86::ATOMUMAX64:
12538     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12539
12540   // This group does 64-bit operations on a 32-bit host.
12541   case X86::ATOMAND6432:
12542     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12543                                                X86::AND32rr, X86::AND32rr,
12544                                                X86::AND32ri, X86::AND32ri,
12545                                                false);
12546   case X86::ATOMOR6432:
12547     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12548                                                X86::OR32rr, X86::OR32rr,
12549                                                X86::OR32ri, X86::OR32ri,
12550                                                false);
12551   case X86::ATOMXOR6432:
12552     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12553                                                X86::XOR32rr, X86::XOR32rr,
12554                                                X86::XOR32ri, X86::XOR32ri,
12555                                                false);
12556   case X86::ATOMNAND6432:
12557     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12558                                                X86::AND32rr, X86::AND32rr,
12559                                                X86::AND32ri, X86::AND32ri,
12560                                                true);
12561   case X86::ATOMADD6432:
12562     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12563                                                X86::ADD32rr, X86::ADC32rr,
12564                                                X86::ADD32ri, X86::ADC32ri,
12565                                                false);
12566   case X86::ATOMSUB6432:
12567     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12568                                                X86::SUB32rr, X86::SBB32rr,
12569                                                X86::SUB32ri, X86::SBB32ri,
12570                                                false);
12571   case X86::ATOMSWAP6432:
12572     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12573                                                X86::MOV32rr, X86::MOV32rr,
12574                                                X86::MOV32ri, X86::MOV32ri,
12575                                                false);
12576   case X86::VASTART_SAVE_XMM_REGS:
12577     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12578
12579   case X86::VAARG_64:
12580     return EmitVAARG64WithCustomInserter(MI, BB);
12581   }
12582 }
12583
12584 //===----------------------------------------------------------------------===//
12585 //                           X86 Optimization Hooks
12586 //===----------------------------------------------------------------------===//
12587
12588 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12589                                                        const APInt &Mask,
12590                                                        APInt &KnownZero,
12591                                                        APInt &KnownOne,
12592                                                        const SelectionDAG &DAG,
12593                                                        unsigned Depth) const {
12594   unsigned Opc = Op.getOpcode();
12595   assert((Opc >= ISD::BUILTIN_OP_END ||
12596           Opc == ISD::INTRINSIC_WO_CHAIN ||
12597           Opc == ISD::INTRINSIC_W_CHAIN ||
12598           Opc == ISD::INTRINSIC_VOID) &&
12599          "Should use MaskedValueIsZero if you don't know whether Op"
12600          " is a target node!");
12601
12602   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12603   switch (Opc) {
12604   default: break;
12605   case X86ISD::ADD:
12606   case X86ISD::SUB:
12607   case X86ISD::ADC:
12608   case X86ISD::SBB:
12609   case X86ISD::SMUL:
12610   case X86ISD::UMUL:
12611   case X86ISD::INC:
12612   case X86ISD::DEC:
12613   case X86ISD::OR:
12614   case X86ISD::XOR:
12615   case X86ISD::AND:
12616     // These nodes' second result is a boolean.
12617     if (Op.getResNo() == 0)
12618       break;
12619     // Fallthrough
12620   case X86ISD::SETCC:
12621     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12622                                        Mask.getBitWidth() - 1);
12623     break;
12624   case ISD::INTRINSIC_WO_CHAIN: {
12625     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12626     unsigned NumLoBits = 0;
12627     switch (IntId) {
12628     default: break;
12629     case Intrinsic::x86_sse_movmsk_ps:
12630     case Intrinsic::x86_avx_movmsk_ps_256:
12631     case Intrinsic::x86_sse2_movmsk_pd:
12632     case Intrinsic::x86_avx_movmsk_pd_256:
12633     case Intrinsic::x86_mmx_pmovmskb:
12634     case Intrinsic::x86_sse2_pmovmskb_128: {
12635       // High bits of movmskp{s|d}, pmovmskb are known zero.
12636       switch (IntId) {
12637         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12638         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12639         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12640         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12641         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12642         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12643       }
12644       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12645                                         Mask.getBitWidth() - NumLoBits);
12646       break;
12647     }
12648     }
12649     break;
12650   }
12651   }
12652 }
12653
12654 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12655                                                          unsigned Depth) const {
12656   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12657   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12658     return Op.getValueType().getScalarType().getSizeInBits();
12659
12660   // Fallback case.
12661   return 1;
12662 }
12663
12664 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12665 /// node is a GlobalAddress + offset.
12666 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12667                                        const GlobalValue* &GA,
12668                                        int64_t &Offset) const {
12669   if (N->getOpcode() == X86ISD::Wrapper) {
12670     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12671       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12672       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12673       return true;
12674     }
12675   }
12676   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12677 }
12678
12679 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12680 /// same as extracting the high 128-bit part of 256-bit vector and then
12681 /// inserting the result into the low part of a new 256-bit vector
12682 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12683   EVT VT = SVOp->getValueType(0);
12684   int NumElems = VT.getVectorNumElements();
12685
12686   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12687   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12688     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12689         SVOp->getMaskElt(j) >= 0)
12690       return false;
12691
12692   return true;
12693 }
12694
12695 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12696 /// same as extracting the low 128-bit part of 256-bit vector and then
12697 /// inserting the result into the high part of a new 256-bit vector
12698 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12699   EVT VT = SVOp->getValueType(0);
12700   int NumElems = VT.getVectorNumElements();
12701
12702   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12703   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12704     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12705         SVOp->getMaskElt(j) >= 0)
12706       return false;
12707
12708   return true;
12709 }
12710
12711 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12712 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12713                                         TargetLowering::DAGCombinerInfo &DCI) {
12714   DebugLoc dl = N->getDebugLoc();
12715   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12716   SDValue V1 = SVOp->getOperand(0);
12717   SDValue V2 = SVOp->getOperand(1);
12718   EVT VT = SVOp->getValueType(0);
12719   int NumElems = VT.getVectorNumElements();
12720
12721   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12722       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12723     //
12724     //                   0,0,0,...
12725     //                      |
12726     //    V      UNDEF    BUILD_VECTOR    UNDEF
12727     //     \      /           \           /
12728     //  CONCAT_VECTOR         CONCAT_VECTOR
12729     //         \                  /
12730     //          \                /
12731     //          RESULT: V + zero extended
12732     //
12733     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12734         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12735         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12736       return SDValue();
12737
12738     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12739       return SDValue();
12740
12741     // To match the shuffle mask, the first half of the mask should
12742     // be exactly the first vector, and all the rest a splat with the
12743     // first element of the second one.
12744     for (int i = 0; i < NumElems/2; ++i)
12745       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12746           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12747         return SDValue();
12748
12749     // Emit a zeroed vector and insert the desired subvector on its
12750     // first half.
12751     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12752     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12753                          DAG.getConstant(0, MVT::i32), DAG, dl);
12754     return DCI.CombineTo(N, InsV);
12755   }
12756
12757   //===--------------------------------------------------------------------===//
12758   // Combine some shuffles into subvector extracts and inserts:
12759   //
12760
12761   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12762   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12763     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12764                                     DAG, dl);
12765     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12766                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12767     return DCI.CombineTo(N, InsV);
12768   }
12769
12770   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12771   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12772     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12773     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12774                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12775     return DCI.CombineTo(N, InsV);
12776   }
12777
12778   return SDValue();
12779 }
12780
12781 /// PerformShuffleCombine - Performs several different shuffle combines.
12782 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12783                                      TargetLowering::DAGCombinerInfo &DCI,
12784                                      const X86Subtarget *Subtarget) {
12785   DebugLoc dl = N->getDebugLoc();
12786   EVT VT = N->getValueType(0);
12787
12788   // Don't create instructions with illegal types after legalize types has run.
12789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12790   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12791     return SDValue();
12792
12793   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12794   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12795       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12796     return PerformShuffleCombine256(N, DAG, DCI);
12797
12798   // Only handle 128 wide vector from here on.
12799   if (VT.getSizeInBits() != 128)
12800     return SDValue();
12801
12802   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12803   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12804   // consecutive, non-overlapping, and in the right order.
12805   SmallVector<SDValue, 16> Elts;
12806   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12807     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12808
12809   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12810 }
12811
12812 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12813 /// generation and convert it from being a bunch of shuffles and extracts
12814 /// to a simple store and scalar loads to extract the elements.
12815 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12816                                                 const TargetLowering &TLI) {
12817   SDValue InputVector = N->getOperand(0);
12818
12819   // Only operate on vectors of 4 elements, where the alternative shuffling
12820   // gets to be more expensive.
12821   if (InputVector.getValueType() != MVT::v4i32)
12822     return SDValue();
12823
12824   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12825   // single use which is a sign-extend or zero-extend, and all elements are
12826   // used.
12827   SmallVector<SDNode *, 4> Uses;
12828   unsigned ExtractedElements = 0;
12829   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12830        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12831     if (UI.getUse().getResNo() != InputVector.getResNo())
12832       return SDValue();
12833
12834     SDNode *Extract = *UI;
12835     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12836       return SDValue();
12837
12838     if (Extract->getValueType(0) != MVT::i32)
12839       return SDValue();
12840     if (!Extract->hasOneUse())
12841       return SDValue();
12842     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12843         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12844       return SDValue();
12845     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12846       return SDValue();
12847
12848     // Record which element was extracted.
12849     ExtractedElements |=
12850       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12851
12852     Uses.push_back(Extract);
12853   }
12854
12855   // If not all the elements were used, this may not be worthwhile.
12856   if (ExtractedElements != 15)
12857     return SDValue();
12858
12859   // Ok, we've now decided to do the transformation.
12860   DebugLoc dl = InputVector.getDebugLoc();
12861
12862   // Store the value to a temporary stack slot.
12863   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12864   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12865                             MachinePointerInfo(), false, false, 0);
12866
12867   // Replace each use (extract) with a load of the appropriate element.
12868   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12869        UE = Uses.end(); UI != UE; ++UI) {
12870     SDNode *Extract = *UI;
12871
12872     // cOMpute the element's address.
12873     SDValue Idx = Extract->getOperand(1);
12874     unsigned EltSize =
12875         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12876     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12877     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12878
12879     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12880                                      StackPtr, OffsetVal);
12881
12882     // Load the scalar.
12883     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12884                                      ScalarAddr, MachinePointerInfo(),
12885                                      false, false, false, 0);
12886
12887     // Replace the exact with the load.
12888     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12889   }
12890
12891   // The replacement was made in place; don't return anything.
12892   return SDValue();
12893 }
12894
12895 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12896 /// nodes.
12897 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12898                                     const X86Subtarget *Subtarget) {
12899   DebugLoc DL = N->getDebugLoc();
12900   SDValue Cond = N->getOperand(0);
12901   // Get the LHS/RHS of the select.
12902   SDValue LHS = N->getOperand(1);
12903   SDValue RHS = N->getOperand(2);
12904   EVT VT = LHS.getValueType();
12905
12906   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12907   // instructions match the semantics of the common C idiom x<y?x:y but not
12908   // x<=y?x:y, because of how they handle negative zero (which can be
12909   // ignored in unsafe-math mode).
12910   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12911       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12912       (Subtarget->hasXMMInt() ||
12913        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12914     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12915
12916     unsigned Opcode = 0;
12917     // Check for x CC y ? x : y.
12918     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12919         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12920       switch (CC) {
12921       default: break;
12922       case ISD::SETULT:
12923         // Converting this to a min would handle NaNs incorrectly, and swapping
12924         // the operands would cause it to handle comparisons between positive
12925         // and negative zero incorrectly.
12926         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12927           if (!UnsafeFPMath &&
12928               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12929             break;
12930           std::swap(LHS, RHS);
12931         }
12932         Opcode = X86ISD::FMIN;
12933         break;
12934       case ISD::SETOLE:
12935         // Converting this to a min would handle comparisons between positive
12936         // and negative zero incorrectly.
12937         if (!UnsafeFPMath &&
12938             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12939           break;
12940         Opcode = X86ISD::FMIN;
12941         break;
12942       case ISD::SETULE:
12943         // Converting this to a min would handle both negative zeros and NaNs
12944         // incorrectly, but we can swap the operands to fix both.
12945         std::swap(LHS, RHS);
12946       case ISD::SETOLT:
12947       case ISD::SETLT:
12948       case ISD::SETLE:
12949         Opcode = X86ISD::FMIN;
12950         break;
12951
12952       case ISD::SETOGE:
12953         // Converting this to a max would handle comparisons between positive
12954         // and negative zero incorrectly.
12955         if (!UnsafeFPMath &&
12956             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12957           break;
12958         Opcode = X86ISD::FMAX;
12959         break;
12960       case ISD::SETUGT:
12961         // Converting this to a max would handle NaNs incorrectly, and swapping
12962         // the operands would cause it to handle comparisons between positive
12963         // and negative zero incorrectly.
12964         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12965           if (!UnsafeFPMath &&
12966               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12967             break;
12968           std::swap(LHS, RHS);
12969         }
12970         Opcode = X86ISD::FMAX;
12971         break;
12972       case ISD::SETUGE:
12973         // Converting this to a max would handle both negative zeros and NaNs
12974         // incorrectly, but we can swap the operands to fix both.
12975         std::swap(LHS, RHS);
12976       case ISD::SETOGT:
12977       case ISD::SETGT:
12978       case ISD::SETGE:
12979         Opcode = X86ISD::FMAX;
12980         break;
12981       }
12982     // Check for x CC y ? y : x -- a min/max with reversed arms.
12983     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12984                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12985       switch (CC) {
12986       default: break;
12987       case ISD::SETOGE:
12988         // Converting this to a min would handle comparisons between positive
12989         // and negative zero incorrectly, and swapping the operands would
12990         // cause it to handle NaNs incorrectly.
12991         if (!UnsafeFPMath &&
12992             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12993           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12994             break;
12995           std::swap(LHS, RHS);
12996         }
12997         Opcode = X86ISD::FMIN;
12998         break;
12999       case ISD::SETUGT:
13000         // Converting this to a min would handle NaNs incorrectly.
13001         if (!UnsafeFPMath &&
13002             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13003           break;
13004         Opcode = X86ISD::FMIN;
13005         break;
13006       case ISD::SETUGE:
13007         // Converting this to a min would handle both negative zeros and NaNs
13008         // incorrectly, but we can swap the operands to fix both.
13009         std::swap(LHS, RHS);
13010       case ISD::SETOGT:
13011       case ISD::SETGT:
13012       case ISD::SETGE:
13013         Opcode = X86ISD::FMIN;
13014         break;
13015
13016       case ISD::SETULT:
13017         // Converting this to a max would handle NaNs incorrectly.
13018         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13019           break;
13020         Opcode = X86ISD::FMAX;
13021         break;
13022       case ISD::SETOLE:
13023         // Converting this to a max would handle comparisons between positive
13024         // and negative zero incorrectly, and swapping the operands would
13025         // cause it to handle NaNs incorrectly.
13026         if (!UnsafeFPMath &&
13027             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13028           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13029             break;
13030           std::swap(LHS, RHS);
13031         }
13032         Opcode = X86ISD::FMAX;
13033         break;
13034       case ISD::SETULE:
13035         // Converting this to a max would handle both negative zeros and NaNs
13036         // incorrectly, but we can swap the operands to fix both.
13037         std::swap(LHS, RHS);
13038       case ISD::SETOLT:
13039       case ISD::SETLT:
13040       case ISD::SETLE:
13041         Opcode = X86ISD::FMAX;
13042         break;
13043       }
13044     }
13045
13046     if (Opcode)
13047       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13048   }
13049
13050   // If this is a select between two integer constants, try to do some
13051   // optimizations.
13052   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13053     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13054       // Don't do this for crazy integer types.
13055       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13056         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13057         // so that TrueC (the true value) is larger than FalseC.
13058         bool NeedsCondInvert = false;
13059
13060         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13061             // Efficiently invertible.
13062             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13063              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13064               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13065           NeedsCondInvert = true;
13066           std::swap(TrueC, FalseC);
13067         }
13068
13069         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13070         if (FalseC->getAPIntValue() == 0 &&
13071             TrueC->getAPIntValue().isPowerOf2()) {
13072           if (NeedsCondInvert) // Invert the condition if needed.
13073             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13074                                DAG.getConstant(1, Cond.getValueType()));
13075
13076           // Zero extend the condition if needed.
13077           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13078
13079           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13080           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13081                              DAG.getConstant(ShAmt, MVT::i8));
13082         }
13083
13084         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13085         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13086           if (NeedsCondInvert) // Invert the condition if needed.
13087             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13088                                DAG.getConstant(1, Cond.getValueType()));
13089
13090           // Zero extend the condition if needed.
13091           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13092                              FalseC->getValueType(0), Cond);
13093           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13094                              SDValue(FalseC, 0));
13095         }
13096
13097         // Optimize cases that will turn into an LEA instruction.  This requires
13098         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13099         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13100           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13101           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13102
13103           bool isFastMultiplier = false;
13104           if (Diff < 10) {
13105             switch ((unsigned char)Diff) {
13106               default: break;
13107               case 1:  // result = add base, cond
13108               case 2:  // result = lea base(    , cond*2)
13109               case 3:  // result = lea base(cond, cond*2)
13110               case 4:  // result = lea base(    , cond*4)
13111               case 5:  // result = lea base(cond, cond*4)
13112               case 8:  // result = lea base(    , cond*8)
13113               case 9:  // result = lea base(cond, cond*8)
13114                 isFastMultiplier = true;
13115                 break;
13116             }
13117           }
13118
13119           if (isFastMultiplier) {
13120             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13121             if (NeedsCondInvert) // Invert the condition if needed.
13122               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13123                                  DAG.getConstant(1, Cond.getValueType()));
13124
13125             // Zero extend the condition if needed.
13126             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13127                                Cond);
13128             // Scale the condition by the difference.
13129             if (Diff != 1)
13130               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13131                                  DAG.getConstant(Diff, Cond.getValueType()));
13132
13133             // Add the base if non-zero.
13134             if (FalseC->getAPIntValue() != 0)
13135               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13136                                  SDValue(FalseC, 0));
13137             return Cond;
13138           }
13139         }
13140       }
13141   }
13142
13143   return SDValue();
13144 }
13145
13146 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13147 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13148                                   TargetLowering::DAGCombinerInfo &DCI) {
13149   DebugLoc DL = N->getDebugLoc();
13150
13151   // If the flag operand isn't dead, don't touch this CMOV.
13152   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13153     return SDValue();
13154
13155   SDValue FalseOp = N->getOperand(0);
13156   SDValue TrueOp = N->getOperand(1);
13157   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13158   SDValue Cond = N->getOperand(3);
13159   if (CC == X86::COND_E || CC == X86::COND_NE) {
13160     switch (Cond.getOpcode()) {
13161     default: break;
13162     case X86ISD::BSR:
13163     case X86ISD::BSF:
13164       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13165       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13166         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13167     }
13168   }
13169
13170   // If this is a select between two integer constants, try to do some
13171   // optimizations.  Note that the operands are ordered the opposite of SELECT
13172   // operands.
13173   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13174     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13175       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13176       // larger than FalseC (the false value).
13177       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13178         CC = X86::GetOppositeBranchCondition(CC);
13179         std::swap(TrueC, FalseC);
13180       }
13181
13182       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13183       // This is efficient for any integer data type (including i8/i16) and
13184       // shift amount.
13185       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13186         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13187                            DAG.getConstant(CC, MVT::i8), Cond);
13188
13189         // Zero extend the condition if needed.
13190         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13191
13192         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13193         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13194                            DAG.getConstant(ShAmt, MVT::i8));
13195         if (N->getNumValues() == 2)  // Dead flag value?
13196           return DCI.CombineTo(N, Cond, SDValue());
13197         return Cond;
13198       }
13199
13200       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13201       // for any integer data type, including i8/i16.
13202       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13203         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13204                            DAG.getConstant(CC, MVT::i8), Cond);
13205
13206         // Zero extend the condition if needed.
13207         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13208                            FalseC->getValueType(0), Cond);
13209         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13210                            SDValue(FalseC, 0));
13211
13212         if (N->getNumValues() == 2)  // Dead flag value?
13213           return DCI.CombineTo(N, Cond, SDValue());
13214         return Cond;
13215       }
13216
13217       // Optimize cases that will turn into an LEA instruction.  This requires
13218       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13219       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13220         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13221         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13222
13223         bool isFastMultiplier = false;
13224         if (Diff < 10) {
13225           switch ((unsigned char)Diff) {
13226           default: break;
13227           case 1:  // result = add base, cond
13228           case 2:  // result = lea base(    , cond*2)
13229           case 3:  // result = lea base(cond, cond*2)
13230           case 4:  // result = lea base(    , cond*4)
13231           case 5:  // result = lea base(cond, cond*4)
13232           case 8:  // result = lea base(    , cond*8)
13233           case 9:  // result = lea base(cond, cond*8)
13234             isFastMultiplier = true;
13235             break;
13236           }
13237         }
13238
13239         if (isFastMultiplier) {
13240           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13241           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13242                              DAG.getConstant(CC, MVT::i8), Cond);
13243           // Zero extend the condition if needed.
13244           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13245                              Cond);
13246           // Scale the condition by the difference.
13247           if (Diff != 1)
13248             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13249                                DAG.getConstant(Diff, Cond.getValueType()));
13250
13251           // Add the base if non-zero.
13252           if (FalseC->getAPIntValue() != 0)
13253             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13254                                SDValue(FalseC, 0));
13255           if (N->getNumValues() == 2)  // Dead flag value?
13256             return DCI.CombineTo(N, Cond, SDValue());
13257           return Cond;
13258         }
13259       }
13260     }
13261   }
13262   return SDValue();
13263 }
13264
13265
13266 /// PerformMulCombine - Optimize a single multiply with constant into two
13267 /// in order to implement it with two cheaper instructions, e.g.
13268 /// LEA + SHL, LEA + LEA.
13269 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13270                                  TargetLowering::DAGCombinerInfo &DCI) {
13271   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13272     return SDValue();
13273
13274   EVT VT = N->getValueType(0);
13275   if (VT != MVT::i64)
13276     return SDValue();
13277
13278   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13279   if (!C)
13280     return SDValue();
13281   uint64_t MulAmt = C->getZExtValue();
13282   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13283     return SDValue();
13284
13285   uint64_t MulAmt1 = 0;
13286   uint64_t MulAmt2 = 0;
13287   if ((MulAmt % 9) == 0) {
13288     MulAmt1 = 9;
13289     MulAmt2 = MulAmt / 9;
13290   } else if ((MulAmt % 5) == 0) {
13291     MulAmt1 = 5;
13292     MulAmt2 = MulAmt / 5;
13293   } else if ((MulAmt % 3) == 0) {
13294     MulAmt1 = 3;
13295     MulAmt2 = MulAmt / 3;
13296   }
13297   if (MulAmt2 &&
13298       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13299     DebugLoc DL = N->getDebugLoc();
13300
13301     if (isPowerOf2_64(MulAmt2) &&
13302         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13303       // If second multiplifer is pow2, issue it first. We want the multiply by
13304       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13305       // is an add.
13306       std::swap(MulAmt1, MulAmt2);
13307
13308     SDValue NewMul;
13309     if (isPowerOf2_64(MulAmt1))
13310       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13311                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13312     else
13313       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13314                            DAG.getConstant(MulAmt1, VT));
13315
13316     if (isPowerOf2_64(MulAmt2))
13317       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13318                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13319     else
13320       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13321                            DAG.getConstant(MulAmt2, VT));
13322
13323     // Do not add new nodes to DAG combiner worklist.
13324     DCI.CombineTo(N, NewMul, false);
13325   }
13326   return SDValue();
13327 }
13328
13329 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13330   SDValue N0 = N->getOperand(0);
13331   SDValue N1 = N->getOperand(1);
13332   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13333   EVT VT = N0.getValueType();
13334
13335   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13336   // since the result of setcc_c is all zero's or all ones.
13337   if (VT.isInteger() && !VT.isVector() &&
13338       N1C && N0.getOpcode() == ISD::AND &&
13339       N0.getOperand(1).getOpcode() == ISD::Constant) {
13340     SDValue N00 = N0.getOperand(0);
13341     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13342         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13343           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13344          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13345       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13346       APInt ShAmt = N1C->getAPIntValue();
13347       Mask = Mask.shl(ShAmt);
13348       if (Mask != 0)
13349         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13350                            N00, DAG.getConstant(Mask, VT));
13351     }
13352   }
13353
13354
13355   // Hardware support for vector shifts is sparse which makes us scalarize the
13356   // vector operations in many cases. Also, on sandybridge ADD is faster than
13357   // shl.
13358   // (shl V, 1) -> add V,V
13359   if (isSplatVector(N1.getNode())) {
13360     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13361     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13362     // We shift all of the values by one. In many cases we do not have
13363     // hardware support for this operation. This is better expressed as an ADD
13364     // of two values.
13365     if (N1C && (1 == N1C->getZExtValue())) {
13366       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13367     }
13368   }
13369
13370   return SDValue();
13371 }
13372
13373 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13374 ///                       when possible.
13375 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13376                                    const X86Subtarget *Subtarget) {
13377   EVT VT = N->getValueType(0);
13378   if (N->getOpcode() == ISD::SHL) {
13379     SDValue V = PerformSHLCombine(N, DAG);
13380     if (V.getNode()) return V;
13381   }
13382
13383   // On X86 with SSE2 support, we can transform this to a vector shift if
13384   // all elements are shifted by the same amount.  We can't do this in legalize
13385   // because the a constant vector is typically transformed to a constant pool
13386   // so we have no knowledge of the shift amount.
13387   if (!Subtarget->hasXMMInt())
13388     return SDValue();
13389
13390   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13391     return SDValue();
13392
13393   SDValue ShAmtOp = N->getOperand(1);
13394   EVT EltVT = VT.getVectorElementType();
13395   DebugLoc DL = N->getDebugLoc();
13396   SDValue BaseShAmt = SDValue();
13397   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13398     unsigned NumElts = VT.getVectorNumElements();
13399     unsigned i = 0;
13400     for (; i != NumElts; ++i) {
13401       SDValue Arg = ShAmtOp.getOperand(i);
13402       if (Arg.getOpcode() == ISD::UNDEF) continue;
13403       BaseShAmt = Arg;
13404       break;
13405     }
13406     for (; i != NumElts; ++i) {
13407       SDValue Arg = ShAmtOp.getOperand(i);
13408       if (Arg.getOpcode() == ISD::UNDEF) continue;
13409       if (Arg != BaseShAmt) {
13410         return SDValue();
13411       }
13412     }
13413   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13414              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13415     SDValue InVec = ShAmtOp.getOperand(0);
13416     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13417       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13418       unsigned i = 0;
13419       for (; i != NumElts; ++i) {
13420         SDValue Arg = InVec.getOperand(i);
13421         if (Arg.getOpcode() == ISD::UNDEF) continue;
13422         BaseShAmt = Arg;
13423         break;
13424       }
13425     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13426        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13427          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13428          if (C->getZExtValue() == SplatIdx)
13429            BaseShAmt = InVec.getOperand(1);
13430        }
13431     }
13432     if (BaseShAmt.getNode() == 0)
13433       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13434                               DAG.getIntPtrConstant(0));
13435   } else
13436     return SDValue();
13437
13438   // The shift amount is an i32.
13439   if (EltVT.bitsGT(MVT::i32))
13440     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13441   else if (EltVT.bitsLT(MVT::i32))
13442     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13443
13444   // The shift amount is identical so we can do a vector shift.
13445   SDValue  ValOp = N->getOperand(0);
13446   switch (N->getOpcode()) {
13447   default:
13448     llvm_unreachable("Unknown shift opcode!");
13449     break;
13450   case ISD::SHL:
13451     if (VT == MVT::v2i64)
13452       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13453                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13454                          ValOp, BaseShAmt);
13455     if (VT == MVT::v4i32)
13456       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13457                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13458                          ValOp, BaseShAmt);
13459     if (VT == MVT::v8i16)
13460       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13461                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13462                          ValOp, BaseShAmt);
13463     break;
13464   case ISD::SRA:
13465     if (VT == MVT::v4i32)
13466       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13467                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13468                          ValOp, BaseShAmt);
13469     if (VT == MVT::v8i16)
13470       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13471                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13472                          ValOp, BaseShAmt);
13473     break;
13474   case ISD::SRL:
13475     if (VT == MVT::v2i64)
13476       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13477                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13478                          ValOp, BaseShAmt);
13479     if (VT == MVT::v4i32)
13480       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13481                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13482                          ValOp, BaseShAmt);
13483     if (VT ==  MVT::v8i16)
13484       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13485                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13486                          ValOp, BaseShAmt);
13487     break;
13488   }
13489   return SDValue();
13490 }
13491
13492
13493 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13494 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13495 // and friends.  Likewise for OR -> CMPNEQSS.
13496 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13497                             TargetLowering::DAGCombinerInfo &DCI,
13498                             const X86Subtarget *Subtarget) {
13499   unsigned opcode;
13500
13501   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13502   // we're requiring SSE2 for both.
13503   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13504     SDValue N0 = N->getOperand(0);
13505     SDValue N1 = N->getOperand(1);
13506     SDValue CMP0 = N0->getOperand(1);
13507     SDValue CMP1 = N1->getOperand(1);
13508     DebugLoc DL = N->getDebugLoc();
13509
13510     // The SETCCs should both refer to the same CMP.
13511     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13512       return SDValue();
13513
13514     SDValue CMP00 = CMP0->getOperand(0);
13515     SDValue CMP01 = CMP0->getOperand(1);
13516     EVT     VT    = CMP00.getValueType();
13517
13518     if (VT == MVT::f32 || VT == MVT::f64) {
13519       bool ExpectingFlags = false;
13520       // Check for any users that want flags:
13521       for (SDNode::use_iterator UI = N->use_begin(),
13522              UE = N->use_end();
13523            !ExpectingFlags && UI != UE; ++UI)
13524         switch (UI->getOpcode()) {
13525         default:
13526         case ISD::BR_CC:
13527         case ISD::BRCOND:
13528         case ISD::SELECT:
13529           ExpectingFlags = true;
13530           break;
13531         case ISD::CopyToReg:
13532         case ISD::SIGN_EXTEND:
13533         case ISD::ZERO_EXTEND:
13534         case ISD::ANY_EXTEND:
13535           break;
13536         }
13537
13538       if (!ExpectingFlags) {
13539         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13540         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13541
13542         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13543           X86::CondCode tmp = cc0;
13544           cc0 = cc1;
13545           cc1 = tmp;
13546         }
13547
13548         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13549             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13550           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13551           X86ISD::NodeType NTOperator = is64BitFP ?
13552             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13553           // FIXME: need symbolic constants for these magic numbers.
13554           // See X86ATTInstPrinter.cpp:printSSECC().
13555           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13556           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13557                                               DAG.getConstant(x86cc, MVT::i8));
13558           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13559                                               OnesOrZeroesF);
13560           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13561                                       DAG.getConstant(1, MVT::i32));
13562           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13563           return OneBitOfTruth;
13564         }
13565       }
13566     }
13567   }
13568   return SDValue();
13569 }
13570
13571 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13572 /// so it can be folded inside ANDNP.
13573 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13574   EVT VT = N->getValueType(0);
13575
13576   // Match direct AllOnes for 128 and 256-bit vectors
13577   if (ISD::isBuildVectorAllOnes(N))
13578     return true;
13579
13580   // Look through a bit convert.
13581   if (N->getOpcode() == ISD::BITCAST)
13582     N = N->getOperand(0).getNode();
13583
13584   // Sometimes the operand may come from a insert_subvector building a 256-bit
13585   // allones vector
13586   if (VT.getSizeInBits() == 256 &&
13587       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13588     SDValue V1 = N->getOperand(0);
13589     SDValue V2 = N->getOperand(1);
13590
13591     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13592         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13593         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13594         ISD::isBuildVectorAllOnes(V2.getNode()))
13595       return true;
13596   }
13597
13598   return false;
13599 }
13600
13601 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13602                                  TargetLowering::DAGCombinerInfo &DCI,
13603                                  const X86Subtarget *Subtarget) {
13604   if (DCI.isBeforeLegalizeOps())
13605     return SDValue();
13606
13607   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13608   if (R.getNode())
13609     return R;
13610
13611   EVT VT = N->getValueType(0);
13612
13613   // Create ANDN, BLSI, and BLSR instructions
13614   // BLSI is X & (-X)
13615   // BLSR is X & (X-1)
13616   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13617     SDValue N0 = N->getOperand(0);
13618     SDValue N1 = N->getOperand(1);
13619     DebugLoc DL = N->getDebugLoc();
13620
13621     // Check LHS for not
13622     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13623       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13624     // Check RHS for not
13625     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13626       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13627
13628     // Check LHS for neg
13629     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13630         isZero(N0.getOperand(0)))
13631       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13632
13633     // Check RHS for neg
13634     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13635         isZero(N1.getOperand(0)))
13636       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13637
13638     // Check LHS for X-1
13639     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13640         isAllOnes(N0.getOperand(1)))
13641       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13642
13643     // Check RHS for X-1
13644     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13645         isAllOnes(N1.getOperand(1)))
13646       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13647
13648     return SDValue();
13649   }
13650
13651   // Want to form ANDNP nodes:
13652   // 1) In the hopes of then easily combining them with OR and AND nodes
13653   //    to form PBLEND/PSIGN.
13654   // 2) To match ANDN packed intrinsics
13655   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13656     return SDValue();
13657
13658   SDValue N0 = N->getOperand(0);
13659   SDValue N1 = N->getOperand(1);
13660   DebugLoc DL = N->getDebugLoc();
13661
13662   // Check LHS for vnot
13663   if (N0.getOpcode() == ISD::XOR &&
13664       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13665       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13666     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13667
13668   // Check RHS for vnot
13669   if (N1.getOpcode() == ISD::XOR &&
13670       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13671       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13672     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13673
13674   return SDValue();
13675 }
13676
13677 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13678                                 TargetLowering::DAGCombinerInfo &DCI,
13679                                 const X86Subtarget *Subtarget) {
13680   if (DCI.isBeforeLegalizeOps())
13681     return SDValue();
13682
13683   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13684   if (R.getNode())
13685     return R;
13686
13687   EVT VT = N->getValueType(0);
13688   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13689     return SDValue();
13690
13691   SDValue N0 = N->getOperand(0);
13692   SDValue N1 = N->getOperand(1);
13693
13694   // look for psign/blend
13695   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13696     if (VT == MVT::v2i64) {
13697       // Canonicalize pandn to RHS
13698       if (N0.getOpcode() == X86ISD::ANDNP)
13699         std::swap(N0, N1);
13700       // or (and (m, x), (pandn m, y))
13701       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13702         SDValue Mask = N1.getOperand(0);
13703         SDValue X    = N1.getOperand(1);
13704         SDValue Y;
13705         if (N0.getOperand(0) == Mask)
13706           Y = N0.getOperand(1);
13707         if (N0.getOperand(1) == Mask)
13708           Y = N0.getOperand(0);
13709
13710         // Check to see if the mask appeared in both the AND and ANDNP and
13711         if (!Y.getNode())
13712           return SDValue();
13713
13714         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13715         if (Mask.getOpcode() != ISD::BITCAST ||
13716             X.getOpcode() != ISD::BITCAST ||
13717             Y.getOpcode() != ISD::BITCAST)
13718           return SDValue();
13719
13720         // Look through mask bitcast.
13721         Mask = Mask.getOperand(0);
13722         EVT MaskVT = Mask.getValueType();
13723
13724         // Validate that the Mask operand is a vector sra node.  The sra node
13725         // will be an intrinsic.
13726         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13727           return SDValue();
13728
13729         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13730         // there is no psrai.b
13731         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13732         case Intrinsic::x86_sse2_psrai_w:
13733         case Intrinsic::x86_sse2_psrai_d:
13734           break;
13735         default: return SDValue();
13736         }
13737
13738         // Check that the SRA is all signbits.
13739         SDValue SraC = Mask.getOperand(2);
13740         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13741         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13742         if ((SraAmt + 1) != EltBits)
13743           return SDValue();
13744
13745         DebugLoc DL = N->getDebugLoc();
13746
13747         // Now we know we at least have a plendvb with the mask val.  See if
13748         // we can form a psignb/w/d.
13749         // psign = x.type == y.type == mask.type && y = sub(0, x);
13750         X = X.getOperand(0);
13751         Y = Y.getOperand(0);
13752         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13753             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13754             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13755           unsigned Opc = 0;
13756           switch (EltBits) {
13757           case 8: Opc = X86ISD::PSIGNB; break;
13758           case 16: Opc = X86ISD::PSIGNW; break;
13759           case 32: Opc = X86ISD::PSIGND; break;
13760           default: break;
13761           }
13762           if (Opc) {
13763             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13764             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13765           }
13766         }
13767         // PBLENDVB only available on SSE 4.1
13768         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13769           return SDValue();
13770
13771         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13772         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13773         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13774         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13775         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13776       }
13777     }
13778   }
13779
13780   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13781   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13782     std::swap(N0, N1);
13783   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13784     return SDValue();
13785   if (!N0.hasOneUse() || !N1.hasOneUse())
13786     return SDValue();
13787
13788   SDValue ShAmt0 = N0.getOperand(1);
13789   if (ShAmt0.getValueType() != MVT::i8)
13790     return SDValue();
13791   SDValue ShAmt1 = N1.getOperand(1);
13792   if (ShAmt1.getValueType() != MVT::i8)
13793     return SDValue();
13794   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13795     ShAmt0 = ShAmt0.getOperand(0);
13796   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13797     ShAmt1 = ShAmt1.getOperand(0);
13798
13799   DebugLoc DL = N->getDebugLoc();
13800   unsigned Opc = X86ISD::SHLD;
13801   SDValue Op0 = N0.getOperand(0);
13802   SDValue Op1 = N1.getOperand(0);
13803   if (ShAmt0.getOpcode() == ISD::SUB) {
13804     Opc = X86ISD::SHRD;
13805     std::swap(Op0, Op1);
13806     std::swap(ShAmt0, ShAmt1);
13807   }
13808
13809   unsigned Bits = VT.getSizeInBits();
13810   if (ShAmt1.getOpcode() == ISD::SUB) {
13811     SDValue Sum = ShAmt1.getOperand(0);
13812     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13813       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13814       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13815         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13816       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13817         return DAG.getNode(Opc, DL, VT,
13818                            Op0, Op1,
13819                            DAG.getNode(ISD::TRUNCATE, DL,
13820                                        MVT::i8, ShAmt0));
13821     }
13822   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13823     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13824     if (ShAmt0C &&
13825         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13826       return DAG.getNode(Opc, DL, VT,
13827                          N0.getOperand(0), N1.getOperand(0),
13828                          DAG.getNode(ISD::TRUNCATE, DL,
13829                                        MVT::i8, ShAmt0));
13830   }
13831
13832   return SDValue();
13833 }
13834
13835 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13836                                  TargetLowering::DAGCombinerInfo &DCI,
13837                                  const X86Subtarget *Subtarget) {
13838   if (DCI.isBeforeLegalizeOps())
13839     return SDValue();
13840
13841   EVT VT = N->getValueType(0);
13842
13843   if (VT != MVT::i32 && VT != MVT::i64)
13844     return SDValue();
13845
13846   // Create BLSMSK instructions by finding X ^ (X-1)
13847   SDValue N0 = N->getOperand(0);
13848   SDValue N1 = N->getOperand(1);
13849   DebugLoc DL = N->getDebugLoc();
13850
13851   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13852       isAllOnes(N0.getOperand(1)))
13853     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13854
13855   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13856       isAllOnes(N1.getOperand(1)))
13857     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13858
13859   return SDValue();
13860 }
13861
13862 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13863 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13864                                    const X86Subtarget *Subtarget) {
13865   LoadSDNode *Ld = cast<LoadSDNode>(N);
13866   EVT RegVT = Ld->getValueType(0);
13867   EVT MemVT = Ld->getMemoryVT();
13868   DebugLoc dl = Ld->getDebugLoc();
13869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13870
13871   ISD::LoadExtType Ext = Ld->getExtensionType();
13872
13873   // If this is a vector EXT Load then attempt to optimize it using a
13874   // shuffle. We need SSE4 for the shuffles.
13875   // TODO: It is possible to support ZExt by zeroing the undef values
13876   // during the shuffle phase or after the shuffle.
13877   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13878     assert(MemVT != RegVT && "Cannot extend to the same type");
13879     assert(MemVT.isVector() && "Must load a vector from memory");
13880
13881     unsigned NumElems = RegVT.getVectorNumElements();
13882     unsigned RegSz = RegVT.getSizeInBits();
13883     unsigned MemSz = MemVT.getSizeInBits();
13884     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13885     // All sizes must be a power of two
13886     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13887
13888     // Attempt to load the original value using a single load op.
13889     // Find a scalar type which is equal to the loaded word size.
13890     MVT SclrLoadTy = MVT::i8;
13891     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13892          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13893       MVT Tp = (MVT::SimpleValueType)tp;
13894       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13895         SclrLoadTy = Tp;
13896         break;
13897       }
13898     }
13899
13900     // Proceed if a load word is found.
13901     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13902
13903     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13904       RegSz/SclrLoadTy.getSizeInBits());
13905
13906     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13907                                   RegSz/MemVT.getScalarType().getSizeInBits());
13908     // Can't shuffle using an illegal type.
13909     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13910
13911     // Perform a single load.
13912     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13913                                   Ld->getBasePtr(),
13914                                   Ld->getPointerInfo(), Ld->isVolatile(),
13915                                   Ld->isNonTemporal(), Ld->isInvariant(),
13916                                   Ld->getAlignment());
13917
13918     // Insert the word loaded into a vector.
13919     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13920       LoadUnitVecVT, ScalarLoad);
13921
13922     // Bitcast the loaded value to a vector of the original element type, in
13923     // the size of the target vector type.
13924     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13925     unsigned SizeRatio = RegSz/MemSz;
13926
13927     // Redistribute the loaded elements into the different locations.
13928     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13929     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13930
13931     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13932                                 DAG.getUNDEF(SlicedVec.getValueType()),
13933                                 ShuffleVec.data());
13934
13935     // Bitcast to the requested type.
13936     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13937     // Replace the original load with the new sequence
13938     // and return the new chain.
13939     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13940     return SDValue(ScalarLoad.getNode(), 1);
13941   }
13942
13943   return SDValue();
13944 }
13945
13946 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13947 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13948                                    const X86Subtarget *Subtarget) {
13949   StoreSDNode *St = cast<StoreSDNode>(N);
13950   EVT VT = St->getValue().getValueType();
13951   EVT StVT = St->getMemoryVT();
13952   DebugLoc dl = St->getDebugLoc();
13953   SDValue StoredVal = St->getOperand(1);
13954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13955
13956   // If we are saving a concatination of two XMM registers, perform two stores.
13957   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13958   // 128-bit ones. If in the future the cost becomes only one memory access the
13959   // first version would be better.
13960   if (VT.getSizeInBits() == 256 &&
13961     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13962     StoredVal.getNumOperands() == 2) {
13963
13964     SDValue Value0 = StoredVal.getOperand(0);
13965     SDValue Value1 = StoredVal.getOperand(1);
13966
13967     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13968     SDValue Ptr0 = St->getBasePtr();
13969     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13970
13971     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13972                                 St->getPointerInfo(), St->isVolatile(),
13973                                 St->isNonTemporal(), St->getAlignment());
13974     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13975                                 St->getPointerInfo(), St->isVolatile(),
13976                                 St->isNonTemporal(), St->getAlignment());
13977     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13978   }
13979
13980   // Optimize trunc store (of multiple scalars) to shuffle and store.
13981   // First, pack all of the elements in one place. Next, store to memory
13982   // in fewer chunks.
13983   if (St->isTruncatingStore() && VT.isVector()) {
13984     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13985     unsigned NumElems = VT.getVectorNumElements();
13986     assert(StVT != VT && "Cannot truncate to the same type");
13987     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13988     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13989
13990     // From, To sizes and ElemCount must be pow of two
13991     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13992     // We are going to use the original vector elt for storing.
13993     // Accumulated smaller vector elements must be a multiple of the store size.
13994     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13995
13996     unsigned SizeRatio  = FromSz / ToSz;
13997
13998     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13999
14000     // Create a type on which we perform the shuffle
14001     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14002             StVT.getScalarType(), NumElems*SizeRatio);
14003
14004     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14005
14006     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14007     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14008     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14009
14010     // Can't shuffle using an illegal type
14011     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14012
14013     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14014                                 DAG.getUNDEF(WideVec.getValueType()),
14015                                 ShuffleVec.data());
14016     // At this point all of the data is stored at the bottom of the
14017     // register. We now need to save it to mem.
14018
14019     // Find the largest store unit
14020     MVT StoreType = MVT::i8;
14021     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14022          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14023       MVT Tp = (MVT::SimpleValueType)tp;
14024       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14025         StoreType = Tp;
14026     }
14027
14028     // Bitcast the original vector into a vector of store-size units
14029     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14030             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14031     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14032     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14033     SmallVector<SDValue, 8> Chains;
14034     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14035                                         TLI.getPointerTy());
14036     SDValue Ptr = St->getBasePtr();
14037
14038     // Perform one or more big stores into memory.
14039     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14040       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14041                                    StoreType, ShuffWide,
14042                                    DAG.getIntPtrConstant(i));
14043       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14044                                 St->getPointerInfo(), St->isVolatile(),
14045                                 St->isNonTemporal(), St->getAlignment());
14046       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14047       Chains.push_back(Ch);
14048     }
14049
14050     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14051                                Chains.size());
14052   }
14053
14054
14055   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14056   // the FP state in cases where an emms may be missing.
14057   // A preferable solution to the general problem is to figure out the right
14058   // places to insert EMMS.  This qualifies as a quick hack.
14059
14060   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14061   if (VT.getSizeInBits() != 64)
14062     return SDValue();
14063
14064   const Function *F = DAG.getMachineFunction().getFunction();
14065   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14066   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14067                      && Subtarget->hasXMMInt();
14068   if ((VT.isVector() ||
14069        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14070       isa<LoadSDNode>(St->getValue()) &&
14071       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14072       St->getChain().hasOneUse() && !St->isVolatile()) {
14073     SDNode* LdVal = St->getValue().getNode();
14074     LoadSDNode *Ld = 0;
14075     int TokenFactorIndex = -1;
14076     SmallVector<SDValue, 8> Ops;
14077     SDNode* ChainVal = St->getChain().getNode();
14078     // Must be a store of a load.  We currently handle two cases:  the load
14079     // is a direct child, and it's under an intervening TokenFactor.  It is
14080     // possible to dig deeper under nested TokenFactors.
14081     if (ChainVal == LdVal)
14082       Ld = cast<LoadSDNode>(St->getChain());
14083     else if (St->getValue().hasOneUse() &&
14084              ChainVal->getOpcode() == ISD::TokenFactor) {
14085       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14086         if (ChainVal->getOperand(i).getNode() == LdVal) {
14087           TokenFactorIndex = i;
14088           Ld = cast<LoadSDNode>(St->getValue());
14089         } else
14090           Ops.push_back(ChainVal->getOperand(i));
14091       }
14092     }
14093
14094     if (!Ld || !ISD::isNormalLoad(Ld))
14095       return SDValue();
14096
14097     // If this is not the MMX case, i.e. we are just turning i64 load/store
14098     // into f64 load/store, avoid the transformation if there are multiple
14099     // uses of the loaded value.
14100     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14101       return SDValue();
14102
14103     DebugLoc LdDL = Ld->getDebugLoc();
14104     DebugLoc StDL = N->getDebugLoc();
14105     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14106     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14107     // pair instead.
14108     if (Subtarget->is64Bit() || F64IsLegal) {
14109       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14110       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14111                                   Ld->getPointerInfo(), Ld->isVolatile(),
14112                                   Ld->isNonTemporal(), Ld->isInvariant(),
14113                                   Ld->getAlignment());
14114       SDValue NewChain = NewLd.getValue(1);
14115       if (TokenFactorIndex != -1) {
14116         Ops.push_back(NewChain);
14117         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14118                                Ops.size());
14119       }
14120       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14121                           St->getPointerInfo(),
14122                           St->isVolatile(), St->isNonTemporal(),
14123                           St->getAlignment());
14124     }
14125
14126     // Otherwise, lower to two pairs of 32-bit loads / stores.
14127     SDValue LoAddr = Ld->getBasePtr();
14128     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14129                                  DAG.getConstant(4, MVT::i32));
14130
14131     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14132                                Ld->getPointerInfo(),
14133                                Ld->isVolatile(), Ld->isNonTemporal(),
14134                                Ld->isInvariant(), Ld->getAlignment());
14135     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14136                                Ld->getPointerInfo().getWithOffset(4),
14137                                Ld->isVolatile(), Ld->isNonTemporal(),
14138                                Ld->isInvariant(),
14139                                MinAlign(Ld->getAlignment(), 4));
14140
14141     SDValue NewChain = LoLd.getValue(1);
14142     if (TokenFactorIndex != -1) {
14143       Ops.push_back(LoLd);
14144       Ops.push_back(HiLd);
14145       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14146                              Ops.size());
14147     }
14148
14149     LoAddr = St->getBasePtr();
14150     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14151                          DAG.getConstant(4, MVT::i32));
14152
14153     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14154                                 St->getPointerInfo(),
14155                                 St->isVolatile(), St->isNonTemporal(),
14156                                 St->getAlignment());
14157     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14158                                 St->getPointerInfo().getWithOffset(4),
14159                                 St->isVolatile(),
14160                                 St->isNonTemporal(),
14161                                 MinAlign(St->getAlignment(), 4));
14162     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14163   }
14164   return SDValue();
14165 }
14166
14167 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14168 /// and return the operands for the horizontal operation in LHS and RHS.  A
14169 /// horizontal operation performs the binary operation on successive elements
14170 /// of its first operand, then on successive elements of its second operand,
14171 /// returning the resulting values in a vector.  For example, if
14172 ///   A = < float a0, float a1, float a2, float a3 >
14173 /// and
14174 ///   B = < float b0, float b1, float b2, float b3 >
14175 /// then the result of doing a horizontal operation on A and B is
14176 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14177 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14178 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14179 /// set to A, RHS to B, and the routine returns 'true'.
14180 /// Note that the binary operation should have the property that if one of the
14181 /// operands is UNDEF then the result is UNDEF.
14182 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14183   // Look for the following pattern: if
14184   //   A = < float a0, float a1, float a2, float a3 >
14185   //   B = < float b0, float b1, float b2, float b3 >
14186   // and
14187   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14188   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14189   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14190   // which is A horizontal-op B.
14191
14192   // At least one of the operands should be a vector shuffle.
14193   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14194       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14195     return false;
14196
14197   EVT VT = LHS.getValueType();
14198   unsigned N = VT.getVectorNumElements();
14199
14200   // View LHS in the form
14201   //   LHS = VECTOR_SHUFFLE A, B, LMask
14202   // If LHS is not a shuffle then pretend it is the shuffle
14203   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14204   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14205   // type VT.
14206   SDValue A, B;
14207   SmallVector<int, 8> LMask(N);
14208   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14209     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14210       A = LHS.getOperand(0);
14211     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14212       B = LHS.getOperand(1);
14213     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14214   } else {
14215     if (LHS.getOpcode() != ISD::UNDEF)
14216       A = LHS;
14217     for (unsigned i = 0; i != N; ++i)
14218       LMask[i] = i;
14219   }
14220
14221   // Likewise, view RHS in the form
14222   //   RHS = VECTOR_SHUFFLE C, D, RMask
14223   SDValue C, D;
14224   SmallVector<int, 8> RMask(N);
14225   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14226     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14227       C = RHS.getOperand(0);
14228     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14229       D = RHS.getOperand(1);
14230     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14231   } else {
14232     if (RHS.getOpcode() != ISD::UNDEF)
14233       C = RHS;
14234     for (unsigned i = 0; i != N; ++i)
14235       RMask[i] = i;
14236   }
14237
14238   // Check that the shuffles are both shuffling the same vectors.
14239   if (!(A == C && B == D) && !(A == D && B == C))
14240     return false;
14241
14242   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14243   if (!A.getNode() && !B.getNode())
14244     return false;
14245
14246   // If A and B occur in reverse order in RHS, then "swap" them (which means
14247   // rewriting the mask).
14248   if (A != C)
14249     for (unsigned i = 0; i != N; ++i) {
14250       unsigned Idx = RMask[i];
14251       if (Idx < N)
14252         RMask[i] += N;
14253       else if (Idx < 2*N)
14254         RMask[i] -= N;
14255     }
14256
14257   // At this point LHS and RHS are equivalent to
14258   //   LHS = VECTOR_SHUFFLE A, B, LMask
14259   //   RHS = VECTOR_SHUFFLE A, B, RMask
14260   // Check that the masks correspond to performing a horizontal operation.
14261   for (unsigned i = 0; i != N; ++i) {
14262     unsigned LIdx = LMask[i], RIdx = RMask[i];
14263
14264     // Ignore any UNDEF components.
14265     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14266         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14267       continue;
14268
14269     // Check that successive elements are being operated on.  If not, this is
14270     // not a horizontal operation.
14271     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14272         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14273       return false;
14274   }
14275
14276   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14277   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14278   return true;
14279 }
14280
14281 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14282 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14283                                   const X86Subtarget *Subtarget) {
14284   EVT VT = N->getValueType(0);
14285   SDValue LHS = N->getOperand(0);
14286   SDValue RHS = N->getOperand(1);
14287
14288   // Try to synthesize horizontal adds from adds of shuffles.
14289   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14290       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14291       isHorizontalBinOp(LHS, RHS, true))
14292     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14293   return SDValue();
14294 }
14295
14296 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14297 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14298                                   const X86Subtarget *Subtarget) {
14299   EVT VT = N->getValueType(0);
14300   SDValue LHS = N->getOperand(0);
14301   SDValue RHS = N->getOperand(1);
14302
14303   // Try to synthesize horizontal subs from subs of shuffles.
14304   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14305       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14306       isHorizontalBinOp(LHS, RHS, false))
14307     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14308   return SDValue();
14309 }
14310
14311 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14312 /// X86ISD::FXOR nodes.
14313 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14314   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14315   // F[X]OR(0.0, x) -> x
14316   // F[X]OR(x, 0.0) -> x
14317   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14318     if (C->getValueAPF().isPosZero())
14319       return N->getOperand(1);
14320   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14321     if (C->getValueAPF().isPosZero())
14322       return N->getOperand(0);
14323   return SDValue();
14324 }
14325
14326 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14327 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14328   // FAND(0.0, x) -> 0.0
14329   // FAND(x, 0.0) -> 0.0
14330   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14331     if (C->getValueAPF().isPosZero())
14332       return N->getOperand(0);
14333   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14334     if (C->getValueAPF().isPosZero())
14335       return N->getOperand(1);
14336   return SDValue();
14337 }
14338
14339 static SDValue PerformBTCombine(SDNode *N,
14340                                 SelectionDAG &DAG,
14341                                 TargetLowering::DAGCombinerInfo &DCI) {
14342   // BT ignores high bits in the bit index operand.
14343   SDValue Op1 = N->getOperand(1);
14344   if (Op1.hasOneUse()) {
14345     unsigned BitWidth = Op1.getValueSizeInBits();
14346     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14347     APInt KnownZero, KnownOne;
14348     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14349                                           !DCI.isBeforeLegalizeOps());
14350     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14351     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14352         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14353       DCI.CommitTargetLoweringOpt(TLO);
14354   }
14355   return SDValue();
14356 }
14357
14358 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14359   SDValue Op = N->getOperand(0);
14360   if (Op.getOpcode() == ISD::BITCAST)
14361     Op = Op.getOperand(0);
14362   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14363   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14364       VT.getVectorElementType().getSizeInBits() ==
14365       OpVT.getVectorElementType().getSizeInBits()) {
14366     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14367   }
14368   return SDValue();
14369 }
14370
14371 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14372   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14373   //           (and (i32 x86isd::setcc_carry), 1)
14374   // This eliminates the zext. This transformation is necessary because
14375   // ISD::SETCC is always legalized to i8.
14376   DebugLoc dl = N->getDebugLoc();
14377   SDValue N0 = N->getOperand(0);
14378   EVT VT = N->getValueType(0);
14379   if (N0.getOpcode() == ISD::AND &&
14380       N0.hasOneUse() &&
14381       N0.getOperand(0).hasOneUse()) {
14382     SDValue N00 = N0.getOperand(0);
14383     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14384       return SDValue();
14385     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14386     if (!C || C->getZExtValue() != 1)
14387       return SDValue();
14388     return DAG.getNode(ISD::AND, dl, VT,
14389                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14390                                    N00.getOperand(0), N00.getOperand(1)),
14391                        DAG.getConstant(1, VT));
14392   }
14393
14394   return SDValue();
14395 }
14396
14397 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14398 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14399   unsigned X86CC = N->getConstantOperandVal(0);
14400   SDValue EFLAG = N->getOperand(1);
14401   DebugLoc DL = N->getDebugLoc();
14402
14403   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14404   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14405   // cases.
14406   if (X86CC == X86::COND_B)
14407     return DAG.getNode(ISD::AND, DL, MVT::i8,
14408                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14409                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14410                        DAG.getConstant(1, MVT::i8));
14411
14412   return SDValue();
14413 }
14414
14415 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14416                                         const X86TargetLowering *XTLI) {
14417   SDValue Op0 = N->getOperand(0);
14418   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14419   // a 32-bit target where SSE doesn't support i64->FP operations.
14420   if (Op0.getOpcode() == ISD::LOAD) {
14421     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14422     EVT VT = Ld->getValueType(0);
14423     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14424         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14425         !XTLI->getSubtarget()->is64Bit() &&
14426         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14427       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14428                                           Ld->getChain(), Op0, DAG);
14429       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14430       return FILDChain;
14431     }
14432   }
14433   return SDValue();
14434 }
14435
14436 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14437 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14438                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14439   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14440   // the result is either zero or one (depending on the input carry bit).
14441   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14442   if (X86::isZeroNode(N->getOperand(0)) &&
14443       X86::isZeroNode(N->getOperand(1)) &&
14444       // We don't have a good way to replace an EFLAGS use, so only do this when
14445       // dead right now.
14446       SDValue(N, 1).use_empty()) {
14447     DebugLoc DL = N->getDebugLoc();
14448     EVT VT = N->getValueType(0);
14449     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14450     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14451                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14452                                            DAG.getConstant(X86::COND_B,MVT::i8),
14453                                            N->getOperand(2)),
14454                                DAG.getConstant(1, VT));
14455     return DCI.CombineTo(N, Res1, CarryOut);
14456   }
14457
14458   return SDValue();
14459 }
14460
14461 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14462 //      (add Y, (setne X, 0)) -> sbb -1, Y
14463 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14464 //      (sub (setne X, 0), Y) -> adc -1, Y
14465 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14466   DebugLoc DL = N->getDebugLoc();
14467
14468   // Look through ZExts.
14469   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14470   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14471     return SDValue();
14472
14473   SDValue SetCC = Ext.getOperand(0);
14474   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14475     return SDValue();
14476
14477   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14478   if (CC != X86::COND_E && CC != X86::COND_NE)
14479     return SDValue();
14480
14481   SDValue Cmp = SetCC.getOperand(1);
14482   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14483       !X86::isZeroNode(Cmp.getOperand(1)) ||
14484       !Cmp.getOperand(0).getValueType().isInteger())
14485     return SDValue();
14486
14487   SDValue CmpOp0 = Cmp.getOperand(0);
14488   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14489                                DAG.getConstant(1, CmpOp0.getValueType()));
14490
14491   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14492   if (CC == X86::COND_NE)
14493     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14494                        DL, OtherVal.getValueType(), OtherVal,
14495                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14496   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14497                      DL, OtherVal.getValueType(), OtherVal,
14498                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14499 }
14500
14501 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14502   SDValue Op0 = N->getOperand(0);
14503   SDValue Op1 = N->getOperand(1);
14504
14505   // X86 can't encode an immediate LHS of a sub. See if we can push the
14506   // negation into a preceding instruction.
14507   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14508     // If the RHS of the sub is a XOR with one use and a constant, invert the
14509     // immediate. Then add one to the LHS of the sub so we can turn
14510     // X-Y -> X+~Y+1, saving one register.
14511     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14512         isa<ConstantSDNode>(Op1.getOperand(1))) {
14513       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14514       EVT VT = Op0.getValueType();
14515       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14516                                    Op1.getOperand(0),
14517                                    DAG.getConstant(~XorC, VT));
14518       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14519                          DAG.getConstant(C->getAPIntValue()+1, VT));
14520     }
14521   }
14522
14523   return OptimizeConditionalInDecrement(N, DAG);
14524 }
14525
14526 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14527                                              DAGCombinerInfo &DCI) const {
14528   SelectionDAG &DAG = DCI.DAG;
14529   switch (N->getOpcode()) {
14530   default: break;
14531   case ISD::EXTRACT_VECTOR_ELT:
14532     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14533   case ISD::VSELECT:
14534   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14535   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14536   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14537   case ISD::SUB:            return PerformSubCombine(N, DAG);
14538   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14539   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14540   case ISD::SHL:
14541   case ISD::SRA:
14542   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14543   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14544   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14545   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14546   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14547   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14548   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14549   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14550   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14551   case X86ISD::FXOR:
14552   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14553   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14554   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14555   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14556   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14557   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14558   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14559   case X86ISD::SHUFPD:
14560   case X86ISD::PALIGN:
14561   case X86ISD::PUNPCKHBW:
14562   case X86ISD::PUNPCKHWD:
14563   case X86ISD::PUNPCKHDQ:
14564   case X86ISD::PUNPCKHQDQ:
14565   case X86ISD::UNPCKHPS:
14566   case X86ISD::UNPCKHPD:
14567   case X86ISD::VUNPCKHPSY:
14568   case X86ISD::VUNPCKHPDY:
14569   case X86ISD::PUNPCKLBW:
14570   case X86ISD::PUNPCKLWD:
14571   case X86ISD::PUNPCKLDQ:
14572   case X86ISD::PUNPCKLQDQ:
14573   case X86ISD::UNPCKLPS:
14574   case X86ISD::UNPCKLPD:
14575   case X86ISD::VUNPCKLPSY:
14576   case X86ISD::VUNPCKLPDY:
14577   case X86ISD::MOVHLPS:
14578   case X86ISD::MOVLHPS:
14579   case X86ISD::PSHUFD:
14580   case X86ISD::PSHUFHW:
14581   case X86ISD::PSHUFLW:
14582   case X86ISD::MOVSS:
14583   case X86ISD::MOVSD:
14584   case X86ISD::VPERMILPS:
14585   case X86ISD::VPERMILPSY:
14586   case X86ISD::VPERMILPD:
14587   case X86ISD::VPERMILPDY:
14588   case X86ISD::VPERM2F128:
14589   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14590   }
14591
14592   return SDValue();
14593 }
14594
14595 /// isTypeDesirableForOp - Return true if the target has native support for
14596 /// the specified value type and it is 'desirable' to use the type for the
14597 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14598 /// instruction encodings are longer and some i16 instructions are slow.
14599 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14600   if (!isTypeLegal(VT))
14601     return false;
14602   if (VT != MVT::i16)
14603     return true;
14604
14605   switch (Opc) {
14606   default:
14607     return true;
14608   case ISD::LOAD:
14609   case ISD::SIGN_EXTEND:
14610   case ISD::ZERO_EXTEND:
14611   case ISD::ANY_EXTEND:
14612   case ISD::SHL:
14613   case ISD::SRL:
14614   case ISD::SUB:
14615   case ISD::ADD:
14616   case ISD::MUL:
14617   case ISD::AND:
14618   case ISD::OR:
14619   case ISD::XOR:
14620     return false;
14621   }
14622 }
14623
14624 /// IsDesirableToPromoteOp - This method query the target whether it is
14625 /// beneficial for dag combiner to promote the specified node. If true, it
14626 /// should return the desired promotion type by reference.
14627 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14628   EVT VT = Op.getValueType();
14629   if (VT != MVT::i16)
14630     return false;
14631
14632   bool Promote = false;
14633   bool Commute = false;
14634   switch (Op.getOpcode()) {
14635   default: break;
14636   case ISD::LOAD: {
14637     LoadSDNode *LD = cast<LoadSDNode>(Op);
14638     // If the non-extending load has a single use and it's not live out, then it
14639     // might be folded.
14640     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14641                                                      Op.hasOneUse()*/) {
14642       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14643              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14644         // The only case where we'd want to promote LOAD (rather then it being
14645         // promoted as an operand is when it's only use is liveout.
14646         if (UI->getOpcode() != ISD::CopyToReg)
14647           return false;
14648       }
14649     }
14650     Promote = true;
14651     break;
14652   }
14653   case ISD::SIGN_EXTEND:
14654   case ISD::ZERO_EXTEND:
14655   case ISD::ANY_EXTEND:
14656     Promote = true;
14657     break;
14658   case ISD::SHL:
14659   case ISD::SRL: {
14660     SDValue N0 = Op.getOperand(0);
14661     // Look out for (store (shl (load), x)).
14662     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14663       return false;
14664     Promote = true;
14665     break;
14666   }
14667   case ISD::ADD:
14668   case ISD::MUL:
14669   case ISD::AND:
14670   case ISD::OR:
14671   case ISD::XOR:
14672     Commute = true;
14673     // fallthrough
14674   case ISD::SUB: {
14675     SDValue N0 = Op.getOperand(0);
14676     SDValue N1 = Op.getOperand(1);
14677     if (!Commute && MayFoldLoad(N1))
14678       return false;
14679     // Avoid disabling potential load folding opportunities.
14680     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14681       return false;
14682     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14683       return false;
14684     Promote = true;
14685   }
14686   }
14687
14688   PVT = MVT::i32;
14689   return Promote;
14690 }
14691
14692 //===----------------------------------------------------------------------===//
14693 //                           X86 Inline Assembly Support
14694 //===----------------------------------------------------------------------===//
14695
14696 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14697   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14698
14699   std::string AsmStr = IA->getAsmString();
14700
14701   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14702   SmallVector<StringRef, 4> AsmPieces;
14703   SplitString(AsmStr, AsmPieces, ";\n");
14704
14705   switch (AsmPieces.size()) {
14706   default: return false;
14707   case 1:
14708     AsmStr = AsmPieces[0];
14709     AsmPieces.clear();
14710     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14711
14712     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14713     // we will turn this bswap into something that will be lowered to logical ops
14714     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14715     // so don't worry about this.
14716     // bswap $0
14717     if (AsmPieces.size() == 2 &&
14718         (AsmPieces[0] == "bswap" ||
14719          AsmPieces[0] == "bswapq" ||
14720          AsmPieces[0] == "bswapl") &&
14721         (AsmPieces[1] == "$0" ||
14722          AsmPieces[1] == "${0:q}")) {
14723       // No need to check constraints, nothing other than the equivalent of
14724       // "=r,0" would be valid here.
14725       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14726       if (!Ty || Ty->getBitWidth() % 16 != 0)
14727         return false;
14728       return IntrinsicLowering::LowerToByteSwap(CI);
14729     }
14730     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14731     if (CI->getType()->isIntegerTy(16) &&
14732         AsmPieces.size() == 3 &&
14733         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14734         AsmPieces[1] == "$$8," &&
14735         AsmPieces[2] == "${0:w}" &&
14736         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14737       AsmPieces.clear();
14738       const std::string &ConstraintsStr = IA->getConstraintString();
14739       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14740       std::sort(AsmPieces.begin(), AsmPieces.end());
14741       if (AsmPieces.size() == 4 &&
14742           AsmPieces[0] == "~{cc}" &&
14743           AsmPieces[1] == "~{dirflag}" &&
14744           AsmPieces[2] == "~{flags}" &&
14745           AsmPieces[3] == "~{fpsr}") {
14746         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14747         if (!Ty || Ty->getBitWidth() % 16 != 0)
14748           return false;
14749         return IntrinsicLowering::LowerToByteSwap(CI);
14750       }
14751     }
14752     break;
14753   case 3:
14754     if (CI->getType()->isIntegerTy(32) &&
14755         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14756       SmallVector<StringRef, 4> Words;
14757       SplitString(AsmPieces[0], Words, " \t,");
14758       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14759           Words[2] == "${0:w}") {
14760         Words.clear();
14761         SplitString(AsmPieces[1], Words, " \t,");
14762         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14763             Words[2] == "$0") {
14764           Words.clear();
14765           SplitString(AsmPieces[2], Words, " \t,");
14766           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14767               Words[2] == "${0:w}") {
14768             AsmPieces.clear();
14769             const std::string &ConstraintsStr = IA->getConstraintString();
14770             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14771             std::sort(AsmPieces.begin(), AsmPieces.end());
14772             if (AsmPieces.size() == 4 &&
14773                 AsmPieces[0] == "~{cc}" &&
14774                 AsmPieces[1] == "~{dirflag}" &&
14775                 AsmPieces[2] == "~{flags}" &&
14776                 AsmPieces[3] == "~{fpsr}") {
14777               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14778               if (!Ty || Ty->getBitWidth() % 16 != 0)
14779                 return false;
14780               return IntrinsicLowering::LowerToByteSwap(CI);
14781             }
14782           }
14783         }
14784       }
14785     }
14786
14787     if (CI->getType()->isIntegerTy(64)) {
14788       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14789       if (Constraints.size() >= 2 &&
14790           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14791           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14792         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14793         SmallVector<StringRef, 4> Words;
14794         SplitString(AsmPieces[0], Words, " \t");
14795         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14796           Words.clear();
14797           SplitString(AsmPieces[1], Words, " \t");
14798           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14799             Words.clear();
14800             SplitString(AsmPieces[2], Words, " \t,");
14801             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14802                 Words[2] == "%edx") {
14803               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14804               if (!Ty || Ty->getBitWidth() % 16 != 0)
14805                 return false;
14806               return IntrinsicLowering::LowerToByteSwap(CI);
14807             }
14808           }
14809         }
14810       }
14811     }
14812     break;
14813   }
14814   return false;
14815 }
14816
14817
14818
14819 /// getConstraintType - Given a constraint letter, return the type of
14820 /// constraint it is for this target.
14821 X86TargetLowering::ConstraintType
14822 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14823   if (Constraint.size() == 1) {
14824     switch (Constraint[0]) {
14825     case 'R':
14826     case 'q':
14827     case 'Q':
14828     case 'f':
14829     case 't':
14830     case 'u':
14831     case 'y':
14832     case 'x':
14833     case 'Y':
14834     case 'l':
14835       return C_RegisterClass;
14836     case 'a':
14837     case 'b':
14838     case 'c':
14839     case 'd':
14840     case 'S':
14841     case 'D':
14842     case 'A':
14843       return C_Register;
14844     case 'I':
14845     case 'J':
14846     case 'K':
14847     case 'L':
14848     case 'M':
14849     case 'N':
14850     case 'G':
14851     case 'C':
14852     case 'e':
14853     case 'Z':
14854       return C_Other;
14855     default:
14856       break;
14857     }
14858   }
14859   return TargetLowering::getConstraintType(Constraint);
14860 }
14861
14862 /// Examine constraint type and operand type and determine a weight value.
14863 /// This object must already have been set up with the operand type
14864 /// and the current alternative constraint selected.
14865 TargetLowering::ConstraintWeight
14866   X86TargetLowering::getSingleConstraintMatchWeight(
14867     AsmOperandInfo &info, const char *constraint) const {
14868   ConstraintWeight weight = CW_Invalid;
14869   Value *CallOperandVal = info.CallOperandVal;
14870     // If we don't have a value, we can't do a match,
14871     // but allow it at the lowest weight.
14872   if (CallOperandVal == NULL)
14873     return CW_Default;
14874   Type *type = CallOperandVal->getType();
14875   // Look at the constraint type.
14876   switch (*constraint) {
14877   default:
14878     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14879   case 'R':
14880   case 'q':
14881   case 'Q':
14882   case 'a':
14883   case 'b':
14884   case 'c':
14885   case 'd':
14886   case 'S':
14887   case 'D':
14888   case 'A':
14889     if (CallOperandVal->getType()->isIntegerTy())
14890       weight = CW_SpecificReg;
14891     break;
14892   case 'f':
14893   case 't':
14894   case 'u':
14895       if (type->isFloatingPointTy())
14896         weight = CW_SpecificReg;
14897       break;
14898   case 'y':
14899       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14900         weight = CW_SpecificReg;
14901       break;
14902   case 'x':
14903   case 'Y':
14904     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14905       weight = CW_Register;
14906     break;
14907   case 'I':
14908     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14909       if (C->getZExtValue() <= 31)
14910         weight = CW_Constant;
14911     }
14912     break;
14913   case 'J':
14914     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14915       if (C->getZExtValue() <= 63)
14916         weight = CW_Constant;
14917     }
14918     break;
14919   case 'K':
14920     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14921       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14922         weight = CW_Constant;
14923     }
14924     break;
14925   case 'L':
14926     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14927       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14928         weight = CW_Constant;
14929     }
14930     break;
14931   case 'M':
14932     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14933       if (C->getZExtValue() <= 3)
14934         weight = CW_Constant;
14935     }
14936     break;
14937   case 'N':
14938     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14939       if (C->getZExtValue() <= 0xff)
14940         weight = CW_Constant;
14941     }
14942     break;
14943   case 'G':
14944   case 'C':
14945     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14946       weight = CW_Constant;
14947     }
14948     break;
14949   case 'e':
14950     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14951       if ((C->getSExtValue() >= -0x80000000LL) &&
14952           (C->getSExtValue() <= 0x7fffffffLL))
14953         weight = CW_Constant;
14954     }
14955     break;
14956   case 'Z':
14957     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14958       if (C->getZExtValue() <= 0xffffffff)
14959         weight = CW_Constant;
14960     }
14961     break;
14962   }
14963   return weight;
14964 }
14965
14966 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14967 /// with another that has more specific requirements based on the type of the
14968 /// corresponding operand.
14969 const char *X86TargetLowering::
14970 LowerXConstraint(EVT ConstraintVT) const {
14971   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14972   // 'f' like normal targets.
14973   if (ConstraintVT.isFloatingPoint()) {
14974     if (Subtarget->hasXMMInt())
14975       return "Y";
14976     if (Subtarget->hasXMM())
14977       return "x";
14978   }
14979
14980   return TargetLowering::LowerXConstraint(ConstraintVT);
14981 }
14982
14983 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14984 /// vector.  If it is invalid, don't add anything to Ops.
14985 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14986                                                      std::string &Constraint,
14987                                                      std::vector<SDValue>&Ops,
14988                                                      SelectionDAG &DAG) const {
14989   SDValue Result(0, 0);
14990
14991   // Only support length 1 constraints for now.
14992   if (Constraint.length() > 1) return;
14993
14994   char ConstraintLetter = Constraint[0];
14995   switch (ConstraintLetter) {
14996   default: break;
14997   case 'I':
14998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14999       if (C->getZExtValue() <= 31) {
15000         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15001         break;
15002       }
15003     }
15004     return;
15005   case 'J':
15006     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15007       if (C->getZExtValue() <= 63) {
15008         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15009         break;
15010       }
15011     }
15012     return;
15013   case 'K':
15014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15015       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15016         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15017         break;
15018       }
15019     }
15020     return;
15021   case 'N':
15022     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15023       if (C->getZExtValue() <= 255) {
15024         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15025         break;
15026       }
15027     }
15028     return;
15029   case 'e': {
15030     // 32-bit signed value
15031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15032       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15033                                            C->getSExtValue())) {
15034         // Widen to 64 bits here to get it sign extended.
15035         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15036         break;
15037       }
15038     // FIXME gcc accepts some relocatable values here too, but only in certain
15039     // memory models; it's complicated.
15040     }
15041     return;
15042   }
15043   case 'Z': {
15044     // 32-bit unsigned value
15045     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15046       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15047                                            C->getZExtValue())) {
15048         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15049         break;
15050       }
15051     }
15052     // FIXME gcc accepts some relocatable values here too, but only in certain
15053     // memory models; it's complicated.
15054     return;
15055   }
15056   case 'i': {
15057     // Literal immediates are always ok.
15058     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15059       // Widen to 64 bits here to get it sign extended.
15060       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15061       break;
15062     }
15063
15064     // In any sort of PIC mode addresses need to be computed at runtime by
15065     // adding in a register or some sort of table lookup.  These can't
15066     // be used as immediates.
15067     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15068       return;
15069
15070     // If we are in non-pic codegen mode, we allow the address of a global (with
15071     // an optional displacement) to be used with 'i'.
15072     GlobalAddressSDNode *GA = 0;
15073     int64_t Offset = 0;
15074
15075     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15076     while (1) {
15077       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15078         Offset += GA->getOffset();
15079         break;
15080       } else if (Op.getOpcode() == ISD::ADD) {
15081         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15082           Offset += C->getZExtValue();
15083           Op = Op.getOperand(0);
15084           continue;
15085         }
15086       } else if (Op.getOpcode() == ISD::SUB) {
15087         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15088           Offset += -C->getZExtValue();
15089           Op = Op.getOperand(0);
15090           continue;
15091         }
15092       }
15093
15094       // Otherwise, this isn't something we can handle, reject it.
15095       return;
15096     }
15097
15098     const GlobalValue *GV = GA->getGlobal();
15099     // If we require an extra load to get this address, as in PIC mode, we
15100     // can't accept it.
15101     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15102                                                         getTargetMachine())))
15103       return;
15104
15105     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15106                                         GA->getValueType(0), Offset);
15107     break;
15108   }
15109   }
15110
15111   if (Result.getNode()) {
15112     Ops.push_back(Result);
15113     return;
15114   }
15115   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15116 }
15117
15118 std::pair<unsigned, const TargetRegisterClass*>
15119 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15120                                                 EVT VT) const {
15121   // First, see if this is a constraint that directly corresponds to an LLVM
15122   // register class.
15123   if (Constraint.size() == 1) {
15124     // GCC Constraint Letters
15125     switch (Constraint[0]) {
15126     default: break;
15127       // TODO: Slight differences here in allocation order and leaving
15128       // RIP in the class. Do they matter any more here than they do
15129       // in the normal allocation?
15130     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15131       if (Subtarget->is64Bit()) {
15132         if (VT == MVT::i32 || VT == MVT::f32)
15133           return std::make_pair(0U, X86::GR32RegisterClass);
15134         else if (VT == MVT::i16)
15135           return std::make_pair(0U, X86::GR16RegisterClass);
15136         else if (VT == MVT::i8 || VT == MVT::i1)
15137           return std::make_pair(0U, X86::GR8RegisterClass);
15138         else if (VT == MVT::i64 || VT == MVT::f64)
15139           return std::make_pair(0U, X86::GR64RegisterClass);
15140         break;
15141       }
15142       // 32-bit fallthrough
15143     case 'Q':   // Q_REGS
15144       if (VT == MVT::i32 || VT == MVT::f32)
15145         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15146       else if (VT == MVT::i16)
15147         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15148       else if (VT == MVT::i8 || VT == MVT::i1)
15149         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15150       else if (VT == MVT::i64)
15151         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15152       break;
15153     case 'r':   // GENERAL_REGS
15154     case 'l':   // INDEX_REGS
15155       if (VT == MVT::i8 || VT == MVT::i1)
15156         return std::make_pair(0U, X86::GR8RegisterClass);
15157       if (VT == MVT::i16)
15158         return std::make_pair(0U, X86::GR16RegisterClass);
15159       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15160         return std::make_pair(0U, X86::GR32RegisterClass);
15161       return std::make_pair(0U, X86::GR64RegisterClass);
15162     case 'R':   // LEGACY_REGS
15163       if (VT == MVT::i8 || VT == MVT::i1)
15164         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15165       if (VT == MVT::i16)
15166         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15167       if (VT == MVT::i32 || !Subtarget->is64Bit())
15168         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15169       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15170     case 'f':  // FP Stack registers.
15171       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15172       // value to the correct fpstack register class.
15173       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15174         return std::make_pair(0U, X86::RFP32RegisterClass);
15175       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15176         return std::make_pair(0U, X86::RFP64RegisterClass);
15177       return std::make_pair(0U, X86::RFP80RegisterClass);
15178     case 'y':   // MMX_REGS if MMX allowed.
15179       if (!Subtarget->hasMMX()) break;
15180       return std::make_pair(0U, X86::VR64RegisterClass);
15181     case 'Y':   // SSE_REGS if SSE2 allowed
15182       if (!Subtarget->hasXMMInt()) break;
15183       // FALL THROUGH.
15184     case 'x':   // SSE_REGS if SSE1 allowed
15185       if (!Subtarget->hasXMM()) break;
15186
15187       switch (VT.getSimpleVT().SimpleTy) {
15188       default: break;
15189       // Scalar SSE types.
15190       case MVT::f32:
15191       case MVT::i32:
15192         return std::make_pair(0U, X86::FR32RegisterClass);
15193       case MVT::f64:
15194       case MVT::i64:
15195         return std::make_pair(0U, X86::FR64RegisterClass);
15196       // Vector types.
15197       case MVT::v16i8:
15198       case MVT::v8i16:
15199       case MVT::v4i32:
15200       case MVT::v2i64:
15201       case MVT::v4f32:
15202       case MVT::v2f64:
15203         return std::make_pair(0U, X86::VR128RegisterClass);
15204       }
15205       break;
15206     }
15207   }
15208
15209   // Use the default implementation in TargetLowering to convert the register
15210   // constraint into a member of a register class.
15211   std::pair<unsigned, const TargetRegisterClass*> Res;
15212   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15213
15214   // Not found as a standard register?
15215   if (Res.second == 0) {
15216     // Map st(0) -> st(7) -> ST0
15217     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15218         tolower(Constraint[1]) == 's' &&
15219         tolower(Constraint[2]) == 't' &&
15220         Constraint[3] == '(' &&
15221         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15222         Constraint[5] == ')' &&
15223         Constraint[6] == '}') {
15224
15225       Res.first = X86::ST0+Constraint[4]-'0';
15226       Res.second = X86::RFP80RegisterClass;
15227       return Res;
15228     }
15229
15230     // GCC allows "st(0)" to be called just plain "st".
15231     if (StringRef("{st}").equals_lower(Constraint)) {
15232       Res.first = X86::ST0;
15233       Res.second = X86::RFP80RegisterClass;
15234       return Res;
15235     }
15236
15237     // flags -> EFLAGS
15238     if (StringRef("{flags}").equals_lower(Constraint)) {
15239       Res.first = X86::EFLAGS;
15240       Res.second = X86::CCRRegisterClass;
15241       return Res;
15242     }
15243
15244     // 'A' means EAX + EDX.
15245     if (Constraint == "A") {
15246       Res.first = X86::EAX;
15247       Res.second = X86::GR32_ADRegisterClass;
15248       return Res;
15249     }
15250     return Res;
15251   }
15252
15253   // Otherwise, check to see if this is a register class of the wrong value
15254   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15255   // turn into {ax},{dx}.
15256   if (Res.second->hasType(VT))
15257     return Res;   // Correct type already, nothing to do.
15258
15259   // All of the single-register GCC register classes map their values onto
15260   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15261   // really want an 8-bit or 32-bit register, map to the appropriate register
15262   // class and return the appropriate register.
15263   if (Res.second == X86::GR16RegisterClass) {
15264     if (VT == MVT::i8) {
15265       unsigned DestReg = 0;
15266       switch (Res.first) {
15267       default: break;
15268       case X86::AX: DestReg = X86::AL; break;
15269       case X86::DX: DestReg = X86::DL; break;
15270       case X86::CX: DestReg = X86::CL; break;
15271       case X86::BX: DestReg = X86::BL; break;
15272       }
15273       if (DestReg) {
15274         Res.first = DestReg;
15275         Res.second = X86::GR8RegisterClass;
15276       }
15277     } else if (VT == MVT::i32) {
15278       unsigned DestReg = 0;
15279       switch (Res.first) {
15280       default: break;
15281       case X86::AX: DestReg = X86::EAX; break;
15282       case X86::DX: DestReg = X86::EDX; break;
15283       case X86::CX: DestReg = X86::ECX; break;
15284       case X86::BX: DestReg = X86::EBX; break;
15285       case X86::SI: DestReg = X86::ESI; break;
15286       case X86::DI: DestReg = X86::EDI; break;
15287       case X86::BP: DestReg = X86::EBP; break;
15288       case X86::SP: DestReg = X86::ESP; break;
15289       }
15290       if (DestReg) {
15291         Res.first = DestReg;
15292         Res.second = X86::GR32RegisterClass;
15293       }
15294     } else if (VT == MVT::i64) {
15295       unsigned DestReg = 0;
15296       switch (Res.first) {
15297       default: break;
15298       case X86::AX: DestReg = X86::RAX; break;
15299       case X86::DX: DestReg = X86::RDX; break;
15300       case X86::CX: DestReg = X86::RCX; break;
15301       case X86::BX: DestReg = X86::RBX; break;
15302       case X86::SI: DestReg = X86::RSI; break;
15303       case X86::DI: DestReg = X86::RDI; break;
15304       case X86::BP: DestReg = X86::RBP; break;
15305       case X86::SP: DestReg = X86::RSP; break;
15306       }
15307       if (DestReg) {
15308         Res.first = DestReg;
15309         Res.second = X86::GR64RegisterClass;
15310       }
15311     }
15312   } else if (Res.second == X86::FR32RegisterClass ||
15313              Res.second == X86::FR64RegisterClass ||
15314              Res.second == X86::VR128RegisterClass) {
15315     // Handle references to XMM physical registers that got mapped into the
15316     // wrong class.  This can happen with constraints like {xmm0} where the
15317     // target independent register mapper will just pick the first match it can
15318     // find, ignoring the required type.
15319     if (VT == MVT::f32)
15320       Res.second = X86::FR32RegisterClass;
15321     else if (VT == MVT::f64)
15322       Res.second = X86::FR64RegisterClass;
15323     else if (X86::VR128RegisterClass->hasType(VT))
15324       Res.second = X86::VR128RegisterClass;
15325   }
15326
15327   return Res;
15328 }