fix a bug I introduced in r148929, this is not a splat!
[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/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VariadicFunction.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 static cl::opt<bool> UseRegMask("x86-use-regmask",
61                                 cl::desc("Use register masks for x86 calls"));
62
63 // Forward declarations.
64 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65                        SDValue V2);
66
67 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
68 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
69 /// simple subregister reference.  Idx is an index in the 128 bits we
70 /// want.  It need not be aligned to a 128-bit bounday.  That makes
71 /// lowering EXTRACT_VECTOR_ELT operations easier.
72 static SDValue Extract128BitVector(SDValue Vec,
73                                    SDValue Idx,
74                                    SelectionDAG &DAG,
75                                    DebugLoc dl) {
76   EVT VT = Vec.getValueType();
77   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
78   EVT ElVT = VT.getVectorElementType();
79   int Factor = VT.getSizeInBits()/128;
80   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
81                                   VT.getVectorNumElements()/Factor);
82
83   // Extract from UNDEF is UNDEF.
84   if (Vec.getOpcode() == ISD::UNDEF)
85     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
86
87   if (isa<ConstantSDNode>(Idx)) {
88     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
89
90     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
91     // we can match to VEXTRACTF128.
92     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
93
94     // This is the index of the first element of the 128-bit chunk
95     // we want.
96     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
97                                  * ElemsPerChunk);
98
99     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
100     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
101                                  VecIdx);
102
103     return Result;
104   }
105
106   return SDValue();
107 }
108
109 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
110 /// sets things up to match to an AVX VINSERTF128 instruction or a
111 /// simple superregister reference.  Idx is an index in the 128 bits
112 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
113 /// lowering INSERT_VECTOR_ELT operations easier.
114 static SDValue Insert128BitVector(SDValue Result,
115                                   SDValue Vec,
116                                   SDValue Idx,
117                                   SelectionDAG &DAG,
118                                   DebugLoc dl) {
119   if (isa<ConstantSDNode>(Idx)) {
120     EVT VT = Vec.getValueType();
121     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
122
123     EVT ElVT = VT.getVectorElementType();
124     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
125     EVT ResultVT = Result.getValueType();
126
127     // Insert the relevant 128 bits.
128     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
129
130     // This is the index of the first element of the 128-bit chunk
131     // we want.
132     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
133                                  * ElemsPerChunk);
134
135     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
136     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
137                          VecIdx);
138     return Result;
139   }
140
141   return SDValue();
142 }
143
144 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
145   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
146   bool is64Bit = Subtarget->is64Bit();
147
148   if (Subtarget->isTargetEnvMacho()) {
149     if (is64Bit)
150       return new X8664_MachoTargetObjectFile();
151     return new TargetLoweringObjectFileMachO();
152   }
153
154   if (Subtarget->isTargetELF())
155     return new TargetLoweringObjectFileELF();
156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157     return new TargetLoweringObjectFileCOFF();
158   llvm_unreachable("unknown subtarget type");
159 }
160
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162   : TargetLowering(TM, createTLOF(TM)) {
163   Subtarget = &TM.getSubtarget<X86Subtarget>();
164   X86ScalarSSEf64 = Subtarget->hasSSE2();
165   X86ScalarSSEf32 = Subtarget->hasSSE1();
166   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
167
168   RegInfo = TM.getRegisterInfo();
169   TD = getTargetData();
170
171   // Set up the TargetLowering object.
172   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
173
174   // X86 is weird, it always uses i8 for shift amounts and setcc results.
175   setBooleanContents(ZeroOrOneBooleanContent);
176   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
177   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
178
179   // For 64-bit since we have so many registers use the ILP scheduler, for
180   // 32-bit code use the register pressure specific scheduling.
181   if (Subtarget->is64Bit())
182     setSchedulingPreference(Sched::ILP);
183   else
184     setSchedulingPreference(Sched::RegPressure);
185   setStackPointerRegisterToSaveRestore(X86StackPtr);
186
187   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
188     // Setup Windows compiler runtime calls.
189     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
190     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
191     setLibcallName(RTLIB::SREM_I64, "_allrem");
192     setLibcallName(RTLIB::UREM_I64, "_aullrem");
193     setLibcallName(RTLIB::MUL_I64, "_allmul");
194     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
195     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
196     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
202     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
203   }
204
205   if (Subtarget->isTargetDarwin()) {
206     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
207     setUseUnderscoreSetJmp(false);
208     setUseUnderscoreLongJmp(false);
209   } else if (Subtarget->isTargetMingw()) {
210     // MS runtime is weird: it exports _setjmp, but longjmp!
211     setUseUnderscoreSetJmp(true);
212     setUseUnderscoreLongJmp(false);
213   } else {
214     setUseUnderscoreSetJmp(true);
215     setUseUnderscoreLongJmp(true);
216   }
217
218   // Set up the register classes.
219   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
220   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
221   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
222   if (Subtarget->is64Bit())
223     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
224
225   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
226
227   // We don't accept any truncstore of integer registers.
228   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
229   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
231   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
232   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
233   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
234
235   // SETOEQ and SETUNE require checking two conditions.
236   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
237   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
239   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
242
243   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
244   // operation.
245   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
248
249   if (Subtarget->is64Bit()) {
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
252   } else if (!TM.Options.UseSoftFloat) {
253     // We have an algorithm for SSE2->double, and we turn this into a
254     // 64-bit FILD followed by conditional FADD for other targets.
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
256     // We have an algorithm for SSE2, and we turn this into a 64-bit
257     // FILD for other targets.
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
259   }
260
261   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
262   // this operation.
263   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
265
266   if (!TM.Options.UseSoftFloat) {
267     // SSE has no i16 to fp conversion, only i32
268     if (X86ScalarSSEf32) {
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
270       // f32 and f64 cases are Legal, f80 case is not
271       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
272     } else {
273       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
275     }
276   } else {
277     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
279   }
280
281   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
282   // are Legal, f80 is custom lowered.
283   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
284   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
285
286   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
287   // this operation.
288   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
290
291   if (X86ScalarSSEf32) {
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
293     // f32 and f64 cases are Legal, f80 case is not
294     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
295   } else {
296     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
298   }
299
300   // Handle FP_TO_UINT by promoting the destination to a larger signed
301   // conversion.
302   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
305
306   if (Subtarget->is64Bit()) {
307     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
309   } else if (!TM.Options.UseSoftFloat) {
310     // Since AVX is a superset of SSE3, only check for SSE here.
311     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
312       // Expand FP_TO_UINT into a select.
313       // FIXME: We would like to use a Custom expander here eventually to do
314       // the optimal thing for SSE vs. the default expansion in the legalizer.
315       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
316     else
317       // With SSE3 we can use fisttpll to convert to a signed i64; without
318       // SSE, we're stuck with a fistpll.
319       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
320   }
321
322   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
323   if (!X86ScalarSSEf64) {
324     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
325     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
326     if (Subtarget->is64Bit()) {
327       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
328       // Without SSE, i64->f64 goes through memory.
329       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
330     }
331   }
332
333   // Scalar integer divide and remainder are lowered to use operations that
334   // produce two results, to match the available instructions. This exposes
335   // the two-result form to trivial CSE, which is able to combine x/y and x%y
336   // into a single instruction.
337   //
338   // Scalar integer multiply-high is also lowered to use two-result
339   // operations, to match the available instructions. However, plain multiply
340   // (low) operations are left as Legal, as there are single-result
341   // instructions for this in x86. Using the two-result multiply instructions
342   // when both high and low results are needed must be arranged by dagcombine.
343   for (unsigned i = 0, e = 4; i != e; ++i) {
344     MVT VT = IntVTs[i];
345     setOperationAction(ISD::MULHS, VT, Expand);
346     setOperationAction(ISD::MULHU, VT, Expand);
347     setOperationAction(ISD::SDIV, VT, Expand);
348     setOperationAction(ISD::UDIV, VT, Expand);
349     setOperationAction(ISD::SREM, VT, Expand);
350     setOperationAction(ISD::UREM, VT, Expand);
351
352     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
353     setOperationAction(ISD::ADDC, VT, Custom);
354     setOperationAction(ISD::ADDE, VT, Custom);
355     setOperationAction(ISD::SUBC, VT, Custom);
356     setOperationAction(ISD::SUBE, VT, Custom);
357   }
358
359   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
360   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
361   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
362   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
363   if (Subtarget->is64Bit())
364     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
365   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
366   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
367   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
368   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
369   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
370   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
371   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
372   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
373
374   // Promote the i8 variants and force them on up to i32 which has a shorter
375   // encoding.
376   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
377   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
378   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
379   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
380   if (Subtarget->hasBMI()) {
381     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
383     if (Subtarget->is64Bit())
384       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
385   } else {
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     // When promoting the i8 variants, force them to i32 for a shorter
394     // encoding.
395     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
396     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
397     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
398     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
399     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
400     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
401     if (Subtarget->is64Bit())
402       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
403   } else {
404     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
405     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
406     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
410     if (Subtarget->is64Bit()) {
411       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
412       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
413     }
414   }
415
416   if (Subtarget->hasPOPCNT()) {
417     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
418   } else {
419     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
420     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
421     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
422     if (Subtarget->is64Bit())
423       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
424   }
425
426   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
427   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
428
429   // These should be promoted to a larger select which is supported.
430   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
431   // X86 wants to expand cmov itself.
432   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
433   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
434   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
435   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
438   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
439   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
440   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
444   if (Subtarget->is64Bit()) {
445     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
446     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
447   }
448   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
449
450   // Darwin ABI issue.
451   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
452   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
453   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
454   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
455   if (Subtarget->is64Bit())
456     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
457   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
458   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
459   if (Subtarget->is64Bit()) {
460     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
461     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
462     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
463     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
464     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
465   }
466   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
467   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
468   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
469   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
470   if (Subtarget->is64Bit()) {
471     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
472     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
473     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
474   }
475
476   if (Subtarget->hasSSE1())
477     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
478
479   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
480   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
481
482   // On X86 and X86-64, atomic operations are lowered to locked instructions.
483   // Locked instructions, in turn, have implicit fence semantics (all memory
484   // operations are flushed before issuing the locked instruction, and they
485   // are not buffered), so we can fold away the common pattern of
486   // fence-atomic-fence.
487   setShouldFoldAtomicFences(true);
488
489   // Expand certain atomics
490   for (unsigned i = 0, e = 4; i != e; ++i) {
491     MVT VT = IntVTs[i];
492     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
493     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
494     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
495   }
496
497   if (!Subtarget->is64Bit()) {
498     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
499     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
506   }
507
508   if (Subtarget->hasCmpxchg16b()) {
509     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
510   }
511
512   // FIXME - use subtarget debug flags
513   if (!Subtarget->isTargetDarwin() &&
514       !Subtarget->isTargetELF() &&
515       !Subtarget->isTargetCygMing()) {
516     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
517   }
518
519   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
520   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
521   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
522   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
523   if (Subtarget->is64Bit()) {
524     setExceptionPointerRegister(X86::RAX);
525     setExceptionSelectorRegister(X86::RDX);
526   } else {
527     setExceptionPointerRegister(X86::EAX);
528     setExceptionSelectorRegister(X86::EDX);
529   }
530   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
531   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
532
533   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
534   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
535
536   setOperationAction(ISD::TRAP, MVT::Other, Legal);
537
538   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
539   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
540   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
541   if (Subtarget->is64Bit()) {
542     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
543     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
544   } else {
545     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
546     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
547   }
548
549   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
550   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
551
552   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
553     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
554                        MVT::i64 : MVT::i32, Custom);
555   else if (TM.Options.EnableSegmentedStacks)
556     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
557                        MVT::i64 : MVT::i32, Custom);
558   else
559     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
560                        MVT::i64 : MVT::i32, Expand);
561
562   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
563     // f32 and f64 use SSE.
564     // Set up the FP register classes.
565     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
566     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
567
568     // Use ANDPD to simulate FABS.
569     setOperationAction(ISD::FABS , MVT::f64, Custom);
570     setOperationAction(ISD::FABS , MVT::f32, Custom);
571
572     // Use XORP to simulate FNEG.
573     setOperationAction(ISD::FNEG , MVT::f64, Custom);
574     setOperationAction(ISD::FNEG , MVT::f32, Custom);
575
576     // Use ANDPD and ORPD to simulate FCOPYSIGN.
577     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
578     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
579
580     // Lower this to FGETSIGNx86 plus an AND.
581     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
582     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
583
584     // We don't support sin/cos/fmod
585     setOperationAction(ISD::FSIN , MVT::f64, Expand);
586     setOperationAction(ISD::FCOS , MVT::f64, Expand);
587     setOperationAction(ISD::FSIN , MVT::f32, Expand);
588     setOperationAction(ISD::FCOS , MVT::f32, Expand);
589
590     // Expand FP immediates into loads from the stack, except for the special
591     // cases we handle.
592     addLegalFPImmediate(APFloat(+0.0)); // xorpd
593     addLegalFPImmediate(APFloat(+0.0f)); // xorps
594   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
595     // Use SSE for f32, x87 for f64.
596     // Set up the FP register classes.
597     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
598     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
599
600     // Use ANDPS to simulate FABS.
601     setOperationAction(ISD::FABS , MVT::f32, Custom);
602
603     // Use XORP to simulate FNEG.
604     setOperationAction(ISD::FNEG , MVT::f32, Custom);
605
606     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
607
608     // Use ANDPS and ORPS to simulate FCOPYSIGN.
609     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
610     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
611
612     // We don't support sin/cos/fmod
613     setOperationAction(ISD::FSIN , MVT::f32, Expand);
614     setOperationAction(ISD::FCOS , MVT::f32, Expand);
615
616     // Special cases we handle for FP constants.
617     addLegalFPImmediate(APFloat(+0.0f)); // xorps
618     addLegalFPImmediate(APFloat(+0.0)); // FLD0
619     addLegalFPImmediate(APFloat(+1.0)); // FLD1
620     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
621     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
622
623     if (!TM.Options.UnsafeFPMath) {
624       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
625       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
626     }
627   } else if (!TM.Options.UseSoftFloat) {
628     // f32 and f64 in x87.
629     // Set up the FP register classes.
630     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
631     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
632
633     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
634     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
635     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
636     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
640       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
641     }
642     addLegalFPImmediate(APFloat(+0.0)); // FLD0
643     addLegalFPImmediate(APFloat(+1.0)); // FLD1
644     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
647     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
648     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
649     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
650   }
651
652   // We don't support FMA.
653   setOperationAction(ISD::FMA, MVT::f64, Expand);
654   setOperationAction(ISD::FMA, MVT::f32, Expand);
655
656   // Long double always uses X87.
657   if (!TM.Options.UseSoftFloat) {
658     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
659     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
661     {
662       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
663       addLegalFPImmediate(TmpFlt);  // FLD0
664       TmpFlt.changeSign();
665       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
666
667       bool ignored;
668       APFloat TmpFlt2(+1.0);
669       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
670                       &ignored);
671       addLegalFPImmediate(TmpFlt2);  // FLD1
672       TmpFlt2.changeSign();
673       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
674     }
675
676     if (!TM.Options.UnsafeFPMath) {
677       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
678       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
679     }
680
681     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
682     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
683     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
684     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
685     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
686     setOperationAction(ISD::FMA, MVT::f80, Expand);
687   }
688
689   // Always use a library call for pow.
690   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
691   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
692   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
693
694   setOperationAction(ISD::FLOG, MVT::f80, Expand);
695   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
696   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
697   setOperationAction(ISD::FEXP, MVT::f80, Expand);
698   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
699
700   // First set operation action for all vector types to either promote
701   // (for widening) or expand (for scalarization). Then we will selectively
702   // turn on ones that can be effectively codegen'd.
703   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
704        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
705     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
720     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
722     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
757     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
762     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
763          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
764       setTruncStoreAction((MVT::SimpleValueType)VT,
765                           (MVT::SimpleValueType)InnerVT, Expand);
766     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
767     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
768     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
769   }
770
771   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
772   // with -msoft-float, disable use of MMX as well.
773   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
774     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
775     // No operations on x86mmx supported, everything uses intrinsics.
776   }
777
778   // MMX-sized vectors (other than x86mmx) are expected to be expanded
779   // into smaller operations.
780   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
781   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
782   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
783   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
784   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
785   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
786   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
787   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
788   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
789   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
790   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
791   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
792   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
793   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
794   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
795   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
796   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
797   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
798   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
799   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
800   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
801   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
802   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
803   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
804   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
805   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
806   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
807   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
808   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
809
810   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
811     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
812
813     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
814     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
815     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
816     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
817     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
818     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
819     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
820     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
821     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
822     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
823     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
824     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
825   }
826
827   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
828     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
829
830     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
831     // registers cannot be used even for integer operations.
832     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
833     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
834     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
835     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
836
837     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
838     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
839     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
840     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
841     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
842     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
843     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
844     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
845     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
846     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
847     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
848     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
849     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
850     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
851     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
852     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
853
854     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
855     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
857     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
858
859     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
860     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
861     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
863     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
864
865     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
866     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
867     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
868     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
869     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
870
871     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
872     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
873       EVT VT = (MVT::SimpleValueType)i;
874       // Do not attempt to custom lower non-power-of-2 vectors
875       if (!isPowerOf2_32(VT.getVectorNumElements()))
876         continue;
877       // Do not attempt to custom lower non-128-bit vectors
878       if (!VT.is128BitVector())
879         continue;
880       setOperationAction(ISD::BUILD_VECTOR,
881                          VT.getSimpleVT().SimpleTy, Custom);
882       setOperationAction(ISD::VECTOR_SHUFFLE,
883                          VT.getSimpleVT().SimpleTy, Custom);
884       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
885                          VT.getSimpleVT().SimpleTy, Custom);
886     }
887
888     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
890     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
892     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
893     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
894
895     if (Subtarget->is64Bit()) {
896       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
897       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
898     }
899
900     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
901     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
902       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
903       EVT VT = SVT;
904
905       // Do not attempt to promote non-128-bit vectors
906       if (!VT.is128BitVector())
907         continue;
908
909       setOperationAction(ISD::AND,    SVT, Promote);
910       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
911       setOperationAction(ISD::OR,     SVT, Promote);
912       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
913       setOperationAction(ISD::XOR,    SVT, Promote);
914       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
915       setOperationAction(ISD::LOAD,   SVT, Promote);
916       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
917       setOperationAction(ISD::SELECT, SVT, Promote);
918       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
919     }
920
921     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
922
923     // Custom lower v2i64 and v2f64 selects.
924     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
925     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
926     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
927     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
928
929     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
930     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
931   }
932
933   if (Subtarget->hasSSE41()) {
934     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
935     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
936     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
937     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
938     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
939     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
940     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
941     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
942     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
943     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
944
945     // FIXME: Do we need to handle scalar-to-vector here?
946     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
947
948     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
949     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
950     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
951     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
953
954     // i8 and i16 vectors are custom , because the source register and source
955     // source memory operand types are not the same width.  f32 vectors are
956     // custom since the immediate controlling the insert encodes additional
957     // information.
958     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
960     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
962
963     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
964     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
965     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
967
968     // FIXME: these should be Legal but thats only for the case where
969     // the index is constant.  For now custom expand to deal with that.
970     if (Subtarget->is64Bit()) {
971       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
972       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
973     }
974   }
975
976   if (Subtarget->hasSSE2()) {
977     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
978     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
979
980     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
981     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
982
983     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
984     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
985
986     if (Subtarget->hasAVX2()) {
987       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
988       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
989
990       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
991       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
992
993       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
994     } else {
995       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
996       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
997
998       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
999       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1000
1001       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1002     }
1003   }
1004
1005   if (Subtarget->hasSSE42())
1006     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1007
1008   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1009     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
1010     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
1011     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
1012     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
1013     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
1014     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
1015
1016     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1019
1020     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1021     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1025     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1026
1027     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1028     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1032     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1033
1034     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1035     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1036     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1037
1038     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1039     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1040     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1041     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1042     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1043     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1044
1045     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1046     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1047
1048     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1049     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1050
1051     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1052     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1053
1054     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1055     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1056     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1057     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1058
1059     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1060     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1061     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1062
1063     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1064     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1065     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1066     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1067
1068     if (Subtarget->hasAVX2()) {
1069       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1070       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1071       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1073
1074       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1075       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1076       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1078
1079       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1080       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1081       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1082       // Don't lower v32i8 because there is no 128-bit byte mul
1083
1084       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1085
1086       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1087       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1088
1089       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1090       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1091
1092       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1093     } else {
1094       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1095       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1096       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1098
1099       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1100       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1101       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1103
1104       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1105       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1106       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1107       // Don't lower v32i8 because there is no 128-bit byte mul
1108
1109       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1110       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1111
1112       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1113       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1114
1115       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1116     }
1117
1118     // Custom lower several nodes for 256-bit types.
1119     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1120                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1121       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1122       EVT VT = SVT;
1123
1124       // Extract subvector is special because the value type
1125       // (result) is 128-bit but the source is 256-bit wide.
1126       if (VT.is128BitVector())
1127         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1128
1129       // Do not attempt to custom lower other non-256-bit vectors
1130       if (!VT.is256BitVector())
1131         continue;
1132
1133       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1134       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1135       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1136       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1137       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1138       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1139     }
1140
1141     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1142     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1143       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1144       EVT VT = SVT;
1145
1146       // Do not attempt to promote non-256-bit vectors
1147       if (!VT.is256BitVector())
1148         continue;
1149
1150       setOperationAction(ISD::AND,    SVT, Promote);
1151       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1152       setOperationAction(ISD::OR,     SVT, Promote);
1153       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1154       setOperationAction(ISD::XOR,    SVT, Promote);
1155       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1156       setOperationAction(ISD::LOAD,   SVT, Promote);
1157       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1158       setOperationAction(ISD::SELECT, SVT, Promote);
1159       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1160     }
1161   }
1162
1163   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1164   // of this type with custom code.
1165   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1166          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1167     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1168                        Custom);
1169   }
1170
1171   // We want to custom lower some of our intrinsics.
1172   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1173
1174
1175   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1176   // handle type legalization for these operations here.
1177   //
1178   // FIXME: We really should do custom legalization for addition and
1179   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1180   // than generic legalization for 64-bit multiplication-with-overflow, though.
1181   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1182     // Add/Sub/Mul with overflow operations are custom lowered.
1183     MVT VT = IntVTs[i];
1184     setOperationAction(ISD::SADDO, VT, Custom);
1185     setOperationAction(ISD::UADDO, VT, Custom);
1186     setOperationAction(ISD::SSUBO, VT, Custom);
1187     setOperationAction(ISD::USUBO, VT, Custom);
1188     setOperationAction(ISD::SMULO, VT, Custom);
1189     setOperationAction(ISD::UMULO, VT, Custom);
1190   }
1191
1192   // There are no 8-bit 3-address imul/mul instructions
1193   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1194   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1195
1196   if (!Subtarget->is64Bit()) {
1197     // These libcalls are not available in 32-bit.
1198     setLibcallName(RTLIB::SHL_I128, 0);
1199     setLibcallName(RTLIB::SRL_I128, 0);
1200     setLibcallName(RTLIB::SRA_I128, 0);
1201   }
1202
1203   // We have target-specific dag combine patterns for the following nodes:
1204   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1205   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1206   setTargetDAGCombine(ISD::VSELECT);
1207   setTargetDAGCombine(ISD::SELECT);
1208   setTargetDAGCombine(ISD::SHL);
1209   setTargetDAGCombine(ISD::SRA);
1210   setTargetDAGCombine(ISD::SRL);
1211   setTargetDAGCombine(ISD::OR);
1212   setTargetDAGCombine(ISD::AND);
1213   setTargetDAGCombine(ISD::ADD);
1214   setTargetDAGCombine(ISD::FADD);
1215   setTargetDAGCombine(ISD::FSUB);
1216   setTargetDAGCombine(ISD::SUB);
1217   setTargetDAGCombine(ISD::LOAD);
1218   setTargetDAGCombine(ISD::STORE);
1219   setTargetDAGCombine(ISD::ZERO_EXTEND);
1220   setTargetDAGCombine(ISD::SINT_TO_FP);
1221   if (Subtarget->is64Bit())
1222     setTargetDAGCombine(ISD::MUL);
1223   if (Subtarget->hasBMI())
1224     setTargetDAGCombine(ISD::XOR);
1225
1226   computeRegisterProperties();
1227
1228   // On Darwin, -Os means optimize for size without hurting performance,
1229   // do not reduce the limit.
1230   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1231   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1232   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1233   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1234   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1235   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1236   setPrefLoopAlignment(4); // 2^4 bytes.
1237   benefitFromCodePlacementOpt = true;
1238
1239   setPrefFunctionAlignment(4); // 2^4 bytes.
1240 }
1241
1242
1243 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1244   if (!VT.isVector()) return MVT::i8;
1245   return VT.changeVectorElementTypeToInteger();
1246 }
1247
1248
1249 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1250 /// the desired ByVal argument alignment.
1251 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1252   if (MaxAlign == 16)
1253     return;
1254   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1255     if (VTy->getBitWidth() == 128)
1256       MaxAlign = 16;
1257   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1258     unsigned EltAlign = 0;
1259     getMaxByValAlign(ATy->getElementType(), EltAlign);
1260     if (EltAlign > MaxAlign)
1261       MaxAlign = EltAlign;
1262   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1263     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1264       unsigned EltAlign = 0;
1265       getMaxByValAlign(STy->getElementType(i), EltAlign);
1266       if (EltAlign > MaxAlign)
1267         MaxAlign = EltAlign;
1268       if (MaxAlign == 16)
1269         break;
1270     }
1271   }
1272   return;
1273 }
1274
1275 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1276 /// function arguments in the caller parameter area. For X86, aggregates
1277 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1278 /// are at 4-byte boundaries.
1279 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1280   if (Subtarget->is64Bit()) {
1281     // Max of 8 and alignment of type.
1282     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1283     if (TyAlign > 8)
1284       return TyAlign;
1285     return 8;
1286   }
1287
1288   unsigned Align = 4;
1289   if (Subtarget->hasSSE1())
1290     getMaxByValAlign(Ty, Align);
1291   return Align;
1292 }
1293
1294 /// getOptimalMemOpType - Returns the target specific optimal type for load
1295 /// and store operations as a result of memset, memcpy, and memmove
1296 /// lowering. If DstAlign is zero that means it's safe to destination
1297 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1298 /// means there isn't a need to check it against alignment requirement,
1299 /// probably because the source does not need to be loaded. If
1300 /// 'IsZeroVal' is true, that means it's safe to return a
1301 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1302 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1303 /// constant so it does not need to be loaded.
1304 /// It returns EVT::Other if the type should be determined using generic
1305 /// target-independent logic.
1306 EVT
1307 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1308                                        unsigned DstAlign, unsigned SrcAlign,
1309                                        bool IsZeroVal,
1310                                        bool MemcpyStrSrc,
1311                                        MachineFunction &MF) const {
1312   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1313   // linux.  This is because the stack realignment code can't handle certain
1314   // cases like PR2962.  This should be removed when PR2962 is fixed.
1315   const Function *F = MF.getFunction();
1316   if (IsZeroVal &&
1317       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1318     if (Size >= 16 &&
1319         (Subtarget->isUnalignedMemAccessFast() ||
1320          ((DstAlign == 0 || DstAlign >= 16) &&
1321           (SrcAlign == 0 || SrcAlign >= 16))) &&
1322         Subtarget->getStackAlignment() >= 16) {
1323       if (Subtarget->getStackAlignment() >= 32) {
1324         if (Subtarget->hasAVX2())
1325           return MVT::v8i32;
1326         if (Subtarget->hasAVX())
1327           return MVT::v8f32;
1328       }
1329       if (Subtarget->hasSSE2())
1330         return MVT::v4i32;
1331       if (Subtarget->hasSSE1())
1332         return MVT::v4f32;
1333     } else if (!MemcpyStrSrc && Size >= 8 &&
1334                !Subtarget->is64Bit() &&
1335                Subtarget->getStackAlignment() >= 8 &&
1336                Subtarget->hasSSE2()) {
1337       // Do not use f64 to lower memcpy if source is string constant. It's
1338       // better to use i32 to avoid the loads.
1339       return MVT::f64;
1340     }
1341   }
1342   if (Subtarget->is64Bit() && Size >= 8)
1343     return MVT::i64;
1344   return MVT::i32;
1345 }
1346
1347 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1348 /// current function.  The returned value is a member of the
1349 /// MachineJumpTableInfo::JTEntryKind enum.
1350 unsigned X86TargetLowering::getJumpTableEncoding() const {
1351   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1352   // symbol.
1353   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1354       Subtarget->isPICStyleGOT())
1355     return MachineJumpTableInfo::EK_Custom32;
1356
1357   // Otherwise, use the normal jump table encoding heuristics.
1358   return TargetLowering::getJumpTableEncoding();
1359 }
1360
1361 const MCExpr *
1362 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1363                                              const MachineBasicBlock *MBB,
1364                                              unsigned uid,MCContext &Ctx) const{
1365   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1366          Subtarget->isPICStyleGOT());
1367   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1368   // entries.
1369   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1370                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1371 }
1372
1373 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1374 /// jumptable.
1375 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1376                                                     SelectionDAG &DAG) const {
1377   if (!Subtarget->is64Bit())
1378     // This doesn't have DebugLoc associated with it, but is not really the
1379     // same as a Register.
1380     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1381   return Table;
1382 }
1383
1384 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1385 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1386 /// MCExpr.
1387 const MCExpr *X86TargetLowering::
1388 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1389                              MCContext &Ctx) const {
1390   // X86-64 uses RIP relative addressing based on the jump table label.
1391   if (Subtarget->isPICStyleRIPRel())
1392     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1393
1394   // Otherwise, the reference is relative to the PIC base.
1395   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1396 }
1397
1398 // FIXME: Why this routine is here? Move to RegInfo!
1399 std::pair<const TargetRegisterClass*, uint8_t>
1400 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1401   const TargetRegisterClass *RRC = 0;
1402   uint8_t Cost = 1;
1403   switch (VT.getSimpleVT().SimpleTy) {
1404   default:
1405     return TargetLowering::findRepresentativeClass(VT);
1406   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1407     RRC = (Subtarget->is64Bit()
1408            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1409     break;
1410   case MVT::x86mmx:
1411     RRC = X86::VR64RegisterClass;
1412     break;
1413   case MVT::f32: case MVT::f64:
1414   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1415   case MVT::v4f32: case MVT::v2f64:
1416   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1417   case MVT::v4f64:
1418     RRC = X86::VR128RegisterClass;
1419     break;
1420   }
1421   return std::make_pair(RRC, Cost);
1422 }
1423
1424 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1425                                                unsigned &Offset) const {
1426   if (!Subtarget->isTargetLinux())
1427     return false;
1428
1429   if (Subtarget->is64Bit()) {
1430     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1431     Offset = 0x28;
1432     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1433       AddressSpace = 256;
1434     else
1435       AddressSpace = 257;
1436   } else {
1437     // %gs:0x14 on i386
1438     Offset = 0x14;
1439     AddressSpace = 256;
1440   }
1441   return true;
1442 }
1443
1444
1445 //===----------------------------------------------------------------------===//
1446 //               Return Value Calling Convention Implementation
1447 //===----------------------------------------------------------------------===//
1448
1449 #include "X86GenCallingConv.inc"
1450
1451 bool
1452 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1453                                   MachineFunction &MF, bool isVarArg,
1454                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1455                         LLVMContext &Context) const {
1456   SmallVector<CCValAssign, 16> RVLocs;
1457   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1458                  RVLocs, Context);
1459   return CCInfo.CheckReturn(Outs, RetCC_X86);
1460 }
1461
1462 SDValue
1463 X86TargetLowering::LowerReturn(SDValue Chain,
1464                                CallingConv::ID CallConv, bool isVarArg,
1465                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1466                                const SmallVectorImpl<SDValue> &OutVals,
1467                                DebugLoc dl, SelectionDAG &DAG) const {
1468   MachineFunction &MF = DAG.getMachineFunction();
1469   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1470
1471   SmallVector<CCValAssign, 16> RVLocs;
1472   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1473                  RVLocs, *DAG.getContext());
1474   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1475
1476   // Add the regs to the liveout set for the function.
1477   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1478   for (unsigned i = 0; i != RVLocs.size(); ++i)
1479     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1480       MRI.addLiveOut(RVLocs[i].getLocReg());
1481
1482   SDValue Flag;
1483
1484   SmallVector<SDValue, 6> RetOps;
1485   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1486   // Operand #1 = Bytes To Pop
1487   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1488                    MVT::i16));
1489
1490   // Copy the result values into the output registers.
1491   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1492     CCValAssign &VA = RVLocs[i];
1493     assert(VA.isRegLoc() && "Can only return in registers!");
1494     SDValue ValToCopy = OutVals[i];
1495     EVT ValVT = ValToCopy.getValueType();
1496
1497     // If this is x86-64, and we disabled SSE, we can't return FP values,
1498     // or SSE or MMX vectors.
1499     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1500          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1501           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1502       report_fatal_error("SSE register return with SSE disabled");
1503     }
1504     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1505     // llvm-gcc has never done it right and no one has noticed, so this
1506     // should be OK for now.
1507     if (ValVT == MVT::f64 &&
1508         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1509       report_fatal_error("SSE2 register return with SSE2 disabled");
1510
1511     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1512     // the RET instruction and handled by the FP Stackifier.
1513     if (VA.getLocReg() == X86::ST0 ||
1514         VA.getLocReg() == X86::ST1) {
1515       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1516       // change the value to the FP stack register class.
1517       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1518         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1519       RetOps.push_back(ValToCopy);
1520       // Don't emit a copytoreg.
1521       continue;
1522     }
1523
1524     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1525     // which is returned in RAX / RDX.
1526     if (Subtarget->is64Bit()) {
1527       if (ValVT == MVT::x86mmx) {
1528         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1529           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1530           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1531                                   ValToCopy);
1532           // If we don't have SSE2 available, convert to v4f32 so the generated
1533           // register is legal.
1534           if (!Subtarget->hasSSE2())
1535             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1536         }
1537       }
1538     }
1539
1540     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1541     Flag = Chain.getValue(1);
1542   }
1543
1544   // The x86-64 ABI for returning structs by value requires that we copy
1545   // the sret argument into %rax for the return. We saved the argument into
1546   // a virtual register in the entry block, so now we copy the value out
1547   // and into %rax.
1548   if (Subtarget->is64Bit() &&
1549       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1550     MachineFunction &MF = DAG.getMachineFunction();
1551     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1552     unsigned Reg = FuncInfo->getSRetReturnReg();
1553     assert(Reg &&
1554            "SRetReturnReg should have been set in LowerFormalArguments().");
1555     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1556
1557     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1558     Flag = Chain.getValue(1);
1559
1560     // RAX now acts like a return value.
1561     MRI.addLiveOut(X86::RAX);
1562   }
1563
1564   RetOps[0] = Chain;  // Update chain.
1565
1566   // Add the flag if we have it.
1567   if (Flag.getNode())
1568     RetOps.push_back(Flag);
1569
1570   return DAG.getNode(X86ISD::RET_FLAG, dl,
1571                      MVT::Other, &RetOps[0], RetOps.size());
1572 }
1573
1574 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1575   if (N->getNumValues() != 1)
1576     return false;
1577   if (!N->hasNUsesOfValue(1, 0))
1578     return false;
1579
1580   SDNode *Copy = *N->use_begin();
1581   if (Copy->getOpcode() != ISD::CopyToReg &&
1582       Copy->getOpcode() != ISD::FP_EXTEND)
1583     return false;
1584
1585   bool HasRet = false;
1586   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1587        UI != UE; ++UI) {
1588     if (UI->getOpcode() != X86ISD::RET_FLAG)
1589       return false;
1590     HasRet = true;
1591   }
1592
1593   return HasRet;
1594 }
1595
1596 EVT
1597 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1598                                             ISD::NodeType ExtendKind) const {
1599   MVT ReturnMVT;
1600   // TODO: Is this also valid on 32-bit?
1601   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1602     ReturnMVT = MVT::i8;
1603   else
1604     ReturnMVT = MVT::i32;
1605
1606   EVT MinVT = getRegisterType(Context, ReturnMVT);
1607   return VT.bitsLT(MinVT) ? MinVT : VT;
1608 }
1609
1610 /// LowerCallResult - Lower the result values of a call into the
1611 /// appropriate copies out of appropriate physical registers.
1612 ///
1613 SDValue
1614 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1615                                    CallingConv::ID CallConv, bool isVarArg,
1616                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1617                                    DebugLoc dl, SelectionDAG &DAG,
1618                                    SmallVectorImpl<SDValue> &InVals) const {
1619
1620   // Assign locations to each value returned by this call.
1621   SmallVector<CCValAssign, 16> RVLocs;
1622   bool Is64Bit = Subtarget->is64Bit();
1623   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1624                  getTargetMachine(), RVLocs, *DAG.getContext());
1625   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1626
1627   // Copy all of the result registers out of their specified physreg.
1628   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1629     CCValAssign &VA = RVLocs[i];
1630     EVT CopyVT = VA.getValVT();
1631
1632     // If this is x86-64, and we disabled SSE, we can't return FP values
1633     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1634         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1635       report_fatal_error("SSE register return with SSE disabled");
1636     }
1637
1638     SDValue Val;
1639
1640     // If this is a call to a function that returns an fp value on the floating
1641     // point stack, we must guarantee the the value is popped from the stack, so
1642     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1643     // if the return value is not used. We use the FpPOP_RETVAL instruction
1644     // instead.
1645     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1646       // If we prefer to use the value in xmm registers, copy it out as f80 and
1647       // use a truncate to move it from fp stack reg to xmm reg.
1648       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1649       SDValue Ops[] = { Chain, InFlag };
1650       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1651                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1652       Val = Chain.getValue(0);
1653
1654       // Round the f80 to the right size, which also moves it to the appropriate
1655       // xmm register.
1656       if (CopyVT != VA.getValVT())
1657         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1658                           // This truncation won't change the value.
1659                           DAG.getIntPtrConstant(1));
1660     } else {
1661       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1662                                  CopyVT, InFlag).getValue(1);
1663       Val = Chain.getValue(0);
1664     }
1665     InFlag = Chain.getValue(2);
1666     InVals.push_back(Val);
1667   }
1668
1669   return Chain;
1670 }
1671
1672
1673 //===----------------------------------------------------------------------===//
1674 //                C & StdCall & Fast Calling Convention implementation
1675 //===----------------------------------------------------------------------===//
1676 //  StdCall calling convention seems to be standard for many Windows' API
1677 //  routines and around. It differs from C calling convention just a little:
1678 //  callee should clean up the stack, not caller. Symbols should be also
1679 //  decorated in some fancy way :) It doesn't support any vector arguments.
1680 //  For info on fast calling convention see Fast Calling Convention (tail call)
1681 //  implementation LowerX86_32FastCCCallTo.
1682
1683 /// CallIsStructReturn - Determines whether a call uses struct return
1684 /// semantics.
1685 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1686   if (Outs.empty())
1687     return false;
1688
1689   return Outs[0].Flags.isSRet();
1690 }
1691
1692 /// ArgsAreStructReturn - Determines whether a function uses struct
1693 /// return semantics.
1694 static bool
1695 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1696   if (Ins.empty())
1697     return false;
1698
1699   return Ins[0].Flags.isSRet();
1700 }
1701
1702 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1703 /// by "Src" to address "Dst" with size and alignment information specified by
1704 /// the specific parameter attribute. The copy will be passed as a byval
1705 /// function parameter.
1706 static SDValue
1707 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1708                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1709                           DebugLoc dl) {
1710   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1711
1712   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1713                        /*isVolatile*/false, /*AlwaysInline=*/true,
1714                        MachinePointerInfo(), MachinePointerInfo());
1715 }
1716
1717 /// IsTailCallConvention - Return true if the calling convention is one that
1718 /// supports tail call optimization.
1719 static bool IsTailCallConvention(CallingConv::ID CC) {
1720   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1721 }
1722
1723 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1724   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1725     return false;
1726
1727   CallSite CS(CI);
1728   CallingConv::ID CalleeCC = CS.getCallingConv();
1729   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1730     return false;
1731
1732   return true;
1733 }
1734
1735 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1736 /// a tailcall target by changing its ABI.
1737 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1738                                    bool GuaranteedTailCallOpt) {
1739   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1740 }
1741
1742 SDValue
1743 X86TargetLowering::LowerMemArgument(SDValue Chain,
1744                                     CallingConv::ID CallConv,
1745                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1746                                     DebugLoc dl, SelectionDAG &DAG,
1747                                     const CCValAssign &VA,
1748                                     MachineFrameInfo *MFI,
1749                                     unsigned i) const {
1750   // Create the nodes corresponding to a load from this parameter slot.
1751   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1752   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1753                               getTargetMachine().Options.GuaranteedTailCallOpt);
1754   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1755   EVT ValVT;
1756
1757   // If value is passed by pointer we have address passed instead of the value
1758   // itself.
1759   if (VA.getLocInfo() == CCValAssign::Indirect)
1760     ValVT = VA.getLocVT();
1761   else
1762     ValVT = VA.getValVT();
1763
1764   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1765   // changed with more analysis.
1766   // In case of tail call optimization mark all arguments mutable. Since they
1767   // could be overwritten by lowering of arguments in case of a tail call.
1768   if (Flags.isByVal()) {
1769     unsigned Bytes = Flags.getByValSize();
1770     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1771     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1772     return DAG.getFrameIndex(FI, getPointerTy());
1773   } else {
1774     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1775                                     VA.getLocMemOffset(), isImmutable);
1776     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1777     return DAG.getLoad(ValVT, dl, Chain, FIN,
1778                        MachinePointerInfo::getFixedStack(FI),
1779                        false, false, false, 0);
1780   }
1781 }
1782
1783 SDValue
1784 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1785                                         CallingConv::ID CallConv,
1786                                         bool isVarArg,
1787                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1788                                         DebugLoc dl,
1789                                         SelectionDAG &DAG,
1790                                         SmallVectorImpl<SDValue> &InVals)
1791                                           const {
1792   MachineFunction &MF = DAG.getMachineFunction();
1793   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1794
1795   const Function* Fn = MF.getFunction();
1796   if (Fn->hasExternalLinkage() &&
1797       Subtarget->isTargetCygMing() &&
1798       Fn->getName() == "main")
1799     FuncInfo->setForceFramePointer(true);
1800
1801   MachineFrameInfo *MFI = MF.getFrameInfo();
1802   bool Is64Bit = Subtarget->is64Bit();
1803   bool IsWindows = Subtarget->isTargetWindows();
1804   bool IsWin64 = Subtarget->isTargetWin64();
1805
1806   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1807          "Var args not supported with calling convention fastcc or ghc");
1808
1809   // Assign locations to all of the incoming arguments.
1810   SmallVector<CCValAssign, 16> ArgLocs;
1811   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1812                  ArgLocs, *DAG.getContext());
1813
1814   // Allocate shadow area for Win64
1815   if (IsWin64) {
1816     CCInfo.AllocateStack(32, 8);
1817   }
1818
1819   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1820
1821   unsigned LastVal = ~0U;
1822   SDValue ArgValue;
1823   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1824     CCValAssign &VA = ArgLocs[i];
1825     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1826     // places.
1827     assert(VA.getValNo() != LastVal &&
1828            "Don't support value assigned to multiple locs yet");
1829     (void)LastVal;
1830     LastVal = VA.getValNo();
1831
1832     if (VA.isRegLoc()) {
1833       EVT RegVT = VA.getLocVT();
1834       TargetRegisterClass *RC = NULL;
1835       if (RegVT == MVT::i32)
1836         RC = X86::GR32RegisterClass;
1837       else if (Is64Bit && RegVT == MVT::i64)
1838         RC = X86::GR64RegisterClass;
1839       else if (RegVT == MVT::f32)
1840         RC = X86::FR32RegisterClass;
1841       else if (RegVT == MVT::f64)
1842         RC = X86::FR64RegisterClass;
1843       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1844         RC = X86::VR256RegisterClass;
1845       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1846         RC = X86::VR128RegisterClass;
1847       else if (RegVT == MVT::x86mmx)
1848         RC = X86::VR64RegisterClass;
1849       else
1850         llvm_unreachable("Unknown argument type!");
1851
1852       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1853       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1854
1855       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1856       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1857       // right size.
1858       if (VA.getLocInfo() == CCValAssign::SExt)
1859         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1860                                DAG.getValueType(VA.getValVT()));
1861       else if (VA.getLocInfo() == CCValAssign::ZExt)
1862         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1863                                DAG.getValueType(VA.getValVT()));
1864       else if (VA.getLocInfo() == CCValAssign::BCvt)
1865         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1866
1867       if (VA.isExtInLoc()) {
1868         // Handle MMX values passed in XMM regs.
1869         if (RegVT.isVector()) {
1870           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1871                                  ArgValue);
1872         } else
1873           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1874       }
1875     } else {
1876       assert(VA.isMemLoc());
1877       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1878     }
1879
1880     // If value is passed via pointer - do a load.
1881     if (VA.getLocInfo() == CCValAssign::Indirect)
1882       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1883                              MachinePointerInfo(), false, false, false, 0);
1884
1885     InVals.push_back(ArgValue);
1886   }
1887
1888   // The x86-64 ABI for returning structs by value requires that we copy
1889   // the sret argument into %rax for the return. Save the argument into
1890   // a virtual register so that we can access it from the return points.
1891   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1892     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1893     unsigned Reg = FuncInfo->getSRetReturnReg();
1894     if (!Reg) {
1895       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1896       FuncInfo->setSRetReturnReg(Reg);
1897     }
1898     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1899     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1900   }
1901
1902   unsigned StackSize = CCInfo.getNextStackOffset();
1903   // Align stack specially for tail calls.
1904   if (FuncIsMadeTailCallSafe(CallConv,
1905                              MF.getTarget().Options.GuaranteedTailCallOpt))
1906     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1907
1908   // If the function takes variable number of arguments, make a frame index for
1909   // the start of the first vararg value... for expansion of llvm.va_start.
1910   if (isVarArg) {
1911     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1912                     CallConv != CallingConv::X86_ThisCall)) {
1913       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1914     }
1915     if (Is64Bit) {
1916       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1917
1918       // FIXME: We should really autogenerate these arrays
1919       static const unsigned GPR64ArgRegsWin64[] = {
1920         X86::RCX, X86::RDX, X86::R8,  X86::R9
1921       };
1922       static const unsigned GPR64ArgRegs64Bit[] = {
1923         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1924       };
1925       static const unsigned XMMArgRegs64Bit[] = {
1926         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1927         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1928       };
1929       const unsigned *GPR64ArgRegs;
1930       unsigned NumXMMRegs = 0;
1931
1932       if (IsWin64) {
1933         // The XMM registers which might contain var arg parameters are shadowed
1934         // in their paired GPR.  So we only need to save the GPR to their home
1935         // slots.
1936         TotalNumIntRegs = 4;
1937         GPR64ArgRegs = GPR64ArgRegsWin64;
1938       } else {
1939         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1940         GPR64ArgRegs = GPR64ArgRegs64Bit;
1941
1942         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1943                                                 TotalNumXMMRegs);
1944       }
1945       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1946                                                        TotalNumIntRegs);
1947
1948       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1949       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1950              "SSE register cannot be used when SSE is disabled!");
1951       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1952                NoImplicitFloatOps) &&
1953              "SSE register cannot be used when SSE is disabled!");
1954       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1955           !Subtarget->hasSSE1())
1956         // Kernel mode asks for SSE to be disabled, so don't push them
1957         // on the stack.
1958         TotalNumXMMRegs = 0;
1959
1960       if (IsWin64) {
1961         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1962         // Get to the caller-allocated home save location.  Add 8 to account
1963         // for the return address.
1964         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1965         FuncInfo->setRegSaveFrameIndex(
1966           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1967         // Fixup to set vararg frame on shadow area (4 x i64).
1968         if (NumIntRegs < 4)
1969           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1970       } else {
1971         // For X86-64, if there are vararg parameters that are passed via
1972         // registers, then we must store them to their spots on the stack so
1973         // they may be loaded by deferencing the result of va_next.
1974         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1975         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1976         FuncInfo->setRegSaveFrameIndex(
1977           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1978                                false));
1979       }
1980
1981       // Store the integer parameter registers.
1982       SmallVector<SDValue, 8> MemOps;
1983       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1984                                         getPointerTy());
1985       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1986       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1987         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1988                                   DAG.getIntPtrConstant(Offset));
1989         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1990                                      X86::GR64RegisterClass);
1991         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1992         SDValue Store =
1993           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1994                        MachinePointerInfo::getFixedStack(
1995                          FuncInfo->getRegSaveFrameIndex(), Offset),
1996                        false, false, 0);
1997         MemOps.push_back(Store);
1998         Offset += 8;
1999       }
2000
2001       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2002         // Now store the XMM (fp + vector) parameter registers.
2003         SmallVector<SDValue, 11> SaveXMMOps;
2004         SaveXMMOps.push_back(Chain);
2005
2006         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
2007         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2008         SaveXMMOps.push_back(ALVal);
2009
2010         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2011                                FuncInfo->getRegSaveFrameIndex()));
2012         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2013                                FuncInfo->getVarArgsFPOffset()));
2014
2015         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2016           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2017                                        X86::VR128RegisterClass);
2018           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2019           SaveXMMOps.push_back(Val);
2020         }
2021         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2022                                      MVT::Other,
2023                                      &SaveXMMOps[0], SaveXMMOps.size()));
2024       }
2025
2026       if (!MemOps.empty())
2027         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2028                             &MemOps[0], MemOps.size());
2029     }
2030   }
2031
2032   // Some CCs need callee pop.
2033   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2034                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2035     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2036   } else {
2037     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2038     // If this is an sret function, the return should pop the hidden pointer.
2039     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2040         ArgsAreStructReturn(Ins))
2041       FuncInfo->setBytesToPopOnReturn(4);
2042   }
2043
2044   if (!Is64Bit) {
2045     // RegSaveFrameIndex is X86-64 only.
2046     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2047     if (CallConv == CallingConv::X86_FastCall ||
2048         CallConv == CallingConv::X86_ThisCall)
2049       // fastcc functions can't have varargs.
2050       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2051   }
2052
2053   FuncInfo->setArgumentStackSize(StackSize);
2054
2055   return Chain;
2056 }
2057
2058 SDValue
2059 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2060                                     SDValue StackPtr, SDValue Arg,
2061                                     DebugLoc dl, SelectionDAG &DAG,
2062                                     const CCValAssign &VA,
2063                                     ISD::ArgFlagsTy Flags) const {
2064   unsigned LocMemOffset = VA.getLocMemOffset();
2065   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2066   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2067   if (Flags.isByVal())
2068     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2069
2070   return DAG.getStore(Chain, dl, Arg, PtrOff,
2071                       MachinePointerInfo::getStack(LocMemOffset),
2072                       false, false, 0);
2073 }
2074
2075 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2076 /// optimization is performed and it is required.
2077 SDValue
2078 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2079                                            SDValue &OutRetAddr, SDValue Chain,
2080                                            bool IsTailCall, bool Is64Bit,
2081                                            int FPDiff, DebugLoc dl) const {
2082   // Adjust the Return address stack slot.
2083   EVT VT = getPointerTy();
2084   OutRetAddr = getReturnAddressFrameIndex(DAG);
2085
2086   // Load the "old" Return address.
2087   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2088                            false, false, false, 0);
2089   return SDValue(OutRetAddr.getNode(), 1);
2090 }
2091
2092 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2093 /// optimization is performed and it is required (FPDiff!=0).
2094 static SDValue
2095 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2096                          SDValue Chain, SDValue RetAddrFrIdx,
2097                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2098   // Store the return address to the appropriate stack slot.
2099   if (!FPDiff) return Chain;
2100   // Calculate the new stack slot for the return address.
2101   int SlotSize = Is64Bit ? 8 : 4;
2102   int NewReturnAddrFI =
2103     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2104   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2105   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2106   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2107                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2108                        false, false, 0);
2109   return Chain;
2110 }
2111
2112 SDValue
2113 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2114                              CallingConv::ID CallConv, bool isVarArg,
2115                              bool &isTailCall,
2116                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2117                              const SmallVectorImpl<SDValue> &OutVals,
2118                              const SmallVectorImpl<ISD::InputArg> &Ins,
2119                              DebugLoc dl, SelectionDAG &DAG,
2120                              SmallVectorImpl<SDValue> &InVals) const {
2121   MachineFunction &MF = DAG.getMachineFunction();
2122   bool Is64Bit        = Subtarget->is64Bit();
2123   bool IsWin64        = Subtarget->isTargetWin64();
2124   bool IsWindows      = Subtarget->isTargetWindows();
2125   bool IsStructRet    = CallIsStructReturn(Outs);
2126   bool IsSibcall      = false;
2127
2128   if (MF.getTarget().Options.DisableTailCalls)
2129     isTailCall = false;
2130
2131   if (isTailCall) {
2132     // Check if it's really possible to do a tail call.
2133     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2134                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2135                                                    Outs, OutVals, Ins, DAG);
2136
2137     // Sibcalls are automatically detected tailcalls which do not require
2138     // ABI changes.
2139     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2140       IsSibcall = true;
2141
2142     if (isTailCall)
2143       ++NumTailCalls;
2144   }
2145
2146   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2147          "Var args not supported with calling convention fastcc or ghc");
2148
2149   // Analyze operands of the call, assigning locations to each operand.
2150   SmallVector<CCValAssign, 16> ArgLocs;
2151   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2152                  ArgLocs, *DAG.getContext());
2153
2154   // Allocate shadow area for Win64
2155   if (IsWin64) {
2156     CCInfo.AllocateStack(32, 8);
2157   }
2158
2159   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2160
2161   // Get a count of how many bytes are to be pushed on the stack.
2162   unsigned NumBytes = CCInfo.getNextStackOffset();
2163   if (IsSibcall)
2164     // This is a sibcall. The memory operands are available in caller's
2165     // own caller's stack.
2166     NumBytes = 0;
2167   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2168            IsTailCallConvention(CallConv))
2169     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2170
2171   int FPDiff = 0;
2172   if (isTailCall && !IsSibcall) {
2173     // Lower arguments at fp - stackoffset + fpdiff.
2174     unsigned NumBytesCallerPushed =
2175       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2176     FPDiff = NumBytesCallerPushed - NumBytes;
2177
2178     // Set the delta of movement of the returnaddr stackslot.
2179     // But only set if delta is greater than previous delta.
2180     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2181       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2182   }
2183
2184   if (!IsSibcall)
2185     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2186
2187   SDValue RetAddrFrIdx;
2188   // Load return address for tail calls.
2189   if (isTailCall && FPDiff)
2190     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2191                                     Is64Bit, FPDiff, dl);
2192
2193   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2194   SmallVector<SDValue, 8> MemOpChains;
2195   SDValue StackPtr;
2196
2197   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2198   // of tail call optimization arguments are handle later.
2199   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2200     CCValAssign &VA = ArgLocs[i];
2201     EVT RegVT = VA.getLocVT();
2202     SDValue Arg = OutVals[i];
2203     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2204     bool isByVal = Flags.isByVal();
2205
2206     // Promote the value if needed.
2207     switch (VA.getLocInfo()) {
2208     default: llvm_unreachable("Unknown loc info!");
2209     case CCValAssign::Full: break;
2210     case CCValAssign::SExt:
2211       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2212       break;
2213     case CCValAssign::ZExt:
2214       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2215       break;
2216     case CCValAssign::AExt:
2217       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2218         // Special case: passing MMX values in XMM registers.
2219         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2220         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2221         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2222       } else
2223         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2224       break;
2225     case CCValAssign::BCvt:
2226       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2227       break;
2228     case CCValAssign::Indirect: {
2229       // Store the argument.
2230       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2231       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2232       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2233                            MachinePointerInfo::getFixedStack(FI),
2234                            false, false, 0);
2235       Arg = SpillSlot;
2236       break;
2237     }
2238     }
2239
2240     if (VA.isRegLoc()) {
2241       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2242       if (isVarArg && IsWin64) {
2243         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2244         // shadow reg if callee is a varargs function.
2245         unsigned ShadowReg = 0;
2246         switch (VA.getLocReg()) {
2247         case X86::XMM0: ShadowReg = X86::RCX; break;
2248         case X86::XMM1: ShadowReg = X86::RDX; break;
2249         case X86::XMM2: ShadowReg = X86::R8; break;
2250         case X86::XMM3: ShadowReg = X86::R9; break;
2251         }
2252         if (ShadowReg)
2253           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2254       }
2255     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2256       assert(VA.isMemLoc());
2257       if (StackPtr.getNode() == 0)
2258         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2259       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2260                                              dl, DAG, VA, Flags));
2261     }
2262   }
2263
2264   if (!MemOpChains.empty())
2265     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2266                         &MemOpChains[0], MemOpChains.size());
2267
2268   // Build a sequence of copy-to-reg nodes chained together with token chain
2269   // and flag operands which copy the outgoing args into registers.
2270   SDValue InFlag;
2271   // Tail call byval lowering might overwrite argument registers so in case of
2272   // tail call optimization the copies to registers are lowered later.
2273   if (!isTailCall)
2274     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2275       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2276                                RegsToPass[i].second, InFlag);
2277       InFlag = Chain.getValue(1);
2278     }
2279
2280   if (Subtarget->isPICStyleGOT()) {
2281     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2282     // GOT pointer.
2283     if (!isTailCall) {
2284       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2285                                DAG.getNode(X86ISD::GlobalBaseReg,
2286                                            DebugLoc(), getPointerTy()),
2287                                InFlag);
2288       InFlag = Chain.getValue(1);
2289     } else {
2290       // If we are tail calling and generating PIC/GOT style code load the
2291       // address of the callee into ECX. The value in ecx is used as target of
2292       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2293       // for tail calls on PIC/GOT architectures. Normally we would just put the
2294       // address of GOT into ebx and then call target@PLT. But for tail calls
2295       // ebx would be restored (since ebx is callee saved) before jumping to the
2296       // target@PLT.
2297
2298       // Note: The actual moving to ECX is done further down.
2299       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2300       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2301           !G->getGlobal()->hasProtectedVisibility())
2302         Callee = LowerGlobalAddress(Callee, DAG);
2303       else if (isa<ExternalSymbolSDNode>(Callee))
2304         Callee = LowerExternalSymbol(Callee, DAG);
2305     }
2306   }
2307
2308   if (Is64Bit && isVarArg && !IsWin64) {
2309     // From AMD64 ABI document:
2310     // For calls that may call functions that use varargs or stdargs
2311     // (prototype-less calls or calls to functions containing ellipsis (...) in
2312     // the declaration) %al is used as hidden argument to specify the number
2313     // of SSE registers used. The contents of %al do not need to match exactly
2314     // the number of registers, but must be an ubound on the number of SSE
2315     // registers used and is in the range 0 - 8 inclusive.
2316
2317     // Count the number of XMM registers allocated.
2318     static const unsigned XMMArgRegs[] = {
2319       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2320       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2321     };
2322     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2323     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2324            && "SSE registers cannot be used when SSE is disabled");
2325
2326     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2327                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2328     InFlag = Chain.getValue(1);
2329   }
2330
2331
2332   // For tail calls lower the arguments to the 'real' stack slot.
2333   if (isTailCall) {
2334     // Force all the incoming stack arguments to be loaded from the stack
2335     // before any new outgoing arguments are stored to the stack, because the
2336     // outgoing stack slots may alias the incoming argument stack slots, and
2337     // the alias isn't otherwise explicit. This is slightly more conservative
2338     // than necessary, because it means that each store effectively depends
2339     // on every argument instead of just those arguments it would clobber.
2340     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2341
2342     SmallVector<SDValue, 8> MemOpChains2;
2343     SDValue FIN;
2344     int FI = 0;
2345     // Do not flag preceding copytoreg stuff together with the following stuff.
2346     InFlag = SDValue();
2347     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2348       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2349         CCValAssign &VA = ArgLocs[i];
2350         if (VA.isRegLoc())
2351           continue;
2352         assert(VA.isMemLoc());
2353         SDValue Arg = OutVals[i];
2354         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2355         // Create frame index.
2356         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2357         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2358         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2359         FIN = DAG.getFrameIndex(FI, getPointerTy());
2360
2361         if (Flags.isByVal()) {
2362           // Copy relative to framepointer.
2363           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2364           if (StackPtr.getNode() == 0)
2365             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2366                                           getPointerTy());
2367           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2368
2369           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2370                                                            ArgChain,
2371                                                            Flags, DAG, dl));
2372         } else {
2373           // Store relative to framepointer.
2374           MemOpChains2.push_back(
2375             DAG.getStore(ArgChain, dl, Arg, FIN,
2376                          MachinePointerInfo::getFixedStack(FI),
2377                          false, false, 0));
2378         }
2379       }
2380     }
2381
2382     if (!MemOpChains2.empty())
2383       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2384                           &MemOpChains2[0], MemOpChains2.size());
2385
2386     // Copy arguments to their registers.
2387     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2388       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2389                                RegsToPass[i].second, InFlag);
2390       InFlag = Chain.getValue(1);
2391     }
2392     InFlag =SDValue();
2393
2394     // Store the return address to the appropriate stack slot.
2395     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2396                                      FPDiff, dl);
2397   }
2398
2399   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2400     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2401     // In the 64-bit large code model, we have to make all calls
2402     // through a register, since the call instruction's 32-bit
2403     // pc-relative offset may not be large enough to hold the whole
2404     // address.
2405   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2406     // If the callee is a GlobalAddress node (quite common, every direct call
2407     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2408     // it.
2409
2410     // We should use extra load for direct calls to dllimported functions in
2411     // non-JIT mode.
2412     const GlobalValue *GV = G->getGlobal();
2413     if (!GV->hasDLLImportLinkage()) {
2414       unsigned char OpFlags = 0;
2415       bool ExtraLoad = false;
2416       unsigned WrapperKind = ISD::DELETED_NODE;
2417
2418       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2419       // external symbols most go through the PLT in PIC mode.  If the symbol
2420       // has hidden or protected visibility, or if it is static or local, then
2421       // we don't need to use the PLT - we can directly call it.
2422       if (Subtarget->isTargetELF() &&
2423           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2424           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2425         OpFlags = X86II::MO_PLT;
2426       } else if (Subtarget->isPICStyleStubAny() &&
2427                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2428                  (!Subtarget->getTargetTriple().isMacOSX() ||
2429                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2430         // PC-relative references to external symbols should go through $stub,
2431         // unless we're building with the leopard linker or later, which
2432         // automatically synthesizes these stubs.
2433         OpFlags = X86II::MO_DARWIN_STUB;
2434       } else if (Subtarget->isPICStyleRIPRel() &&
2435                  isa<Function>(GV) &&
2436                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2437         // If the function is marked as non-lazy, generate an indirect call
2438         // which loads from the GOT directly. This avoids runtime overhead
2439         // at the cost of eager binding (and one extra byte of encoding).
2440         OpFlags = X86II::MO_GOTPCREL;
2441         WrapperKind = X86ISD::WrapperRIP;
2442         ExtraLoad = true;
2443       }
2444
2445       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2446                                           G->getOffset(), OpFlags);
2447
2448       // Add a wrapper if needed.
2449       if (WrapperKind != ISD::DELETED_NODE)
2450         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2451       // Add extra indirection if needed.
2452       if (ExtraLoad)
2453         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2454                              MachinePointerInfo::getGOT(),
2455                              false, false, false, 0);
2456     }
2457   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2458     unsigned char OpFlags = 0;
2459
2460     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2461     // external symbols should go through the PLT.
2462     if (Subtarget->isTargetELF() &&
2463         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2464       OpFlags = X86II::MO_PLT;
2465     } else if (Subtarget->isPICStyleStubAny() &&
2466                (!Subtarget->getTargetTriple().isMacOSX() ||
2467                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2468       // PC-relative references to external symbols should go through $stub,
2469       // unless we're building with the leopard linker or later, which
2470       // automatically synthesizes these stubs.
2471       OpFlags = X86II::MO_DARWIN_STUB;
2472     }
2473
2474     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2475                                          OpFlags);
2476   }
2477
2478   // Returns a chain & a flag for retval copy to use.
2479   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2480   SmallVector<SDValue, 8> Ops;
2481
2482   if (!IsSibcall && isTailCall) {
2483     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2484                            DAG.getIntPtrConstant(0, true), InFlag);
2485     InFlag = Chain.getValue(1);
2486   }
2487
2488   Ops.push_back(Chain);
2489   Ops.push_back(Callee);
2490
2491   if (isTailCall)
2492     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2493
2494   // Add argument registers to the end of the list so that they are known live
2495   // into the call.
2496   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2497     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2498                                   RegsToPass[i].second.getValueType()));
2499
2500   // Add an implicit use GOT pointer in EBX.
2501   if (!isTailCall && Subtarget->isPICStyleGOT())
2502     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2503
2504   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2505   if (Is64Bit && isVarArg && !IsWin64)
2506     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2507
2508   // Experimental: Add a register mask operand representing the call-preserved
2509   // registers.
2510   if (UseRegMask) {
2511     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2512     const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2513     Ops.push_back(DAG.getRegisterMask(Mask));
2514   }
2515
2516   if (InFlag.getNode())
2517     Ops.push_back(InFlag);
2518
2519   if (isTailCall) {
2520     // We used to do:
2521     //// If this is the first return lowered for this function, add the regs
2522     //// to the liveout set for the function.
2523     // This isn't right, although it's probably harmless on x86; liveouts
2524     // should be computed from returns not tail calls.  Consider a void
2525     // function making a tail call to a function returning int.
2526     return DAG.getNode(X86ISD::TC_RETURN, dl,
2527                        NodeTys, &Ops[0], Ops.size());
2528   }
2529
2530   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2531   InFlag = Chain.getValue(1);
2532
2533   // Create the CALLSEQ_END node.
2534   unsigned NumBytesForCalleeToPush;
2535   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2536                        getTargetMachine().Options.GuaranteedTailCallOpt))
2537     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2538   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2539            IsStructRet)
2540     // If this is a call to a struct-return function, the callee
2541     // pops the hidden struct pointer, so we have to push it back.
2542     // This is common for Darwin/X86, Linux & Mingw32 targets.
2543     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2544     NumBytesForCalleeToPush = 4;
2545   else
2546     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2547
2548   // Returns a flag for retval copy to use.
2549   if (!IsSibcall) {
2550     Chain = DAG.getCALLSEQ_END(Chain,
2551                                DAG.getIntPtrConstant(NumBytes, true),
2552                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2553                                                      true),
2554                                InFlag);
2555     InFlag = Chain.getValue(1);
2556   }
2557
2558   // Handle result values, copying them out of physregs into vregs that we
2559   // return.
2560   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2561                          Ins, dl, DAG, InVals);
2562 }
2563
2564
2565 //===----------------------------------------------------------------------===//
2566 //                Fast Calling Convention (tail call) implementation
2567 //===----------------------------------------------------------------------===//
2568
2569 //  Like std call, callee cleans arguments, convention except that ECX is
2570 //  reserved for storing the tail called function address. Only 2 registers are
2571 //  free for argument passing (inreg). Tail call optimization is performed
2572 //  provided:
2573 //                * tailcallopt is enabled
2574 //                * caller/callee are fastcc
2575 //  On X86_64 architecture with GOT-style position independent code only local
2576 //  (within module) calls are supported at the moment.
2577 //  To keep the stack aligned according to platform abi the function
2578 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2579 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2580 //  If a tail called function callee has more arguments than the caller the
2581 //  caller needs to make sure that there is room to move the RETADDR to. This is
2582 //  achieved by reserving an area the size of the argument delta right after the
2583 //  original REtADDR, but before the saved framepointer or the spilled registers
2584 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2585 //  stack layout:
2586 //    arg1
2587 //    arg2
2588 //    RETADDR
2589 //    [ new RETADDR
2590 //      move area ]
2591 //    (possible EBP)
2592 //    ESI
2593 //    EDI
2594 //    local1 ..
2595
2596 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2597 /// for a 16 byte align requirement.
2598 unsigned
2599 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2600                                                SelectionDAG& DAG) const {
2601   MachineFunction &MF = DAG.getMachineFunction();
2602   const TargetMachine &TM = MF.getTarget();
2603   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2604   unsigned StackAlignment = TFI.getStackAlignment();
2605   uint64_t AlignMask = StackAlignment - 1;
2606   int64_t Offset = StackSize;
2607   uint64_t SlotSize = TD->getPointerSize();
2608   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2609     // Number smaller than 12 so just add the difference.
2610     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2611   } else {
2612     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2613     Offset = ((~AlignMask) & Offset) + StackAlignment +
2614       (StackAlignment-SlotSize);
2615   }
2616   return Offset;
2617 }
2618
2619 /// MatchingStackOffset - Return true if the given stack call argument is
2620 /// already available in the same position (relatively) of the caller's
2621 /// incoming argument stack.
2622 static
2623 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2624                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2625                          const X86InstrInfo *TII) {
2626   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2627   int FI = INT_MAX;
2628   if (Arg.getOpcode() == ISD::CopyFromReg) {
2629     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2630     if (!TargetRegisterInfo::isVirtualRegister(VR))
2631       return false;
2632     MachineInstr *Def = MRI->getVRegDef(VR);
2633     if (!Def)
2634       return false;
2635     if (!Flags.isByVal()) {
2636       if (!TII->isLoadFromStackSlot(Def, FI))
2637         return false;
2638     } else {
2639       unsigned Opcode = Def->getOpcode();
2640       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2641           Def->getOperand(1).isFI()) {
2642         FI = Def->getOperand(1).getIndex();
2643         Bytes = Flags.getByValSize();
2644       } else
2645         return false;
2646     }
2647   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2648     if (Flags.isByVal())
2649       // ByVal argument is passed in as a pointer but it's now being
2650       // dereferenced. e.g.
2651       // define @foo(%struct.X* %A) {
2652       //   tail call @bar(%struct.X* byval %A)
2653       // }
2654       return false;
2655     SDValue Ptr = Ld->getBasePtr();
2656     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2657     if (!FINode)
2658       return false;
2659     FI = FINode->getIndex();
2660   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2661     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2662     FI = FINode->getIndex();
2663     Bytes = Flags.getByValSize();
2664   } else
2665     return false;
2666
2667   assert(FI != INT_MAX);
2668   if (!MFI->isFixedObjectIndex(FI))
2669     return false;
2670   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2671 }
2672
2673 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2674 /// for tail call optimization. Targets which want to do tail call
2675 /// optimization should implement this function.
2676 bool
2677 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2678                                                      CallingConv::ID CalleeCC,
2679                                                      bool isVarArg,
2680                                                      bool isCalleeStructRet,
2681                                                      bool isCallerStructRet,
2682                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2683                                     const SmallVectorImpl<SDValue> &OutVals,
2684                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2685                                                      SelectionDAG& DAG) const {
2686   if (!IsTailCallConvention(CalleeCC) &&
2687       CalleeCC != CallingConv::C)
2688     return false;
2689
2690   // If -tailcallopt is specified, make fastcc functions tail-callable.
2691   const MachineFunction &MF = DAG.getMachineFunction();
2692   const Function *CallerF = DAG.getMachineFunction().getFunction();
2693   CallingConv::ID CallerCC = CallerF->getCallingConv();
2694   bool CCMatch = CallerCC == CalleeCC;
2695
2696   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2697     if (IsTailCallConvention(CalleeCC) && CCMatch)
2698       return true;
2699     return false;
2700   }
2701
2702   // Look for obvious safe cases to perform tail call optimization that do not
2703   // require ABI changes. This is what gcc calls sibcall.
2704
2705   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2706   // emit a special epilogue.
2707   if (RegInfo->needsStackRealignment(MF))
2708     return false;
2709
2710   // Also avoid sibcall optimization if either caller or callee uses struct
2711   // return semantics.
2712   if (isCalleeStructRet || isCallerStructRet)
2713     return false;
2714
2715   // An stdcall caller is expected to clean up its arguments; the callee
2716   // isn't going to do that.
2717   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2718     return false;
2719
2720   // Do not sibcall optimize vararg calls unless all arguments are passed via
2721   // registers.
2722   if (isVarArg && !Outs.empty()) {
2723
2724     // Optimizing for varargs on Win64 is unlikely to be safe without
2725     // additional testing.
2726     if (Subtarget->isTargetWin64())
2727       return false;
2728
2729     SmallVector<CCValAssign, 16> ArgLocs;
2730     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2731                    getTargetMachine(), ArgLocs, *DAG.getContext());
2732
2733     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2734     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2735       if (!ArgLocs[i].isRegLoc())
2736         return false;
2737   }
2738
2739   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2740   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2741   // this into a sibcall.
2742   bool Unused = false;
2743   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2744     if (!Ins[i].Used) {
2745       Unused = true;
2746       break;
2747     }
2748   }
2749   if (Unused) {
2750     SmallVector<CCValAssign, 16> RVLocs;
2751     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2752                    getTargetMachine(), RVLocs, *DAG.getContext());
2753     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2754     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2755       CCValAssign &VA = RVLocs[i];
2756       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2757         return false;
2758     }
2759   }
2760
2761   // If the calling conventions do not match, then we'd better make sure the
2762   // results are returned in the same way as what the caller expects.
2763   if (!CCMatch) {
2764     SmallVector<CCValAssign, 16> RVLocs1;
2765     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2766                     getTargetMachine(), RVLocs1, *DAG.getContext());
2767     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2768
2769     SmallVector<CCValAssign, 16> RVLocs2;
2770     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2771                     getTargetMachine(), RVLocs2, *DAG.getContext());
2772     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2773
2774     if (RVLocs1.size() != RVLocs2.size())
2775       return false;
2776     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2777       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2778         return false;
2779       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2780         return false;
2781       if (RVLocs1[i].isRegLoc()) {
2782         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2783           return false;
2784       } else {
2785         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2786           return false;
2787       }
2788     }
2789   }
2790
2791   // If the callee takes no arguments then go on to check the results of the
2792   // call.
2793   if (!Outs.empty()) {
2794     // Check if stack adjustment is needed. For now, do not do this if any
2795     // argument is passed on the stack.
2796     SmallVector<CCValAssign, 16> ArgLocs;
2797     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2798                    getTargetMachine(), ArgLocs, *DAG.getContext());
2799
2800     // Allocate shadow area for Win64
2801     if (Subtarget->isTargetWin64()) {
2802       CCInfo.AllocateStack(32, 8);
2803     }
2804
2805     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2806     if (CCInfo.getNextStackOffset()) {
2807       MachineFunction &MF = DAG.getMachineFunction();
2808       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2809         return false;
2810
2811       // Check if the arguments are already laid out in the right way as
2812       // the caller's fixed stack objects.
2813       MachineFrameInfo *MFI = MF.getFrameInfo();
2814       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2815       const X86InstrInfo *TII =
2816         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2817       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2818         CCValAssign &VA = ArgLocs[i];
2819         SDValue Arg = OutVals[i];
2820         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2821         if (VA.getLocInfo() == CCValAssign::Indirect)
2822           return false;
2823         if (!VA.isRegLoc()) {
2824           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2825                                    MFI, MRI, TII))
2826             return false;
2827         }
2828       }
2829     }
2830
2831     // If the tailcall address may be in a register, then make sure it's
2832     // possible to register allocate for it. In 32-bit, the call address can
2833     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2834     // callee-saved registers are restored. These happen to be the same
2835     // registers used to pass 'inreg' arguments so watch out for those.
2836     if (!Subtarget->is64Bit() &&
2837         !isa<GlobalAddressSDNode>(Callee) &&
2838         !isa<ExternalSymbolSDNode>(Callee)) {
2839       unsigned NumInRegs = 0;
2840       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2841         CCValAssign &VA = ArgLocs[i];
2842         if (!VA.isRegLoc())
2843           continue;
2844         unsigned Reg = VA.getLocReg();
2845         switch (Reg) {
2846         default: break;
2847         case X86::EAX: case X86::EDX: case X86::ECX:
2848           if (++NumInRegs == 3)
2849             return false;
2850           break;
2851         }
2852       }
2853     }
2854   }
2855
2856   return true;
2857 }
2858
2859 FastISel *
2860 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2861   return X86::createFastISel(funcInfo);
2862 }
2863
2864
2865 //===----------------------------------------------------------------------===//
2866 //                           Other Lowering Hooks
2867 //===----------------------------------------------------------------------===//
2868
2869 static bool MayFoldLoad(SDValue Op) {
2870   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2871 }
2872
2873 static bool MayFoldIntoStore(SDValue Op) {
2874   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2875 }
2876
2877 static bool isTargetShuffle(unsigned Opcode) {
2878   switch(Opcode) {
2879   default: return false;
2880   case X86ISD::PSHUFD:
2881   case X86ISD::PSHUFHW:
2882   case X86ISD::PSHUFLW:
2883   case X86ISD::SHUFP:
2884   case X86ISD::PALIGN:
2885   case X86ISD::MOVLHPS:
2886   case X86ISD::MOVLHPD:
2887   case X86ISD::MOVHLPS:
2888   case X86ISD::MOVLPS:
2889   case X86ISD::MOVLPD:
2890   case X86ISD::MOVSHDUP:
2891   case X86ISD::MOVSLDUP:
2892   case X86ISD::MOVDDUP:
2893   case X86ISD::MOVSS:
2894   case X86ISD::MOVSD:
2895   case X86ISD::UNPCKL:
2896   case X86ISD::UNPCKH:
2897   case X86ISD::VPERMILP:
2898   case X86ISD::VPERM2X128:
2899     return true;
2900   }
2901 }
2902
2903 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2904                                                SDValue V1, SelectionDAG &DAG) {
2905   switch(Opc) {
2906   default: llvm_unreachable("Unknown x86 shuffle node");
2907   case X86ISD::MOVSHDUP:
2908   case X86ISD::MOVSLDUP:
2909   case X86ISD::MOVDDUP:
2910     return DAG.getNode(Opc, dl, VT, V1);
2911   }
2912 }
2913
2914 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2915                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2916   switch(Opc) {
2917   default: llvm_unreachable("Unknown x86 shuffle node");
2918   case X86ISD::PSHUFD:
2919   case X86ISD::PSHUFHW:
2920   case X86ISD::PSHUFLW:
2921   case X86ISD::VPERMILP:
2922     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2923   }
2924 }
2925
2926 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2927                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2928   switch(Opc) {
2929   default: llvm_unreachable("Unknown x86 shuffle node");
2930   case X86ISD::PALIGN:
2931   case X86ISD::SHUFP:
2932   case X86ISD::VPERM2X128:
2933     return DAG.getNode(Opc, dl, VT, V1, V2,
2934                        DAG.getConstant(TargetMask, MVT::i8));
2935   }
2936 }
2937
2938 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2939                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2940   switch(Opc) {
2941   default: llvm_unreachable("Unknown x86 shuffle node");
2942   case X86ISD::MOVLHPS:
2943   case X86ISD::MOVLHPD:
2944   case X86ISD::MOVHLPS:
2945   case X86ISD::MOVLPS:
2946   case X86ISD::MOVLPD:
2947   case X86ISD::MOVSS:
2948   case X86ISD::MOVSD:
2949   case X86ISD::UNPCKL:
2950   case X86ISD::UNPCKH:
2951     return DAG.getNode(Opc, dl, VT, V1, V2);
2952   }
2953 }
2954
2955 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2956   MachineFunction &MF = DAG.getMachineFunction();
2957   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2958   int ReturnAddrIndex = FuncInfo->getRAIndex();
2959
2960   if (ReturnAddrIndex == 0) {
2961     // Set up a frame object for the return address.
2962     uint64_t SlotSize = TD->getPointerSize();
2963     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2964                                                            false);
2965     FuncInfo->setRAIndex(ReturnAddrIndex);
2966   }
2967
2968   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2969 }
2970
2971
2972 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2973                                        bool hasSymbolicDisplacement) {
2974   // Offset should fit into 32 bit immediate field.
2975   if (!isInt<32>(Offset))
2976     return false;
2977
2978   // If we don't have a symbolic displacement - we don't have any extra
2979   // restrictions.
2980   if (!hasSymbolicDisplacement)
2981     return true;
2982
2983   // FIXME: Some tweaks might be needed for medium code model.
2984   if (M != CodeModel::Small && M != CodeModel::Kernel)
2985     return false;
2986
2987   // For small code model we assume that latest object is 16MB before end of 31
2988   // bits boundary. We may also accept pretty large negative constants knowing
2989   // that all objects are in the positive half of address space.
2990   if (M == CodeModel::Small && Offset < 16*1024*1024)
2991     return true;
2992
2993   // For kernel code model we know that all object resist in the negative half
2994   // of 32bits address space. We may not accept negative offsets, since they may
2995   // be just off and we may accept pretty large positive ones.
2996   if (M == CodeModel::Kernel && Offset > 0)
2997     return true;
2998
2999   return false;
3000 }
3001
3002 /// isCalleePop - Determines whether the callee is required to pop its
3003 /// own arguments. Callee pop is necessary to support tail calls.
3004 bool X86::isCalleePop(CallingConv::ID CallingConv,
3005                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3006   if (IsVarArg)
3007     return false;
3008
3009   switch (CallingConv) {
3010   default:
3011     return false;
3012   case CallingConv::X86_StdCall:
3013     return !is64Bit;
3014   case CallingConv::X86_FastCall:
3015     return !is64Bit;
3016   case CallingConv::X86_ThisCall:
3017     return !is64Bit;
3018   case CallingConv::Fast:
3019     return TailCallOpt;
3020   case CallingConv::GHC:
3021     return TailCallOpt;
3022   }
3023 }
3024
3025 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3026 /// specific condition code, returning the condition code and the LHS/RHS of the
3027 /// comparison to make.
3028 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3029                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3030   if (!isFP) {
3031     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3032       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3033         // X > -1   -> X == 0, jump !sign.
3034         RHS = DAG.getConstant(0, RHS.getValueType());
3035         return X86::COND_NS;
3036       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3037         // X < 0   -> X == 0, jump on sign.
3038         return X86::COND_S;
3039       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3040         // X < 1   -> X <= 0
3041         RHS = DAG.getConstant(0, RHS.getValueType());
3042         return X86::COND_LE;
3043       }
3044     }
3045
3046     switch (SetCCOpcode) {
3047     default: llvm_unreachable("Invalid integer condition!");
3048     case ISD::SETEQ:  return X86::COND_E;
3049     case ISD::SETGT:  return X86::COND_G;
3050     case ISD::SETGE:  return X86::COND_GE;
3051     case ISD::SETLT:  return X86::COND_L;
3052     case ISD::SETLE:  return X86::COND_LE;
3053     case ISD::SETNE:  return X86::COND_NE;
3054     case ISD::SETULT: return X86::COND_B;
3055     case ISD::SETUGT: return X86::COND_A;
3056     case ISD::SETULE: return X86::COND_BE;
3057     case ISD::SETUGE: return X86::COND_AE;
3058     }
3059   }
3060
3061   // First determine if it is required or is profitable to flip the operands.
3062
3063   // If LHS is a foldable load, but RHS is not, flip the condition.
3064   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3065       !ISD::isNON_EXTLoad(RHS.getNode())) {
3066     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3067     std::swap(LHS, RHS);
3068   }
3069
3070   switch (SetCCOpcode) {
3071   default: break;
3072   case ISD::SETOLT:
3073   case ISD::SETOLE:
3074   case ISD::SETUGT:
3075   case ISD::SETUGE:
3076     std::swap(LHS, RHS);
3077     break;
3078   }
3079
3080   // On a floating point condition, the flags are set as follows:
3081   // ZF  PF  CF   op
3082   //  0 | 0 | 0 | X > Y
3083   //  0 | 0 | 1 | X < Y
3084   //  1 | 0 | 0 | X == Y
3085   //  1 | 1 | 1 | unordered
3086   switch (SetCCOpcode) {
3087   default: llvm_unreachable("Condcode should be pre-legalized away");
3088   case ISD::SETUEQ:
3089   case ISD::SETEQ:   return X86::COND_E;
3090   case ISD::SETOLT:              // flipped
3091   case ISD::SETOGT:
3092   case ISD::SETGT:   return X86::COND_A;
3093   case ISD::SETOLE:              // flipped
3094   case ISD::SETOGE:
3095   case ISD::SETGE:   return X86::COND_AE;
3096   case ISD::SETUGT:              // flipped
3097   case ISD::SETULT:
3098   case ISD::SETLT:   return X86::COND_B;
3099   case ISD::SETUGE:              // flipped
3100   case ISD::SETULE:
3101   case ISD::SETLE:   return X86::COND_BE;
3102   case ISD::SETONE:
3103   case ISD::SETNE:   return X86::COND_NE;
3104   case ISD::SETUO:   return X86::COND_P;
3105   case ISD::SETO:    return X86::COND_NP;
3106   case ISD::SETOEQ:
3107   case ISD::SETUNE:  return X86::COND_INVALID;
3108   }
3109 }
3110
3111 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3112 /// code. Current x86 isa includes the following FP cmov instructions:
3113 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3114 static bool hasFPCMov(unsigned X86CC) {
3115   switch (X86CC) {
3116   default:
3117     return false;
3118   case X86::COND_B:
3119   case X86::COND_BE:
3120   case X86::COND_E:
3121   case X86::COND_P:
3122   case X86::COND_A:
3123   case X86::COND_AE:
3124   case X86::COND_NE:
3125   case X86::COND_NP:
3126     return true;
3127   }
3128 }
3129
3130 /// isFPImmLegal - Returns true if the target can instruction select the
3131 /// specified FP immediate natively. If false, the legalizer will
3132 /// materialize the FP immediate as a load from a constant pool.
3133 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3134   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3135     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3136       return true;
3137   }
3138   return false;
3139 }
3140
3141 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3142 /// the specified range (L, H].
3143 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3144   return (Val < 0) || (Val >= Low && Val < Hi);
3145 }
3146
3147 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3148 /// specified value.
3149 static bool isUndefOrEqual(int Val, int CmpVal) {
3150   if (Val < 0 || Val == CmpVal)
3151     return true;
3152   return false;
3153 }
3154
3155 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3156 /// from position Pos and ending in Pos+Size, falls within the specified
3157 /// sequential range (L, L+Pos]. or is undef.
3158 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3159                                        int Pos, int Size, int Low) {
3160   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3161     if (!isUndefOrEqual(Mask[i], Low))
3162       return false;
3163   return true;
3164 }
3165
3166 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3167 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3168 /// the second operand.
3169 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3170   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3171     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3172   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3173     return (Mask[0] < 2 && Mask[1] < 2);
3174   return false;
3175 }
3176
3177 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3178   return ::isPSHUFDMask(N->getMask(), N->getValueType(0));
3179 }
3180
3181 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3182 /// is suitable for input to PSHUFHW.
3183 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT) {
3184   if (VT != MVT::v8i16)
3185     return false;
3186
3187   // Lower quadword copied in order or undef.
3188   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3189     return false;
3190
3191   // Upper quadword shuffled.
3192   for (unsigned i = 4; i != 8; ++i)
3193     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3194       return false;
3195
3196   return true;
3197 }
3198
3199 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3200   return ::isPSHUFHWMask(N->getMask(), N->getValueType(0));
3201 }
3202
3203 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFLW.
3205 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT) {
3206   if (VT != MVT::v8i16)
3207     return false;
3208
3209   // Upper quadword copied in order.
3210   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3211     return false;
3212
3213   // Lower quadword shuffled.
3214   for (unsigned i = 0; i != 4; ++i)
3215     if (Mask[i] >= 4)
3216       return false;
3217
3218   return true;
3219 }
3220
3221 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3222   return ::isPSHUFLWMask(N->getMask(), N->getValueType(0));
3223 }
3224
3225 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3226 /// is suitable for input to PALIGNR.
3227 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3228                           const X86Subtarget *Subtarget) {
3229   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3230       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3231     return false;
3232
3233   unsigned NumElts = VT.getVectorNumElements();
3234   unsigned NumLanes = VT.getSizeInBits()/128;
3235   unsigned NumLaneElts = NumElts/NumLanes;
3236
3237   // Do not handle 64-bit element shuffles with palignr.
3238   if (NumLaneElts == 2)
3239     return false;
3240
3241   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3242     unsigned i;
3243     for (i = 0; i != NumLaneElts; ++i) {
3244       if (Mask[i+l] >= 0)
3245         break;
3246     }
3247
3248     // Lane is all undef, go to next lane
3249     if (i == NumLaneElts)
3250       continue;
3251
3252     int Start = Mask[i+l];
3253
3254     // Make sure its in this lane in one of the sources
3255     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3256         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3257       return false;
3258
3259     // If not lane 0, then we must match lane 0
3260     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3261       return false;
3262
3263     // Correct second source to be contiguous with first source
3264     if (Start >= (int)NumElts)
3265       Start -= NumElts - NumLaneElts;
3266
3267     // Make sure we're shifting in the right direction.
3268     if (Start <= (int)(i+l))
3269       return false;
3270
3271     Start -= i;
3272
3273     // Check the rest of the elements to see if they are consecutive.
3274     for (++i; i != NumLaneElts; ++i) {
3275       int Idx = Mask[i+l];
3276
3277       // Make sure its in this lane
3278       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3279           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3280         return false;
3281
3282       // If not lane 0, then we must match lane 0
3283       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3284         return false;
3285
3286       if (Idx >= (int)NumElts)
3287         Idx -= NumElts - NumLaneElts;
3288
3289       if (!isUndefOrEqual(Idx, Start+i))
3290         return false;
3291
3292     }
3293   }
3294
3295   return true;
3296 }
3297
3298 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3299 /// the two vector operands have swapped position.
3300 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3301                                      unsigned NumElems) {
3302   for (unsigned i = 0; i != NumElems; ++i) {
3303     int idx = Mask[i];
3304     if (idx < 0)
3305       continue;
3306     else if (idx < (int)NumElems)
3307       Mask[i] = idx + NumElems;
3308     else
3309       Mask[i] = idx - NumElems;
3310   }
3311 }
3312
3313 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3314 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3315 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3316 /// reverse of what x86 shuffles want.
3317 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3318                         bool Commuted = false) {
3319   if (!HasAVX && VT.getSizeInBits() == 256)
3320     return false;
3321
3322   unsigned NumElems = VT.getVectorNumElements();
3323   unsigned NumLanes = VT.getSizeInBits()/128;
3324   unsigned NumLaneElems = NumElems/NumLanes;
3325
3326   if (NumLaneElems != 2 && NumLaneElems != 4)
3327     return false;
3328
3329   // VSHUFPSY divides the resulting vector into 4 chunks.
3330   // The sources are also splitted into 4 chunks, and each destination
3331   // chunk must come from a different source chunk.
3332   //
3333   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3334   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3335   //
3336   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3337   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3338   //
3339   // VSHUFPDY divides the resulting vector into 4 chunks.
3340   // The sources are also splitted into 4 chunks, and each destination
3341   // chunk must come from a different source chunk.
3342   //
3343   //  SRC1 =>      X3       X2       X1       X0
3344   //  SRC2 =>      Y3       Y2       Y1       Y0
3345   //
3346   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3347   //
3348   unsigned HalfLaneElems = NumLaneElems/2;
3349   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3350     for (unsigned i = 0; i != NumLaneElems; ++i) {
3351       int Idx = Mask[i+l];
3352       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3353       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3354         return false;
3355       // For VSHUFPSY, the mask of the second half must be the same as the
3356       // first but with the appropriate offsets. This works in the same way as
3357       // VPERMILPS works with masks.
3358       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3359         continue;
3360       if (!isUndefOrEqual(Idx, Mask[i]+l))
3361         return false;
3362     }
3363   }
3364
3365   return true;
3366 }
3367
3368 bool X86::isSHUFPMask(ShuffleVectorSDNode *N, bool HasAVX) {
3369   return ::isSHUFPMask(N->getMask(), N->getValueType(0), HasAVX);
3370 }
3371
3372 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3373 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3374 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3375   EVT VT = N->getValueType(0);
3376   unsigned NumElems = VT.getVectorNumElements();
3377
3378   if (VT.getSizeInBits() != 128)
3379     return false;
3380
3381   if (NumElems != 4)
3382     return false;
3383
3384   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3385   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3386          isUndefOrEqual(N->getMaskElt(1), 7) &&
3387          isUndefOrEqual(N->getMaskElt(2), 2) &&
3388          isUndefOrEqual(N->getMaskElt(3), 3);
3389 }
3390
3391 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3392 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3393 /// <2, 3, 2, 3>
3394 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3395   EVT VT = N->getValueType(0);
3396   unsigned NumElems = VT.getVectorNumElements();
3397
3398   if (VT.getSizeInBits() != 128)
3399     return false;
3400
3401   if (NumElems != 4)
3402     return false;
3403
3404   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3405          isUndefOrEqual(N->getMaskElt(1), 3) &&
3406          isUndefOrEqual(N->getMaskElt(2), 2) &&
3407          isUndefOrEqual(N->getMaskElt(3), 3);
3408 }
3409
3410 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3411 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3412 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3413   EVT VT = N->getValueType(0);
3414
3415   if (VT.getSizeInBits() != 128)
3416     return false;
3417
3418   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3419
3420   if (NumElems != 2 && NumElems != 4)
3421     return false;
3422
3423   for (unsigned i = 0; i < NumElems/2; ++i)
3424     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3425       return false;
3426
3427   for (unsigned i = NumElems/2; i < NumElems; ++i)
3428     if (!isUndefOrEqual(N->getMaskElt(i), i))
3429       return false;
3430
3431   return true;
3432 }
3433
3434 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3435 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3436 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3437   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3438
3439   if ((NumElems != 2 && NumElems != 4)
3440       || N->getValueType(0).getSizeInBits() > 128)
3441     return false;
3442
3443   for (unsigned i = 0; i < NumElems/2; ++i)
3444     if (!isUndefOrEqual(N->getMaskElt(i), i))
3445       return false;
3446
3447   for (unsigned i = 0; i < NumElems/2; ++i)
3448     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3449       return false;
3450
3451   return true;
3452 }
3453
3454 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3455 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3456 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3457                          bool HasAVX2, bool V2IsSplat = false) {
3458   unsigned NumElts = VT.getVectorNumElements();
3459
3460   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3461          "Unsupported vector type for unpckh");
3462
3463   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3464       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3465     return false;
3466
3467   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3468   // independently on 128-bit lanes.
3469   unsigned NumLanes = VT.getSizeInBits()/128;
3470   unsigned NumLaneElts = NumElts/NumLanes;
3471
3472   for (unsigned l = 0; l != NumLanes; ++l) {
3473     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3474          i != (l+1)*NumLaneElts;
3475          i += 2, ++j) {
3476       int BitI  = Mask[i];
3477       int BitI1 = Mask[i+1];
3478       if (!isUndefOrEqual(BitI, j))
3479         return false;
3480       if (V2IsSplat) {
3481         if (!isUndefOrEqual(BitI1, NumElts))
3482           return false;
3483       } else {
3484         if (!isUndefOrEqual(BitI1, j + NumElts))
3485           return false;
3486       }
3487     }
3488   }
3489
3490   return true;
3491 }
3492
3493 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3494   return ::isUNPCKLMask(N->getMask(), N->getValueType(0), HasAVX2, V2IsSplat);
3495 }
3496
3497 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3498 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3499 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3500                          bool HasAVX2, bool V2IsSplat = false) {
3501   unsigned NumElts = VT.getVectorNumElements();
3502
3503   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3504          "Unsupported vector type for unpckh");
3505
3506   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3507       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3508     return false;
3509
3510   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3511   // independently on 128-bit lanes.
3512   unsigned NumLanes = VT.getSizeInBits()/128;
3513   unsigned NumLaneElts = NumElts/NumLanes;
3514
3515   for (unsigned l = 0; l != NumLanes; ++l) {
3516     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3517          i != (l+1)*NumLaneElts; i += 2, ++j) {
3518       int BitI  = Mask[i];
3519       int BitI1 = Mask[i+1];
3520       if (!isUndefOrEqual(BitI, j))
3521         return false;
3522       if (V2IsSplat) {
3523         if (isUndefOrEqual(BitI1, NumElts))
3524           return false;
3525       } else {
3526         if (!isUndefOrEqual(BitI1, j+NumElts))
3527           return false;
3528       }
3529     }
3530   }
3531   return true;
3532 }
3533
3534 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3535   return ::isUNPCKHMask(N->getMask(), N->getValueType(0), HasAVX2, V2IsSplat);
3536 }
3537
3538 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3539 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3540 /// <0, 0, 1, 1>
3541 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3542                                   bool HasAVX2) {
3543   unsigned 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       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3550     return false;
3551
3552   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3553   // FIXME: Need a better way to get rid of this, there's no latency difference
3554   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3555   // the former later. We should also remove the "_undef" special mask.
3556   if (NumElts == 4 && VT.getSizeInBits() == 256)
3557     return false;
3558
3559   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3560   // independently on 128-bit lanes.
3561   unsigned NumLanes = VT.getSizeInBits()/128;
3562   unsigned NumLaneElts = NumElts/NumLanes;
3563
3564   for (unsigned l = 0; l != NumLanes; ++l) {
3565     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3566          i != (l+1)*NumLaneElts;
3567          i += 2, ++j) {
3568       int BitI  = Mask[i];
3569       int BitI1 = Mask[i+1];
3570
3571       if (!isUndefOrEqual(BitI, j))
3572         return false;
3573       if (!isUndefOrEqual(BitI1, j))
3574         return false;
3575     }
3576   }
3577
3578   return true;
3579 }
3580
3581 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3582   return ::isUNPCKL_v_undef_Mask(N->getMask(), N->getValueType(0), HasAVX2);
3583 }
3584
3585 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3586 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3587 /// <2, 2, 3, 3>
3588 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3589   unsigned NumElts = VT.getVectorNumElements();
3590
3591   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3592          "Unsupported vector type for unpckh");
3593
3594   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3595       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3596     return false;
3597
3598   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3599   // independently on 128-bit lanes.
3600   unsigned NumLanes = VT.getSizeInBits()/128;
3601   unsigned NumLaneElts = NumElts/NumLanes;
3602
3603   for (unsigned l = 0; l != NumLanes; ++l) {
3604     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3605          i != (l+1)*NumLaneElts; i += 2, ++j) {
3606       int BitI  = Mask[i];
3607       int BitI1 = Mask[i+1];
3608       if (!isUndefOrEqual(BitI, j))
3609         return false;
3610       if (!isUndefOrEqual(BitI1, j))
3611         return false;
3612     }
3613   }
3614   return true;
3615 }
3616
3617 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N, bool HasAVX2) {
3618   return ::isUNPCKH_v_undef_Mask(N->getMask(), N->getValueType(0), HasAVX2);
3619 }
3620
3621 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3622 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3623 /// MOVSD, and MOVD, i.e. setting the lowest element.
3624 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3625   if (VT.getVectorElementType().getSizeInBits() < 32)
3626     return false;
3627   if (VT.getSizeInBits() == 256)
3628     return false;
3629
3630   unsigned NumElts = VT.getVectorNumElements();
3631
3632   if (!isUndefOrEqual(Mask[0], NumElts))
3633     return false;
3634
3635   for (unsigned i = 1; i != NumElts; ++i)
3636     if (!isUndefOrEqual(Mask[i], i))
3637       return false;
3638
3639   return true;
3640 }
3641
3642 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3643   return ::isMOVLMask(N->getMask(), N->getValueType(0));
3644 }
3645
3646 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3647 /// as permutations between 128-bit chunks or halves. As an example: this
3648 /// shuffle bellow:
3649 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3650 /// The first half comes from the second half of V1 and the second half from the
3651 /// the second half of V2.
3652 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3653   if (!HasAVX || VT.getSizeInBits() != 256)
3654     return false;
3655
3656   // The shuffle result is divided into half A and half B. In total the two
3657   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3658   // B must come from C, D, E or F.
3659   unsigned HalfSize = VT.getVectorNumElements()/2;
3660   bool MatchA = false, MatchB = false;
3661
3662   // Check if A comes from one of C, D, E, F.
3663   for (unsigned Half = 0; Half != 4; ++Half) {
3664     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3665       MatchA = true;
3666       break;
3667     }
3668   }
3669
3670   // Check if B comes from one of C, D, E, F.
3671   for (unsigned Half = 0; Half != 4; ++Half) {
3672     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3673       MatchB = true;
3674       break;
3675     }
3676   }
3677
3678   return MatchA && MatchB;
3679 }
3680
3681 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3682 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3683 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3684   EVT VT = SVOp->getValueType(0);
3685
3686   unsigned HalfSize = VT.getVectorNumElements()/2;
3687
3688   unsigned FstHalf = 0, SndHalf = 0;
3689   for (unsigned i = 0; i < HalfSize; ++i) {
3690     if (SVOp->getMaskElt(i) > 0) {
3691       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3692       break;
3693     }
3694   }
3695   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3696     if (SVOp->getMaskElt(i) > 0) {
3697       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3698       break;
3699     }
3700   }
3701
3702   return (FstHalf | (SndHalf << 4));
3703 }
3704
3705 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3706 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3707 /// Note that VPERMIL mask matching is different depending whether theunderlying
3708 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3709 /// to the same elements of the low, but to the higher half of the source.
3710 /// In VPERMILPD the two lanes could be shuffled independently of each other
3711 /// with the same restriction that lanes can't be crossed.
3712 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3713   if (!HasAVX)
3714     return false;
3715
3716   unsigned NumElts = VT.getVectorNumElements();
3717   // Only match 256-bit with 32/64-bit types
3718   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3719     return false;
3720
3721   unsigned NumLanes = VT.getSizeInBits()/128;
3722   unsigned LaneSize = NumElts/NumLanes;
3723   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3724     for (unsigned i = 0; i != LaneSize; ++i) {
3725       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3726         return false;
3727       if (NumElts != 8 || l == 0)
3728         continue;
3729       // VPERMILPS handling
3730       if (Mask[i] < 0)
3731         continue;
3732       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3733         return false;
3734     }
3735   }
3736
3737   return true;
3738 }
3739
3740 /// getShuffleVPERMILPImmediate - Return the appropriate immediate to shuffle
3741 /// the specified VECTOR_MASK mask with VPERMILPS/D* instructions.
3742 static unsigned getShuffleVPERMILPImmediate(ShuffleVectorSDNode *SVOp) {
3743   EVT VT = SVOp->getValueType(0);
3744
3745   unsigned NumElts = VT.getVectorNumElements();
3746   unsigned NumLanes = VT.getSizeInBits()/128;
3747   unsigned LaneSize = NumElts/NumLanes;
3748
3749   // Although the mask is equal for both lanes do it twice to get the cases
3750   // where a mask will match because the same mask element is undef on the
3751   // first half but valid on the second. This would get pathological cases
3752   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3753   unsigned Shift = (LaneSize == 4) ? 2 : 1;
3754   unsigned Mask = 0;
3755   for (unsigned i = 0; i != NumElts; ++i) {
3756     int MaskElt = SVOp->getMaskElt(i);
3757     if (MaskElt < 0)
3758       continue;
3759     MaskElt %= LaneSize;
3760     unsigned Shamt = i;
3761     // VPERMILPSY, the mask of the first half must be equal to the second one
3762     if (NumElts == 8) Shamt %= LaneSize;
3763     Mask |= MaskElt << (Shamt*Shift);
3764   }
3765
3766   return Mask;
3767 }
3768
3769 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3770 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3771 /// element of vector 2 and the other elements to come from vector 1 in order.
3772 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3773                                bool V2IsSplat = false, bool V2IsUndef = false) {
3774   unsigned NumOps = VT.getVectorNumElements();
3775   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3776     return false;
3777
3778   if (!isUndefOrEqual(Mask[0], 0))
3779     return false;
3780
3781   for (unsigned i = 1; i != NumOps; ++i)
3782     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3783           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3784           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3785       return false;
3786
3787   return true;
3788 }
3789
3790 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3791                            bool V2IsUndef = false) {
3792   return isCommutedMOVLMask(N->getMask(), N->getValueType(0),
3793                             V2IsSplat, V2IsUndef);
3794 }
3795
3796 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3797 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3798 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3799 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3800                          const X86Subtarget *Subtarget) {
3801   if (!Subtarget->hasSSE3())
3802     return false;
3803
3804   // The second vector must be undef
3805   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3806     return false;
3807
3808   EVT VT = N->getValueType(0);
3809   unsigned NumElems = VT.getVectorNumElements();
3810
3811   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3812       (VT.getSizeInBits() == 256 && NumElems != 8))
3813     return false;
3814
3815   // "i+1" is the value the indexed mask element must have
3816   for (unsigned i = 0; i < NumElems; i += 2)
3817     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3818         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3819       return false;
3820
3821   return true;
3822 }
3823
3824 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3825 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3826 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3827 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3828                          const X86Subtarget *Subtarget) {
3829   if (!Subtarget->hasSSE3())
3830     return false;
3831
3832   // The second vector must be undef
3833   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3834     return false;
3835
3836   EVT VT = N->getValueType(0);
3837   unsigned NumElems = VT.getVectorNumElements();
3838
3839   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3840       (VT.getSizeInBits() == 256 && NumElems != 8))
3841     return false;
3842
3843   // "i" is the value the indexed mask element must have
3844   for (unsigned i = 0; i != NumElems; i += 2)
3845     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3846         !isUndefOrEqual(N->getMaskElt(i+1), i))
3847       return false;
3848
3849   return true;
3850 }
3851
3852 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3853 /// specifies a shuffle of elements that is suitable for input to 256-bit
3854 /// version of MOVDDUP.
3855 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3856   unsigned NumElts = VT.getVectorNumElements();
3857
3858   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3859     return false;
3860
3861   for (unsigned i = 0; i != NumElts/2; ++i)
3862     if (!isUndefOrEqual(Mask[i], 0))
3863       return false;
3864   for (unsigned i = NumElts/2; i != NumElts; ++i)
3865     if (!isUndefOrEqual(Mask[i], NumElts/2))
3866       return false;
3867   return true;
3868 }
3869
3870 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3871 /// specifies a shuffle of elements that is suitable for input to 128-bit
3872 /// version of MOVDDUP.
3873 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3874   EVT VT = N->getValueType(0);
3875
3876   if (VT.getSizeInBits() != 128)
3877     return false;
3878
3879   unsigned e = VT.getVectorNumElements() / 2;
3880   for (unsigned i = 0; i != e; ++i)
3881     if (!isUndefOrEqual(N->getMaskElt(i), i))
3882       return false;
3883   for (unsigned i = 0; i != e; ++i)
3884     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3885       return false;
3886   return true;
3887 }
3888
3889 /// isVEXTRACTF128Index - Return true if the specified
3890 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3891 /// suitable for input to VEXTRACTF128.
3892 bool X86::isVEXTRACTF128Index(SDNode *N) {
3893   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3894     return false;
3895
3896   // The index should be aligned on a 128-bit boundary.
3897   uint64_t Index =
3898     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3899
3900   unsigned VL = N->getValueType(0).getVectorNumElements();
3901   unsigned VBits = N->getValueType(0).getSizeInBits();
3902   unsigned ElSize = VBits / VL;
3903   bool Result = (Index * ElSize) % 128 == 0;
3904
3905   return Result;
3906 }
3907
3908 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3909 /// operand specifies a subvector insert that is suitable for input to
3910 /// VINSERTF128.
3911 bool X86::isVINSERTF128Index(SDNode *N) {
3912   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3913     return false;
3914
3915   // The index should be aligned on a 128-bit boundary.
3916   uint64_t Index =
3917     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3918
3919   unsigned VL = N->getValueType(0).getVectorNumElements();
3920   unsigned VBits = N->getValueType(0).getSizeInBits();
3921   unsigned ElSize = VBits / VL;
3922   bool Result = (Index * ElSize) % 128 == 0;
3923
3924   return Result;
3925 }
3926
3927 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3928 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3929 /// Handles 128-bit and 256-bit.
3930 unsigned X86::getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3931   EVT VT = N->getValueType(0);
3932
3933   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3934          "Unsupported vector type for PSHUF/SHUFP");
3935
3936   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3937   // independently on 128-bit lanes.
3938   unsigned NumElts = VT.getVectorNumElements();
3939   unsigned NumLanes = VT.getSizeInBits()/128;
3940   unsigned NumLaneElts = NumElts/NumLanes;
3941
3942   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3943          "Only supports 2 or 4 elements per lane");
3944
3945   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3946   unsigned Mask = 0;
3947   for (unsigned i = 0; i != NumElts; ++i) {
3948     int Elt = N->getMaskElt(i);
3949     if (Elt < 0) continue;
3950     Elt %= NumLaneElts;
3951     unsigned ShAmt = i << Shift;
3952     if (ShAmt >= 8) ShAmt -= 8;
3953     Mask |= Elt << ShAmt;
3954   }
3955
3956   return Mask;
3957 }
3958
3959 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3960 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3961 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3962   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3963   unsigned Mask = 0;
3964   // 8 nodes, but we only care about the last 4.
3965   for (unsigned i = 7; i >= 4; --i) {
3966     int Val = SVOp->getMaskElt(i);
3967     if (Val >= 0)
3968       Mask |= (Val - 4);
3969     if (i != 4)
3970       Mask <<= 2;
3971   }
3972   return Mask;
3973 }
3974
3975 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3976 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3977 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3978   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3979   unsigned Mask = 0;
3980   // 8 nodes, but we only care about the first 4.
3981   for (int i = 3; i >= 0; --i) {
3982     int Val = SVOp->getMaskElt(i);
3983     if (Val >= 0)
3984       Mask |= Val;
3985     if (i != 0)
3986       Mask <<= 2;
3987   }
3988   return Mask;
3989 }
3990
3991 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3992 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3993 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3994   EVT VT = SVOp->getValueType(0);
3995   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3996
3997   unsigned NumElts = VT.getVectorNumElements();
3998   unsigned NumLanes = VT.getSizeInBits()/128;
3999   unsigned NumLaneElts = NumElts/NumLanes;
4000
4001   int Val = 0;
4002   unsigned i;
4003   for (i = 0; i != NumElts; ++i) {
4004     Val = SVOp->getMaskElt(i);
4005     if (Val >= 0)
4006       break;
4007   }
4008   if (Val >= (int)NumElts)
4009     Val -= NumElts - NumLaneElts;
4010
4011   assert(Val - i > 0 && "PALIGNR imm should be positive");
4012   return (Val - i) * EltSize;
4013 }
4014
4015 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4016 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4017 /// instructions.
4018 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4019   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4020     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4021
4022   uint64_t Index =
4023     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4024
4025   EVT VecVT = N->getOperand(0).getValueType();
4026   EVT ElVT = VecVT.getVectorElementType();
4027
4028   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4029   return Index / NumElemsPerChunk;
4030 }
4031
4032 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4033 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4034 /// instructions.
4035 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4036   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4037     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4038
4039   uint64_t Index =
4040     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4041
4042   EVT VecVT = N->getValueType(0);
4043   EVT ElVT = VecVT.getVectorElementType();
4044
4045   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4046   return Index / NumElemsPerChunk;
4047 }
4048
4049 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4050 /// constant +0.0.
4051 bool X86::isZeroNode(SDValue Elt) {
4052   return ((isa<ConstantSDNode>(Elt) &&
4053            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4054           (isa<ConstantFPSDNode>(Elt) &&
4055            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4056 }
4057
4058 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4059 /// their permute mask.
4060 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4061                                     SelectionDAG &DAG) {
4062   EVT VT = SVOp->getValueType(0);
4063   unsigned NumElems = VT.getVectorNumElements();
4064   SmallVector<int, 8> MaskVec;
4065
4066   for (unsigned i = 0; i != NumElems; ++i) {
4067     int idx = SVOp->getMaskElt(i);
4068     if (idx < 0)
4069       MaskVec.push_back(idx);
4070     else if (idx < (int)NumElems)
4071       MaskVec.push_back(idx + NumElems);
4072     else
4073       MaskVec.push_back(idx - NumElems);
4074   }
4075   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4076                               SVOp->getOperand(0), &MaskVec[0]);
4077 }
4078
4079 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4080 /// match movhlps. The lower half elements should come from upper half of
4081 /// V1 (and in order), and the upper half elements should come from the upper
4082 /// half of V2 (and in order).
4083 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4084   EVT VT = Op->getValueType(0);
4085   if (VT.getSizeInBits() != 128)
4086     return false;
4087   if (VT.getVectorNumElements() != 4)
4088     return false;
4089   for (unsigned i = 0, e = 2; i != e; ++i)
4090     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4091       return false;
4092   for (unsigned i = 2; i != 4; ++i)
4093     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4094       return false;
4095   return true;
4096 }
4097
4098 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4099 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4100 /// required.
4101 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4102   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4103     return false;
4104   N = N->getOperand(0).getNode();
4105   if (!ISD::isNON_EXTLoad(N))
4106     return false;
4107   if (LD)
4108     *LD = cast<LoadSDNode>(N);
4109   return true;
4110 }
4111
4112 // Test whether the given value is a vector value which will be legalized
4113 // into a load.
4114 static bool WillBeConstantPoolLoad(SDNode *N) {
4115   if (N->getOpcode() != ISD::BUILD_VECTOR)
4116     return false;
4117
4118   // Check for any non-constant elements.
4119   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4120     switch (N->getOperand(i).getNode()->getOpcode()) {
4121     case ISD::UNDEF:
4122     case ISD::ConstantFP:
4123     case ISD::Constant:
4124       break;
4125     default:
4126       return false;
4127     }
4128
4129   // Vectors of all-zeros and all-ones are materialized with special
4130   // instructions rather than being loaded.
4131   return !ISD::isBuildVectorAllZeros(N) &&
4132          !ISD::isBuildVectorAllOnes(N);
4133 }
4134
4135 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4136 /// match movlp{s|d}. The lower half elements should come from lower half of
4137 /// V1 (and in order), and the upper half elements should come from the upper
4138 /// half of V2 (and in order). And since V1 will become the source of the
4139 /// MOVLP, it must be either a vector load or a scalar load to vector.
4140 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4141                                ShuffleVectorSDNode *Op) {
4142   EVT VT = Op->getValueType(0);
4143   if (VT.getSizeInBits() != 128)
4144     return false;
4145
4146   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4147     return false;
4148   // Is V2 is a vector load, don't do this transformation. We will try to use
4149   // load folding shufps op.
4150   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4151     return false;
4152
4153   unsigned NumElems = VT.getVectorNumElements();
4154
4155   if (NumElems != 2 && NumElems != 4)
4156     return false;
4157   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4158     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4159       return false;
4160   for (unsigned i = NumElems/2; i != NumElems; ++i)
4161     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4162       return false;
4163   return true;
4164 }
4165
4166 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4167 /// all the same.
4168 static bool isSplatVector(SDNode *N) {
4169   if (N->getOpcode() != ISD::BUILD_VECTOR)
4170     return false;
4171
4172   SDValue SplatValue = N->getOperand(0);
4173   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4174     if (N->getOperand(i) != SplatValue)
4175       return false;
4176   return true;
4177 }
4178
4179 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4180 /// to an zero vector.
4181 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4182 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4183   SDValue V1 = N->getOperand(0);
4184   SDValue V2 = N->getOperand(1);
4185   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4186   for (unsigned i = 0; i != NumElems; ++i) {
4187     int Idx = N->getMaskElt(i);
4188     if (Idx >= (int)NumElems) {
4189       unsigned Opc = V2.getOpcode();
4190       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4191         continue;
4192       if (Opc != ISD::BUILD_VECTOR ||
4193           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4194         return false;
4195     } else if (Idx >= 0) {
4196       unsigned Opc = V1.getOpcode();
4197       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4198         continue;
4199       if (Opc != ISD::BUILD_VECTOR ||
4200           !X86::isZeroNode(V1.getOperand(Idx)))
4201         return false;
4202     }
4203   }
4204   return true;
4205 }
4206
4207 /// getZeroVector - Returns a vector of specified type with all zero elements.
4208 ///
4209 static SDValue getZeroVector(EVT VT, bool HasSSE2, bool HasAVX2,
4210                              SelectionDAG &DAG, DebugLoc dl) {
4211   assert(VT.isVector() && "Expected a vector type");
4212
4213   // Always build SSE zero vectors as <4 x i32> bitcasted
4214   // to their dest type. This ensures they get CSE'd.
4215   SDValue Vec;
4216   if (VT.getSizeInBits() == 128) {  // SSE
4217     if (HasSSE2) {  // SSE2
4218       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4219       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4220     } else { // SSE1
4221       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4222       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4223     }
4224   } else if (VT.getSizeInBits() == 256) { // AVX
4225     if (HasAVX2) { // AVX2
4226       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4227       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4228       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4229     } else {
4230       // 256-bit logic and arithmetic instructions in AVX are all
4231       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4232       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4233       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4234       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4235     }
4236   }
4237   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4238 }
4239
4240 /// getOnesVector - Returns a vector of specified type with all bits set.
4241 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4242 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4243 /// Then bitcast to their original type, ensuring they get CSE'd.
4244 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4245                              DebugLoc dl) {
4246   assert(VT.isVector() && "Expected a vector type");
4247   assert((VT.is128BitVector() || VT.is256BitVector())
4248          && "Expected a 128-bit or 256-bit vector type");
4249
4250   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4251   SDValue Vec;
4252   if (VT.getSizeInBits() == 256) {
4253     if (HasAVX2) { // AVX2
4254       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4255       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4256     } else { // AVX
4257       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4258       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4259                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4260       Vec = Insert128BitVector(InsV, Vec,
4261                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4262     }
4263   } else {
4264     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4265   }
4266
4267   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4268 }
4269
4270 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4271 /// that point to V2 points to its first element.
4272 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4273   EVT VT = SVOp->getValueType(0);
4274   unsigned NumElems = VT.getVectorNumElements();
4275
4276   bool Changed = false;
4277   SmallVector<int, 8> MaskVec(SVOp->getMask().begin(), SVOp->getMask().end());
4278
4279   for (unsigned i = 0; i != NumElems; ++i) {
4280     if (MaskVec[i] > (int)NumElems) {
4281       MaskVec[i] = NumElems;
4282       Changed = true;
4283     }
4284   }
4285   if (Changed)
4286     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4287                                 SVOp->getOperand(1), &MaskVec[0]);
4288   return SDValue(SVOp, 0);
4289 }
4290
4291 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4292 /// operation of specified width.
4293 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4294                        SDValue V2) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SmallVector<int, 8> Mask;
4297   Mask.push_back(NumElems);
4298   for (unsigned i = 1; i != NumElems; ++i)
4299     Mask.push_back(i);
4300   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4301 }
4302
4303 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4304 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4305                           SDValue V2) {
4306   unsigned NumElems = VT.getVectorNumElements();
4307   SmallVector<int, 8> Mask;
4308   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4309     Mask.push_back(i);
4310     Mask.push_back(i + NumElems);
4311   }
4312   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4313 }
4314
4315 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4316 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4317                           SDValue V2) {
4318   unsigned NumElems = VT.getVectorNumElements();
4319   unsigned Half = NumElems/2;
4320   SmallVector<int, 8> Mask;
4321   for (unsigned i = 0; i != Half; ++i) {
4322     Mask.push_back(i + Half);
4323     Mask.push_back(i + NumElems + Half);
4324   }
4325   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4326 }
4327
4328 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4329 // a generic shuffle instruction because the target has no such instructions.
4330 // Generate shuffles which repeat i16 and i8 several times until they can be
4331 // represented by v4f32 and then be manipulated by target suported shuffles.
4332 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4333   EVT VT = V.getValueType();
4334   int NumElems = VT.getVectorNumElements();
4335   DebugLoc dl = V.getDebugLoc();
4336
4337   while (NumElems > 4) {
4338     if (EltNo < NumElems/2) {
4339       V = getUnpackl(DAG, dl, VT, V, V);
4340     } else {
4341       V = getUnpackh(DAG, dl, VT, V, V);
4342       EltNo -= NumElems/2;
4343     }
4344     NumElems >>= 1;
4345   }
4346   return V;
4347 }
4348
4349 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4350 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4351   EVT VT = V.getValueType();
4352   DebugLoc dl = V.getDebugLoc();
4353   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4354          && "Vector size not supported");
4355
4356   if (VT.getSizeInBits() == 128) {
4357     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4358     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4359     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4360                              &SplatMask[0]);
4361   } else {
4362     // To use VPERMILPS to splat scalars, the second half of indicies must
4363     // refer to the higher part, which is a duplication of the lower one,
4364     // because VPERMILPS can only handle in-lane permutations.
4365     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4366                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4367
4368     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4369     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4370                              &SplatMask[0]);
4371   }
4372
4373   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4374 }
4375
4376 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4377 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4378   EVT SrcVT = SV->getValueType(0);
4379   SDValue V1 = SV->getOperand(0);
4380   DebugLoc dl = SV->getDebugLoc();
4381
4382   int EltNo = SV->getSplatIndex();
4383   int NumElems = SrcVT.getVectorNumElements();
4384   unsigned Size = SrcVT.getSizeInBits();
4385
4386   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4387           "Unknown how to promote splat for type");
4388
4389   // Extract the 128-bit part containing the splat element and update
4390   // the splat element index when it refers to the higher register.
4391   if (Size == 256) {
4392     unsigned Idx = (EltNo >= NumElems/2) ? NumElems/2 : 0;
4393     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4394     if (Idx > 0)
4395       EltNo -= NumElems/2;
4396   }
4397
4398   // All i16 and i8 vector types can't be used directly by a generic shuffle
4399   // instruction because the target has no such instruction. Generate shuffles
4400   // which repeat i16 and i8 several times until they fit in i32, and then can
4401   // be manipulated by target suported shuffles.
4402   EVT EltVT = SrcVT.getVectorElementType();
4403   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4404     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4405
4406   // Recreate the 256-bit vector and place the same 128-bit vector
4407   // into the low and high part. This is necessary because we want
4408   // to use VPERM* to shuffle the vectors
4409   if (Size == 256) {
4410     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4411                          DAG.getConstant(0, MVT::i32), DAG, dl);
4412     V1 = Insert128BitVector(InsV, V1,
4413                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4414   }
4415
4416   return getLegalSplat(DAG, V1, EltNo);
4417 }
4418
4419 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4420 /// vector of zero or undef vector.  This produces a shuffle where the low
4421 /// element of V2 is swizzled into the zero/undef vector, landing at element
4422 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4423 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4424                                            bool IsZero,
4425                                            const X86Subtarget *Subtarget,
4426                                            SelectionDAG &DAG) {
4427   EVT VT = V2.getValueType();
4428   SDValue V1 = IsZero
4429     ? getZeroVector(VT, Subtarget->hasSSE2(), Subtarget->hasAVX2(), DAG,
4430                     V2.getDebugLoc()) : DAG.getUNDEF(VT);
4431   unsigned NumElems = VT.getVectorNumElements();
4432   SmallVector<int, 16> MaskVec;
4433   for (unsigned i = 0; i != NumElems; ++i)
4434     // If this is the insertion idx, put the low elt of V2 here.
4435     MaskVec.push_back(i == Idx ? NumElems : i);
4436   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4437 }
4438
4439 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4440 /// element of the result of the vector shuffle.
4441 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4442                                    unsigned Depth) {
4443   if (Depth == 6)
4444     return SDValue();  // Limit search depth.
4445
4446   SDValue V = SDValue(N, 0);
4447   EVT VT = V.getValueType();
4448   unsigned Opcode = V.getOpcode();
4449
4450   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4451   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4452     Index = SV->getMaskElt(Index);
4453
4454     if (Index < 0)
4455       return DAG.getUNDEF(VT.getVectorElementType());
4456
4457     int NumElems = VT.getVectorNumElements();
4458     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4459     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4460   }
4461
4462   // Recurse into target specific vector shuffles to find scalars.
4463   if (isTargetShuffle(Opcode)) {
4464     int NumElems = VT.getVectorNumElements();
4465     SmallVector<unsigned, 16> ShuffleMask;
4466     SDValue ImmN;
4467
4468     switch(Opcode) {
4469     case X86ISD::SHUFP:
4470       ImmN = N->getOperand(N->getNumOperands()-1);
4471       DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4472                       ShuffleMask);
4473       break;
4474     case X86ISD::UNPCKH:
4475       DecodeUNPCKHMask(VT, ShuffleMask);
4476       break;
4477     case X86ISD::UNPCKL:
4478       DecodeUNPCKLMask(VT, ShuffleMask);
4479       break;
4480     case X86ISD::MOVHLPS:
4481       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4482       break;
4483     case X86ISD::MOVLHPS:
4484       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4485       break;
4486     case X86ISD::PSHUFD:
4487       ImmN = N->getOperand(N->getNumOperands()-1);
4488       DecodePSHUFMask(NumElems,
4489                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4490                       ShuffleMask);
4491       break;
4492     case X86ISD::PSHUFHW:
4493       ImmN = N->getOperand(N->getNumOperands()-1);
4494       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4495                         ShuffleMask);
4496       break;
4497     case X86ISD::PSHUFLW:
4498       ImmN = N->getOperand(N->getNumOperands()-1);
4499       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4500                         ShuffleMask);
4501       break;
4502     case X86ISD::MOVSS:
4503     case X86ISD::MOVSD: {
4504       // The index 0 always comes from the first element of the second source,
4505       // this is why MOVSS and MOVSD are used in the first place. The other
4506       // elements come from the other positions of the first source vector.
4507       unsigned OpNum = (Index == 0) ? 1 : 0;
4508       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4509                                  Depth+1);
4510     }
4511     case X86ISD::VPERMILP:
4512       ImmN = N->getOperand(N->getNumOperands()-1);
4513       DecodeVPERMILPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4514                         ShuffleMask);
4515       break;
4516     case X86ISD::VPERM2X128:
4517       ImmN = N->getOperand(N->getNumOperands()-1);
4518       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4519                            ShuffleMask);
4520       break;
4521     case X86ISD::MOVDDUP:
4522     case X86ISD::MOVLHPD:
4523     case X86ISD::MOVLPD:
4524     case X86ISD::MOVLPS:
4525     case X86ISD::MOVSHDUP:
4526     case X86ISD::MOVSLDUP:
4527     case X86ISD::PALIGN:
4528       return SDValue(); // Not yet implemented.
4529     default:
4530       assert(0 && "unknown target shuffle node");
4531       return SDValue();
4532     }
4533
4534     Index = ShuffleMask[Index];
4535     if (Index < 0)
4536       return DAG.getUNDEF(VT.getVectorElementType());
4537
4538     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4539     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4540                                Depth+1);
4541   }
4542
4543   // Actual nodes that may contain scalar elements
4544   if (Opcode == ISD::BITCAST) {
4545     V = V.getOperand(0);
4546     EVT SrcVT = V.getValueType();
4547     unsigned NumElems = VT.getVectorNumElements();
4548
4549     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4550       return SDValue();
4551   }
4552
4553   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4554     return (Index == 0) ? V.getOperand(0)
4555                           : DAG.getUNDEF(VT.getVectorElementType());
4556
4557   if (V.getOpcode() == ISD::BUILD_VECTOR)
4558     return V.getOperand(Index);
4559
4560   return SDValue();
4561 }
4562
4563 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4564 /// shuffle operation which come from a consecutively from a zero. The
4565 /// search can start in two different directions, from left or right.
4566 static
4567 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4568                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4569   int i = 0;
4570
4571   while (i < NumElems) {
4572     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4573     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4574     if (!(Elt.getNode() &&
4575          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4576       break;
4577     ++i;
4578   }
4579
4580   return i;
4581 }
4582
4583 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4584 /// MaskE correspond consecutively to elements from one of the vector operands,
4585 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4586 static
4587 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4588                               int OpIdx, int NumElems, unsigned &OpNum) {
4589   bool SeenV1 = false;
4590   bool SeenV2 = false;
4591
4592   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4593     int Idx = SVOp->getMaskElt(i);
4594     // Ignore undef indicies
4595     if (Idx < 0)
4596       continue;
4597
4598     if (Idx < NumElems)
4599       SeenV1 = true;
4600     else
4601       SeenV2 = true;
4602
4603     // Only accept consecutive elements from the same vector
4604     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4605       return false;
4606   }
4607
4608   OpNum = SeenV1 ? 0 : 1;
4609   return true;
4610 }
4611
4612 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4613 /// logical left shift of a vector.
4614 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4615                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4616   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4617   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4618               false /* check zeros from right */, DAG);
4619   unsigned OpSrc;
4620
4621   if (!NumZeros)
4622     return false;
4623
4624   // Considering the elements in the mask that are not consecutive zeros,
4625   // check if they consecutively come from only one of the source vectors.
4626   //
4627   //               V1 = {X, A, B, C}     0
4628   //                         \  \  \    /
4629   //   vector_shuffle V1, V2 <1, 2, 3, X>
4630   //
4631   if (!isShuffleMaskConsecutive(SVOp,
4632             0,                   // Mask Start Index
4633             NumElems-NumZeros-1, // Mask End Index
4634             NumZeros,            // Where to start looking in the src vector
4635             NumElems,            // Number of elements in vector
4636             OpSrc))              // Which source operand ?
4637     return false;
4638
4639   isLeft = false;
4640   ShAmt = NumZeros;
4641   ShVal = SVOp->getOperand(OpSrc);
4642   return true;
4643 }
4644
4645 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4646 /// logical left shift of a vector.
4647 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4648                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4649   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4650   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4651               true /* check zeros from left */, DAG);
4652   unsigned OpSrc;
4653
4654   if (!NumZeros)
4655     return false;
4656
4657   // Considering the elements in the mask that are not consecutive zeros,
4658   // check if they consecutively come from only one of the source vectors.
4659   //
4660   //                           0    { A, B, X, X } = V2
4661   //                          / \    /  /
4662   //   vector_shuffle V1, V2 <X, X, 4, 5>
4663   //
4664   if (!isShuffleMaskConsecutive(SVOp,
4665             NumZeros,     // Mask Start Index
4666             NumElems-1,   // Mask End Index
4667             0,            // Where to start looking in the src vector
4668             NumElems,     // Number of elements in vector
4669             OpSrc))       // Which source operand ?
4670     return false;
4671
4672   isLeft = true;
4673   ShAmt = NumZeros;
4674   ShVal = SVOp->getOperand(OpSrc);
4675   return true;
4676 }
4677
4678 /// isVectorShift - Returns true if the shuffle can be implemented as a
4679 /// logical left or right shift of a vector.
4680 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4681                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4682   // Although the logic below support any bitwidth size, there are no
4683   // shift instructions which handle more than 128-bit vectors.
4684   if (SVOp->getValueType(0).getSizeInBits() > 128)
4685     return false;
4686
4687   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4688       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4689     return true;
4690
4691   return false;
4692 }
4693
4694 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4695 ///
4696 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4697                                        unsigned NumNonZero, unsigned NumZero,
4698                                        SelectionDAG &DAG,
4699                                        const TargetLowering &TLI) {
4700   if (NumNonZero > 8)
4701     return SDValue();
4702
4703   DebugLoc dl = Op.getDebugLoc();
4704   SDValue V(0, 0);
4705   bool First = true;
4706   for (unsigned i = 0; i < 16; ++i) {
4707     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4708     if (ThisIsNonZero && First) {
4709       if (NumZero)
4710         V = getZeroVector(MVT::v8i16, /*HasSSE2*/ true, /*HasAVX2*/ false,
4711                           DAG, dl);
4712       else
4713         V = DAG.getUNDEF(MVT::v8i16);
4714       First = false;
4715     }
4716
4717     if ((i & 1) != 0) {
4718       SDValue ThisElt(0, 0), LastElt(0, 0);
4719       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4720       if (LastIsNonZero) {
4721         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4722                               MVT::i16, Op.getOperand(i-1));
4723       }
4724       if (ThisIsNonZero) {
4725         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4726         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4727                               ThisElt, DAG.getConstant(8, MVT::i8));
4728         if (LastIsNonZero)
4729           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4730       } else
4731         ThisElt = LastElt;
4732
4733       if (ThisElt.getNode())
4734         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4735                         DAG.getIntPtrConstant(i/2));
4736     }
4737   }
4738
4739   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4740 }
4741
4742 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4743 ///
4744 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4745                                      unsigned NumNonZero, unsigned NumZero,
4746                                      SelectionDAG &DAG,
4747                                      const TargetLowering &TLI) {
4748   if (NumNonZero > 4)
4749     return SDValue();
4750
4751   DebugLoc dl = Op.getDebugLoc();
4752   SDValue V(0, 0);
4753   bool First = true;
4754   for (unsigned i = 0; i < 8; ++i) {
4755     bool isNonZero = (NonZeros & (1 << i)) != 0;
4756     if (isNonZero) {
4757       if (First) {
4758         if (NumZero)
4759           V = getZeroVector(MVT::v8i16, /*HasSSE2*/ true, /*HasAVX2*/ false,
4760                             DAG, dl);
4761         else
4762           V = DAG.getUNDEF(MVT::v8i16);
4763         First = false;
4764       }
4765       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4766                       MVT::v8i16, V, Op.getOperand(i),
4767                       DAG.getIntPtrConstant(i));
4768     }
4769   }
4770
4771   return V;
4772 }
4773
4774 /// getVShift - Return a vector logical shift node.
4775 ///
4776 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4777                          unsigned NumBits, SelectionDAG &DAG,
4778                          const TargetLowering &TLI, DebugLoc dl) {
4779   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4780   EVT ShVT = MVT::v2i64;
4781   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4782   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4783   return DAG.getNode(ISD::BITCAST, dl, VT,
4784                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4785                              DAG.getConstant(NumBits,
4786                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4787 }
4788
4789 SDValue
4790 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4791                                           SelectionDAG &DAG) const {
4792
4793   // Check if the scalar load can be widened into a vector load. And if
4794   // the address is "base + cst" see if the cst can be "absorbed" into
4795   // the shuffle mask.
4796   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4797     SDValue Ptr = LD->getBasePtr();
4798     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4799       return SDValue();
4800     EVT PVT = LD->getValueType(0);
4801     if (PVT != MVT::i32 && PVT != MVT::f32)
4802       return SDValue();
4803
4804     int FI = -1;
4805     int64_t Offset = 0;
4806     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4807       FI = FINode->getIndex();
4808       Offset = 0;
4809     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4810                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4811       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4812       Offset = Ptr.getConstantOperandVal(1);
4813       Ptr = Ptr.getOperand(0);
4814     } else {
4815       return SDValue();
4816     }
4817
4818     // FIXME: 256-bit vector instructions don't require a strict alignment,
4819     // improve this code to support it better.
4820     unsigned RequiredAlign = VT.getSizeInBits()/8;
4821     SDValue Chain = LD->getChain();
4822     // Make sure the stack object alignment is at least 16 or 32.
4823     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4824     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4825       if (MFI->isFixedObjectIndex(FI)) {
4826         // Can't change the alignment. FIXME: It's possible to compute
4827         // the exact stack offset and reference FI + adjust offset instead.
4828         // If someone *really* cares about this. That's the way to implement it.
4829         return SDValue();
4830       } else {
4831         MFI->setObjectAlignment(FI, RequiredAlign);
4832       }
4833     }
4834
4835     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4836     // Ptr + (Offset & ~15).
4837     if (Offset < 0)
4838       return SDValue();
4839     if ((Offset % RequiredAlign) & 3)
4840       return SDValue();
4841     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4842     if (StartOffset)
4843       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4844                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4845
4846     int EltNo = (Offset - StartOffset) >> 2;
4847     int NumElems = VT.getVectorNumElements();
4848
4849     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4850     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4851     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4852                              LD->getPointerInfo().getWithOffset(StartOffset),
4853                              false, false, false, 0);
4854
4855     // Canonicalize it to a v4i32 or v8i32 shuffle.
4856     SmallVector<int, 8> Mask;
4857     for (int i = 0; i < NumElems; ++i)
4858       Mask.push_back(EltNo);
4859
4860     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4861     return DAG.getNode(ISD::BITCAST, dl, NVT,
4862                        DAG.getVectorShuffle(CanonVT, dl, V1,
4863                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4864   }
4865
4866   return SDValue();
4867 }
4868
4869 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4870 /// vector of type 'VT', see if the elements can be replaced by a single large
4871 /// load which has the same value as a build_vector whose operands are 'elts'.
4872 ///
4873 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4874 ///
4875 /// FIXME: we'd also like to handle the case where the last elements are zero
4876 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4877 /// There's even a handy isZeroNode for that purpose.
4878 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4879                                         DebugLoc &DL, SelectionDAG &DAG) {
4880   EVT EltVT = VT.getVectorElementType();
4881   unsigned NumElems = Elts.size();
4882
4883   LoadSDNode *LDBase = NULL;
4884   unsigned LastLoadedElt = -1U;
4885
4886   // For each element in the initializer, see if we've found a load or an undef.
4887   // If we don't find an initial load element, or later load elements are
4888   // non-consecutive, bail out.
4889   for (unsigned i = 0; i < NumElems; ++i) {
4890     SDValue Elt = Elts[i];
4891
4892     if (!Elt.getNode() ||
4893         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4894       return SDValue();
4895     if (!LDBase) {
4896       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4897         return SDValue();
4898       LDBase = cast<LoadSDNode>(Elt.getNode());
4899       LastLoadedElt = i;
4900       continue;
4901     }
4902     if (Elt.getOpcode() == ISD::UNDEF)
4903       continue;
4904
4905     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4906     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4907       return SDValue();
4908     LastLoadedElt = i;
4909   }
4910
4911   // If we have found an entire vector of loads and undefs, then return a large
4912   // load of the entire vector width starting at the base pointer.  If we found
4913   // consecutive loads for the low half, generate a vzext_load node.
4914   if (LastLoadedElt == NumElems - 1) {
4915     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4916       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4917                          LDBase->getPointerInfo(),
4918                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4919                          LDBase->isInvariant(), 0);
4920     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4921                        LDBase->getPointerInfo(),
4922                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4923                        LDBase->isInvariant(), LDBase->getAlignment());
4924   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4925              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4926     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4927     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4928     SDValue ResNode =
4929         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4930                                 LDBase->getPointerInfo(),
4931                                 LDBase->getAlignment(),
4932                                 false/*isVolatile*/, true/*ReadMem*/,
4933                                 false/*WriteMem*/);
4934     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4935   }
4936   return SDValue();
4937 }
4938
4939 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
4940 /// a vbroadcast node. We support two patterns:
4941 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
4942 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4943 /// a scalar load.
4944 /// The scalar load node is returned when a pattern is found,
4945 /// or SDValue() otherwise.
4946 static SDValue isVectorBroadcast(SDValue &Op, const X86Subtarget *Subtarget) {
4947   if (!Subtarget->hasAVX())
4948     return SDValue();
4949
4950   EVT VT = Op.getValueType();
4951   SDValue V = Op;
4952
4953   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
4954     V = V.getOperand(0);
4955
4956   //A suspected load to be broadcasted.
4957   SDValue Ld;
4958
4959   switch (V.getOpcode()) {
4960     default:
4961       // Unknown pattern found.
4962       return SDValue();
4963
4964     case ISD::BUILD_VECTOR: {
4965       // The BUILD_VECTOR node must be a splat.
4966       if (!isSplatVector(V.getNode()))
4967         return SDValue();
4968
4969       Ld = V.getOperand(0);
4970
4971       // The suspected load node has several users. Make sure that all
4972       // of its users are from the BUILD_VECTOR node.
4973       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4974         return SDValue();
4975       break;
4976     }
4977
4978     case ISD::VECTOR_SHUFFLE: {
4979       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4980
4981       // Shuffles must have a splat mask where the first element is
4982       // broadcasted.
4983       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4984         return SDValue();
4985
4986       SDValue Sc = Op.getOperand(0);
4987       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4988         return SDValue();
4989
4990       Ld = Sc.getOperand(0);
4991
4992       // The scalar_to_vector node and the suspected
4993       // load node must have exactly one user.
4994       if (!Sc.hasOneUse() || !Ld.hasOneUse())
4995         return SDValue();
4996       break;
4997     }
4998   }
4999
5000   // The scalar source must be a normal load.
5001   if (!ISD::isNormalLoad(Ld.getNode()))
5002     return SDValue();
5003
5004   bool Is256 = VT.getSizeInBits() == 256;
5005   bool Is128 = VT.getSizeInBits() == 128;
5006   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5007
5008   // VBroadcast to YMM
5009   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5010     return Ld;
5011
5012   // VBroadcast to XMM
5013   if (Is128 && (ScalarSize == 32))
5014     return Ld;
5015
5016   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5017   // double since there is vbroadcastsd xmm
5018   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5019     // VBroadcast to YMM
5020     if (Is256 && (ScalarSize == 8 || ScalarSize == 16))
5021       return Ld;
5022
5023     // VBroadcast to XMM
5024     if (Is128 && (ScalarSize ==  8 || ScalarSize == 16 || ScalarSize == 64))
5025       return Ld;
5026   }
5027
5028   // Unsupported broadcast.
5029   return SDValue();
5030 }
5031
5032 SDValue
5033 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5034   DebugLoc dl = Op.getDebugLoc();
5035
5036   EVT VT = Op.getValueType();
5037   EVT ExtVT = VT.getVectorElementType();
5038   unsigned NumElems = Op.getNumOperands();
5039
5040   // Vectors containing all zeros can be matched by pxor and xorps later
5041   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5042     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5043     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5044     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5045       return Op;
5046
5047     return getZeroVector(VT, Subtarget->hasSSE2(),
5048                          Subtarget->hasAVX2(), DAG, dl);
5049   }
5050
5051   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5052   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5053   // vpcmpeqd on 256-bit vectors.
5054   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5055     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5056       return Op;
5057
5058     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5059   }
5060
5061   SDValue LD = isVectorBroadcast(Op, Subtarget);
5062   if (LD.getNode())
5063     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5064
5065   unsigned EVTBits = ExtVT.getSizeInBits();
5066
5067   unsigned NumZero  = 0;
5068   unsigned NumNonZero = 0;
5069   unsigned NonZeros = 0;
5070   bool IsAllConstants = true;
5071   SmallSet<SDValue, 8> Values;
5072   for (unsigned i = 0; i < NumElems; ++i) {
5073     SDValue Elt = Op.getOperand(i);
5074     if (Elt.getOpcode() == ISD::UNDEF)
5075       continue;
5076     Values.insert(Elt);
5077     if (Elt.getOpcode() != ISD::Constant &&
5078         Elt.getOpcode() != ISD::ConstantFP)
5079       IsAllConstants = false;
5080     if (X86::isZeroNode(Elt))
5081       NumZero++;
5082     else {
5083       NonZeros |= (1 << i);
5084       NumNonZero++;
5085     }
5086   }
5087
5088   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5089   if (NumNonZero == 0)
5090     return DAG.getUNDEF(VT);
5091
5092   // Special case for single non-zero, non-undef, element.
5093   if (NumNonZero == 1) {
5094     unsigned Idx = CountTrailingZeros_32(NonZeros);
5095     SDValue Item = Op.getOperand(Idx);
5096
5097     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5098     // the value are obviously zero, truncate the value to i32 and do the
5099     // insertion that way.  Only do this if the value is non-constant or if the
5100     // value is a constant being inserted into element 0.  It is cheaper to do
5101     // a constant pool load than it is to do a movd + shuffle.
5102     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5103         (!IsAllConstants || Idx == 0)) {
5104       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5105         // Handle SSE only.
5106         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5107         EVT VecVT = MVT::v4i32;
5108         unsigned VecElts = 4;
5109
5110         // Truncate the value (which may itself be a constant) to i32, and
5111         // convert it to a vector with movd (S2V+shuffle to zero extend).
5112         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5113         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5114         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5115
5116         // Now we have our 32-bit value zero extended in the low element of
5117         // a vector.  If Idx != 0, swizzle it into place.
5118         if (Idx != 0) {
5119           SmallVector<int, 4> Mask;
5120           Mask.push_back(Idx);
5121           for (unsigned i = 1; i != VecElts; ++i)
5122             Mask.push_back(i);
5123           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5124                                       DAG.getUNDEF(Item.getValueType()),
5125                                       &Mask[0]);
5126         }
5127         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5128       }
5129     }
5130
5131     // If we have a constant or non-constant insertion into the low element of
5132     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5133     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5134     // depending on what the source datatype is.
5135     if (Idx == 0) {
5136       if (NumZero == 0)
5137         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5138
5139       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5140           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5141         if (VT.getSizeInBits() == 256) {
5142           SDValue ZeroVec = getZeroVector(VT, Subtarget->hasSSE2(),
5143                                           Subtarget->hasAVX2(), DAG, dl);
5144           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5145                              Item, DAG.getIntPtrConstant(0));
5146         }
5147         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5148         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5149         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5150         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5151       }
5152
5153       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5154         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5155         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5156         if (VT.getSizeInBits() == 256) {
5157           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget->hasSSE2(),
5158                                           Subtarget->hasAVX2(), DAG, dl);
5159           Item = Insert128BitVector(ZeroVec, Item, DAG.getConstant(0, MVT::i32),
5160                                     DAG, dl);
5161         } else {
5162           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5163           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5164         }
5165         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5166       }
5167     }
5168
5169     // Is it a vector logical left shift?
5170     if (NumElems == 2 && Idx == 1 &&
5171         X86::isZeroNode(Op.getOperand(0)) &&
5172         !X86::isZeroNode(Op.getOperand(1))) {
5173       unsigned NumBits = VT.getSizeInBits();
5174       return getVShift(true, VT,
5175                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5176                                    VT, Op.getOperand(1)),
5177                        NumBits/2, DAG, *this, dl);
5178     }
5179
5180     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5181       return SDValue();
5182
5183     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5184     // is a non-constant being inserted into an element other than the low one,
5185     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5186     // movd/movss) to move this into the low element, then shuffle it into
5187     // place.
5188     if (EVTBits == 32) {
5189       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5190
5191       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5192       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5193       SmallVector<int, 8> MaskVec;
5194       for (unsigned i = 0; i < NumElems; i++)
5195         MaskVec.push_back(i == Idx ? 0 : 1);
5196       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5197     }
5198   }
5199
5200   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5201   if (Values.size() == 1) {
5202     if (EVTBits == 32) {
5203       // Instead of a shuffle like this:
5204       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5205       // Check if it's possible to issue this instead.
5206       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5207       unsigned Idx = CountTrailingZeros_32(NonZeros);
5208       SDValue Item = Op.getOperand(Idx);
5209       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5210         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5211     }
5212     return SDValue();
5213   }
5214
5215   // A vector full of immediates; various special cases are already
5216   // handled, so this is best done with a single constant-pool load.
5217   if (IsAllConstants)
5218     return SDValue();
5219
5220   // For AVX-length vectors, build the individual 128-bit pieces and use
5221   // shuffles to put them in place.
5222   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5223     SmallVector<SDValue, 32> V;
5224     for (unsigned i = 0; i < NumElems; ++i)
5225       V.push_back(Op.getOperand(i));
5226
5227     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5228
5229     // Build both the lower and upper subvector.
5230     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5231     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5232                                 NumElems/2);
5233
5234     // Recreate the wider vector with the lower and upper part.
5235     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5236                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5237     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5238                               DAG, dl);
5239   }
5240
5241   // Let legalizer expand 2-wide build_vectors.
5242   if (EVTBits == 64) {
5243     if (NumNonZero == 1) {
5244       // One half is zero or undef.
5245       unsigned Idx = CountTrailingZeros_32(NonZeros);
5246       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5247                                  Op.getOperand(Idx));
5248       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5249     }
5250     return SDValue();
5251   }
5252
5253   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5254   if (EVTBits == 8 && NumElems == 16) {
5255     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5256                                         *this);
5257     if (V.getNode()) return V;
5258   }
5259
5260   if (EVTBits == 16 && NumElems == 8) {
5261     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5262                                       *this);
5263     if (V.getNode()) return V;
5264   }
5265
5266   // If element VT is == 32 bits, turn it into a number of shuffles.
5267   SmallVector<SDValue, 8> V;
5268   V.resize(NumElems);
5269   if (NumElems == 4 && NumZero > 0) {
5270     for (unsigned i = 0; i < 4; ++i) {
5271       bool isZero = !(NonZeros & (1 << i));
5272       if (isZero)
5273         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), Subtarget->hasAVX2(),
5274                              DAG, dl);
5275       else
5276         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5277     }
5278
5279     for (unsigned i = 0; i < 2; ++i) {
5280       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5281         default: break;
5282         case 0:
5283           V[i] = V[i*2];  // Must be a zero vector.
5284           break;
5285         case 1:
5286           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5287           break;
5288         case 2:
5289           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5290           break;
5291         case 3:
5292           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5293           break;
5294       }
5295     }
5296
5297     SmallVector<int, 8> MaskVec;
5298     bool Reverse = (NonZeros & 0x3) == 2;
5299     for (unsigned i = 0; i < 2; ++i)
5300       MaskVec.push_back(Reverse ? 1-i : i);
5301     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5302     for (unsigned i = 0; i < 2; ++i)
5303       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5304     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5305   }
5306
5307   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5308     // Check for a build vector of consecutive loads.
5309     for (unsigned i = 0; i < NumElems; ++i)
5310       V[i] = Op.getOperand(i);
5311
5312     // Check for elements which are consecutive loads.
5313     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5314     if (LD.getNode())
5315       return LD;
5316
5317     // For SSE 4.1, use insertps to put the high elements into the low element.
5318     if (getSubtarget()->hasSSE41()) {
5319       SDValue Result;
5320       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5321         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5322       else
5323         Result = DAG.getUNDEF(VT);
5324
5325       for (unsigned i = 1; i < NumElems; ++i) {
5326         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5327         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5328                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5329       }
5330       return Result;
5331     }
5332
5333     // Otherwise, expand into a number of unpckl*, start by extending each of
5334     // our (non-undef) elements to the full vector width with the element in the
5335     // bottom slot of the vector (which generates no code for SSE).
5336     for (unsigned i = 0; i < NumElems; ++i) {
5337       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5338         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5339       else
5340         V[i] = DAG.getUNDEF(VT);
5341     }
5342
5343     // Next, we iteratively mix elements, e.g. for v4f32:
5344     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5345     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5346     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5347     unsigned EltStride = NumElems >> 1;
5348     while (EltStride != 0) {
5349       for (unsigned i = 0; i < EltStride; ++i) {
5350         // If V[i+EltStride] is undef and this is the first round of mixing,
5351         // then it is safe to just drop this shuffle: V[i] is already in the
5352         // right place, the one element (since it's the first round) being
5353         // inserted as undef can be dropped.  This isn't safe for successive
5354         // rounds because they will permute elements within both vectors.
5355         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5356             EltStride == NumElems/2)
5357           continue;
5358
5359         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5360       }
5361       EltStride >>= 1;
5362     }
5363     return V[0];
5364   }
5365   return SDValue();
5366 }
5367
5368 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5369 // them in a MMX register.  This is better than doing a stack convert.
5370 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5371   DebugLoc dl = Op.getDebugLoc();
5372   EVT ResVT = Op.getValueType();
5373
5374   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5375          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5376   int Mask[2];
5377   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5378   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5379   InVec = Op.getOperand(1);
5380   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5381     unsigned NumElts = ResVT.getVectorNumElements();
5382     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5383     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5384                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5385   } else {
5386     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5387     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5388     Mask[0] = 0; Mask[1] = 2;
5389     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5390   }
5391   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5392 }
5393
5394 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5395 // to create 256-bit vectors from two other 128-bit ones.
5396 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5397   DebugLoc dl = Op.getDebugLoc();
5398   EVT ResVT = Op.getValueType();
5399
5400   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5401
5402   SDValue V1 = Op.getOperand(0);
5403   SDValue V2 = Op.getOperand(1);
5404   unsigned NumElems = ResVT.getVectorNumElements();
5405
5406   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5407                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5408   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5409                             DAG, dl);
5410 }
5411
5412 SDValue
5413 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5414   EVT ResVT = Op.getValueType();
5415
5416   assert(Op.getNumOperands() == 2);
5417   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5418          "Unsupported CONCAT_VECTORS for value type");
5419
5420   // We support concatenate two MMX registers and place them in a MMX register.
5421   // This is better than doing a stack convert.
5422   if (ResVT.is128BitVector())
5423     return LowerMMXCONCAT_VECTORS(Op, DAG);
5424
5425   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5426   // from two other 128-bit ones.
5427   return LowerAVXCONCAT_VECTORS(Op, DAG);
5428 }
5429
5430 // v8i16 shuffles - Prefer shuffles in the following order:
5431 // 1. [all]   pshuflw, pshufhw, optional move
5432 // 2. [ssse3] 1 x pshufb
5433 // 3. [ssse3] 2 x pshufb + 1 x por
5434 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5435 SDValue
5436 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5437                                             SelectionDAG &DAG) const {
5438   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5439   SDValue V1 = SVOp->getOperand(0);
5440   SDValue V2 = SVOp->getOperand(1);
5441   DebugLoc dl = SVOp->getDebugLoc();
5442   SmallVector<int, 8> MaskVals;
5443
5444   // Determine if more than 1 of the words in each of the low and high quadwords
5445   // of the result come from the same quadword of one of the two inputs.  Undef
5446   // mask values count as coming from any quadword, for better codegen.
5447   unsigned LoQuad[] = { 0, 0, 0, 0 };
5448   unsigned HiQuad[] = { 0, 0, 0, 0 };
5449   BitVector InputQuads(4);
5450   for (unsigned i = 0; i < 8; ++i) {
5451     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5452     int EltIdx = SVOp->getMaskElt(i);
5453     MaskVals.push_back(EltIdx);
5454     if (EltIdx < 0) {
5455       ++Quad[0];
5456       ++Quad[1];
5457       ++Quad[2];
5458       ++Quad[3];
5459       continue;
5460     }
5461     ++Quad[EltIdx / 4];
5462     InputQuads.set(EltIdx / 4);
5463   }
5464
5465   int BestLoQuad = -1;
5466   unsigned MaxQuad = 1;
5467   for (unsigned i = 0; i < 4; ++i) {
5468     if (LoQuad[i] > MaxQuad) {
5469       BestLoQuad = i;
5470       MaxQuad = LoQuad[i];
5471     }
5472   }
5473
5474   int BestHiQuad = -1;
5475   MaxQuad = 1;
5476   for (unsigned i = 0; i < 4; ++i) {
5477     if (HiQuad[i] > MaxQuad) {
5478       BestHiQuad = i;
5479       MaxQuad = HiQuad[i];
5480     }
5481   }
5482
5483   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5484   // of the two input vectors, shuffle them into one input vector so only a
5485   // single pshufb instruction is necessary. If There are more than 2 input
5486   // quads, disable the next transformation since it does not help SSSE3.
5487   bool V1Used = InputQuads[0] || InputQuads[1];
5488   bool V2Used = InputQuads[2] || InputQuads[3];
5489   if (Subtarget->hasSSSE3()) {
5490     if (InputQuads.count() == 2 && V1Used && V2Used) {
5491       BestLoQuad = InputQuads.find_first();
5492       BestHiQuad = InputQuads.find_next(BestLoQuad);
5493     }
5494     if (InputQuads.count() > 2) {
5495       BestLoQuad = -1;
5496       BestHiQuad = -1;
5497     }
5498   }
5499
5500   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5501   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5502   // words from all 4 input quadwords.
5503   SDValue NewV;
5504   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5505     SmallVector<int, 8> MaskV;
5506     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5507     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5508     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5509                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5510                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5511     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5512
5513     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5514     // source words for the shuffle, to aid later transformations.
5515     bool AllWordsInNewV = true;
5516     bool InOrder[2] = { true, true };
5517     for (unsigned i = 0; i != 8; ++i) {
5518       int idx = MaskVals[i];
5519       if (idx != (int)i)
5520         InOrder[i/4] = false;
5521       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5522         continue;
5523       AllWordsInNewV = false;
5524       break;
5525     }
5526
5527     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5528     if (AllWordsInNewV) {
5529       for (int i = 0; i != 8; ++i) {
5530         int idx = MaskVals[i];
5531         if (idx < 0)
5532           continue;
5533         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5534         if ((idx != i) && idx < 4)
5535           pshufhw = false;
5536         if ((idx != i) && idx > 3)
5537           pshuflw = false;
5538       }
5539       V1 = NewV;
5540       V2Used = false;
5541       BestLoQuad = 0;
5542       BestHiQuad = 1;
5543     }
5544
5545     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5546     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5547     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5548       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5549       unsigned TargetMask = 0;
5550       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5551                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5552       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5553                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5554       V1 = NewV.getOperand(0);
5555       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5556     }
5557   }
5558
5559   // If we have SSSE3, and all words of the result are from 1 input vector,
5560   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5561   // is present, fall back to case 4.
5562   if (Subtarget->hasSSSE3()) {
5563     SmallVector<SDValue,16> pshufbMask;
5564
5565     // If we have elements from both input vectors, set the high bit of the
5566     // shuffle mask element to zero out elements that come from V2 in the V1
5567     // mask, and elements that come from V1 in the V2 mask, so that the two
5568     // results can be OR'd together.
5569     bool TwoInputs = V1Used && V2Used;
5570     for (unsigned i = 0; i != 8; ++i) {
5571       int EltIdx = MaskVals[i] * 2;
5572       if (TwoInputs && (EltIdx >= 16)) {
5573         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5574         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5575         continue;
5576       }
5577       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5578       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5579     }
5580     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5581     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5582                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5583                                  MVT::v16i8, &pshufbMask[0], 16));
5584     if (!TwoInputs)
5585       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5586
5587     // Calculate the shuffle mask for the second input, shuffle it, and
5588     // OR it with the first shuffled input.
5589     pshufbMask.clear();
5590     for (unsigned i = 0; i != 8; ++i) {
5591       int EltIdx = MaskVals[i] * 2;
5592       if (EltIdx < 16) {
5593         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5594         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5595         continue;
5596       }
5597       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5598       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5599     }
5600     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5601     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5602                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5603                                  MVT::v16i8, &pshufbMask[0], 16));
5604     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5605     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5606   }
5607
5608   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5609   // and update MaskVals with new element order.
5610   BitVector InOrder(8);
5611   if (BestLoQuad >= 0) {
5612     SmallVector<int, 8> MaskV;
5613     for (int i = 0; i != 4; ++i) {
5614       int idx = MaskVals[i];
5615       if (idx < 0) {
5616         MaskV.push_back(-1);
5617         InOrder.set(i);
5618       } else if ((idx / 4) == BestLoQuad) {
5619         MaskV.push_back(idx & 3);
5620         InOrder.set(i);
5621       } else {
5622         MaskV.push_back(-1);
5623       }
5624     }
5625     for (unsigned i = 4; i != 8; ++i)
5626       MaskV.push_back(i);
5627     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5628                                 &MaskV[0]);
5629
5630     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5631       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5632                                NewV.getOperand(0),
5633                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5634                                DAG);
5635   }
5636
5637   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5638   // and update MaskVals with the new element order.
5639   if (BestHiQuad >= 0) {
5640     SmallVector<int, 8> MaskV;
5641     for (unsigned i = 0; i != 4; ++i)
5642       MaskV.push_back(i);
5643     for (unsigned i = 4; i != 8; ++i) {
5644       int idx = MaskVals[i];
5645       if (idx < 0) {
5646         MaskV.push_back(-1);
5647         InOrder.set(i);
5648       } else if ((idx / 4) == BestHiQuad) {
5649         MaskV.push_back((idx & 3) + 4);
5650         InOrder.set(i);
5651       } else {
5652         MaskV.push_back(-1);
5653       }
5654     }
5655     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5656                                 &MaskV[0]);
5657
5658     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
5659       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5660                               NewV.getOperand(0),
5661                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5662                               DAG);
5663   }
5664
5665   // In case BestHi & BestLo were both -1, which means each quadword has a word
5666   // from each of the four input quadwords, calculate the InOrder bitvector now
5667   // before falling through to the insert/extract cleanup.
5668   if (BestLoQuad == -1 && BestHiQuad == -1) {
5669     NewV = V1;
5670     for (int i = 0; i != 8; ++i)
5671       if (MaskVals[i] < 0 || MaskVals[i] == i)
5672         InOrder.set(i);
5673   }
5674
5675   // The other elements are put in the right place using pextrw and pinsrw.
5676   for (unsigned i = 0; i != 8; ++i) {
5677     if (InOrder[i])
5678       continue;
5679     int EltIdx = MaskVals[i];
5680     if (EltIdx < 0)
5681       continue;
5682     SDValue ExtOp = (EltIdx < 8)
5683     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5684                   DAG.getIntPtrConstant(EltIdx))
5685     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5686                   DAG.getIntPtrConstant(EltIdx - 8));
5687     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5688                        DAG.getIntPtrConstant(i));
5689   }
5690   return NewV;
5691 }
5692
5693 // v16i8 shuffles - Prefer shuffles in the following order:
5694 // 1. [ssse3] 1 x pshufb
5695 // 2. [ssse3] 2 x pshufb + 1 x por
5696 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5697 static
5698 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5699                                  SelectionDAG &DAG,
5700                                  const X86TargetLowering &TLI) {
5701   SDValue V1 = SVOp->getOperand(0);
5702   SDValue V2 = SVOp->getOperand(1);
5703   DebugLoc dl = SVOp->getDebugLoc();
5704   ArrayRef<int> MaskVals = SVOp->getMask();
5705
5706   // If we have SSSE3, case 1 is generated when all result bytes come from
5707   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5708   // present, fall back to case 3.
5709   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5710   bool V1Only = true;
5711   bool V2Only = true;
5712   for (unsigned i = 0; i < 16; ++i) {
5713     int EltIdx = MaskVals[i];
5714     if (EltIdx < 0)
5715       continue;
5716     if (EltIdx < 16)
5717       V2Only = false;
5718     else
5719       V1Only = false;
5720   }
5721
5722   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5723   if (TLI.getSubtarget()->hasSSSE3()) {
5724     SmallVector<SDValue,16> pshufbMask;
5725
5726     // If all result elements are from one input vector, then only translate
5727     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5728     //
5729     // Otherwise, we have elements from both input vectors, and must zero out
5730     // elements that come from V2 in the first mask, and V1 in the second mask
5731     // so that we can OR them together.
5732     bool TwoInputs = !(V1Only || V2Only);
5733     for (unsigned i = 0; i != 16; ++i) {
5734       int EltIdx = MaskVals[i];
5735       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5736         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5737         continue;
5738       }
5739       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5740     }
5741     // If all the elements are from V2, assign it to V1 and return after
5742     // building the first pshufb.
5743     if (V2Only)
5744       V1 = V2;
5745     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5746                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5747                                  MVT::v16i8, &pshufbMask[0], 16));
5748     if (!TwoInputs)
5749       return V1;
5750
5751     // Calculate the shuffle mask for the second input, shuffle it, and
5752     // OR it with the first shuffled input.
5753     pshufbMask.clear();
5754     for (unsigned i = 0; i != 16; ++i) {
5755       int EltIdx = MaskVals[i];
5756       if (EltIdx < 16) {
5757         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5758         continue;
5759       }
5760       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5761     }
5762     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5763                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5764                                  MVT::v16i8, &pshufbMask[0], 16));
5765     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5766   }
5767
5768   // No SSSE3 - Calculate in place words and then fix all out of place words
5769   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5770   // the 16 different words that comprise the two doublequadword input vectors.
5771   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5772   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5773   SDValue NewV = V2Only ? V2 : V1;
5774   for (int i = 0; i != 8; ++i) {
5775     int Elt0 = MaskVals[i*2];
5776     int Elt1 = MaskVals[i*2+1];
5777
5778     // This word of the result is all undef, skip it.
5779     if (Elt0 < 0 && Elt1 < 0)
5780       continue;
5781
5782     // This word of the result is already in the correct place, skip it.
5783     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5784       continue;
5785     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5786       continue;
5787
5788     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5789     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5790     SDValue InsElt;
5791
5792     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5793     // using a single extract together, load it and store it.
5794     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5795       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5796                            DAG.getIntPtrConstant(Elt1 / 2));
5797       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5798                         DAG.getIntPtrConstant(i));
5799       continue;
5800     }
5801
5802     // If Elt1 is defined, extract it from the appropriate source.  If the
5803     // source byte is not also odd, shift the extracted word left 8 bits
5804     // otherwise clear the bottom 8 bits if we need to do an or.
5805     if (Elt1 >= 0) {
5806       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5807                            DAG.getIntPtrConstant(Elt1 / 2));
5808       if ((Elt1 & 1) == 0)
5809         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5810                              DAG.getConstant(8,
5811                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5812       else if (Elt0 >= 0)
5813         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5814                              DAG.getConstant(0xFF00, MVT::i16));
5815     }
5816     // If Elt0 is defined, extract it from the appropriate source.  If the
5817     // source byte is not also even, shift the extracted word right 8 bits. If
5818     // Elt1 was also defined, OR the extracted values together before
5819     // inserting them in the result.
5820     if (Elt0 >= 0) {
5821       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5822                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5823       if ((Elt0 & 1) != 0)
5824         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5825                               DAG.getConstant(8,
5826                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5827       else if (Elt1 >= 0)
5828         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5829                              DAG.getConstant(0x00FF, MVT::i16));
5830       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5831                          : InsElt0;
5832     }
5833     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5834                        DAG.getIntPtrConstant(i));
5835   }
5836   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5837 }
5838
5839 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5840 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5841 /// done when every pair / quad of shuffle mask elements point to elements in
5842 /// the right sequence. e.g.
5843 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5844 static
5845 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5846                                  SelectionDAG &DAG, DebugLoc dl) {
5847   EVT VT = SVOp->getValueType(0);
5848   SDValue V1 = SVOp->getOperand(0);
5849   SDValue V2 = SVOp->getOperand(1);
5850   unsigned NumElems = VT.getVectorNumElements();
5851   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5852   EVT NewVT;
5853   switch (VT.getSimpleVT().SimpleTy) {
5854   default: assert(false && "Unexpected!");
5855   case MVT::v4f32: NewVT = MVT::v2f64; break;
5856   case MVT::v4i32: NewVT = MVT::v2i64; break;
5857   case MVT::v8i16: NewVT = MVT::v4i32; break;
5858   case MVT::v16i8: NewVT = MVT::v4i32; break;
5859   }
5860
5861   int Scale = NumElems / NewWidth;
5862   SmallVector<int, 8> MaskVec;
5863   for (unsigned i = 0; i < NumElems; i += Scale) {
5864     int StartIdx = -1;
5865     for (int j = 0; j < Scale; ++j) {
5866       int EltIdx = SVOp->getMaskElt(i+j);
5867       if (EltIdx < 0)
5868         continue;
5869       if (StartIdx == -1)
5870         StartIdx = EltIdx - (EltIdx % Scale);
5871       if (EltIdx != StartIdx + j)
5872         return SDValue();
5873     }
5874     if (StartIdx == -1)
5875       MaskVec.push_back(-1);
5876     else
5877       MaskVec.push_back(StartIdx / Scale);
5878   }
5879
5880   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5881   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5882   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5883 }
5884
5885 /// getVZextMovL - Return a zero-extending vector move low node.
5886 ///
5887 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5888                             SDValue SrcOp, SelectionDAG &DAG,
5889                             const X86Subtarget *Subtarget, DebugLoc dl) {
5890   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5891     LoadSDNode *LD = NULL;
5892     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5893       LD = dyn_cast<LoadSDNode>(SrcOp);
5894     if (!LD) {
5895       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5896       // instead.
5897       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5898       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5899           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5900           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5901           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5902         // PR2108
5903         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5904         return DAG.getNode(ISD::BITCAST, dl, VT,
5905                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5906                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5907                                                    OpVT,
5908                                                    SrcOp.getOperand(0)
5909                                                           .getOperand(0))));
5910       }
5911     }
5912   }
5913
5914   return DAG.getNode(ISD::BITCAST, dl, VT,
5915                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5916                                  DAG.getNode(ISD::BITCAST, dl,
5917                                              OpVT, SrcOp)));
5918 }
5919
5920 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5921 /// which could not be matched by any known target speficic shuffle
5922 static SDValue
5923 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5924   EVT VT = SVOp->getValueType(0);
5925
5926   unsigned NumElems = VT.getVectorNumElements();
5927   unsigned NumLaneElems = NumElems / 2;
5928
5929   int MinRange[2][2] = { { static_cast<int>(NumElems),
5930                            static_cast<int>(NumElems) },
5931                          { static_cast<int>(NumElems),
5932                            static_cast<int>(NumElems) } };
5933   int MaxRange[2][2] = { { -1, -1 }, { -1, -1 } };
5934
5935   // Collect used ranges for each source in each lane
5936   for (unsigned l = 0; l < 2; ++l) {
5937     unsigned LaneStart = l*NumLaneElems;
5938     for (unsigned i = 0; i != NumLaneElems; ++i) {
5939       int Idx = SVOp->getMaskElt(i+LaneStart);
5940       if (Idx < 0)
5941         continue;
5942
5943       int Input = 0;
5944       if (Idx >= (int)NumElems) {
5945         Idx -= NumElems;
5946         Input = 1;
5947       }
5948
5949       if (Idx > MaxRange[l][Input])
5950         MaxRange[l][Input] = Idx;
5951       if (Idx < MinRange[l][Input])
5952         MinRange[l][Input] = Idx;
5953     }
5954   }
5955
5956   // Make sure each range is 128-bits
5957   int ExtractIdx[2][2] = { { -1, -1 }, { -1, -1 } };
5958   for (unsigned l = 0; l < 2; ++l) {
5959     for (unsigned Input = 0; Input < 2; ++Input) {
5960       if (MinRange[l][Input] == (int)NumElems && MaxRange[l][Input] < 0)
5961         continue;
5962
5963       if (MinRange[l][Input] >= 0 && MaxRange[l][Input] < (int)NumLaneElems)
5964         ExtractIdx[l][Input] = 0;
5965       else if (MinRange[l][Input] >= (int)NumLaneElems &&
5966                MaxRange[l][Input] < (int)NumElems)
5967         ExtractIdx[l][Input] = NumLaneElems;
5968       else
5969         return SDValue();
5970     }
5971   }
5972
5973   DebugLoc dl = SVOp->getDebugLoc();
5974   MVT EltVT = VT.getVectorElementType().getSimpleVT();
5975   EVT NVT = MVT::getVectorVT(EltVT, NumElems/2);
5976
5977   SDValue Ops[2][2];
5978   for (unsigned l = 0; l < 2; ++l) {
5979     for (unsigned Input = 0; Input < 2; ++Input) {
5980       if (ExtractIdx[l][Input] >= 0)
5981         Ops[l][Input] = Extract128BitVector(SVOp->getOperand(Input),
5982                                 DAG.getConstant(ExtractIdx[l][Input], MVT::i32),
5983                                                 DAG, dl);
5984       else
5985         Ops[l][Input] = DAG.getUNDEF(NVT);
5986     }
5987   }
5988
5989   // Generate 128-bit shuffles
5990   SmallVector<int, 16> Mask1, Mask2;
5991   for (unsigned i = 0; i != NumLaneElems; ++i) {
5992     int Elt = SVOp->getMaskElt(i);
5993     if (Elt >= (int)NumElems) {
5994       Elt %= NumLaneElems;
5995       Elt += NumLaneElems;
5996     } else if (Elt >= 0) {
5997       Elt %= NumLaneElems;
5998     }
5999     Mask1.push_back(Elt);
6000   }
6001   for (unsigned i = NumLaneElems; i != NumElems; ++i) {
6002     int Elt = SVOp->getMaskElt(i);
6003     if (Elt >= (int)NumElems) {
6004       Elt %= NumLaneElems;
6005       Elt += NumLaneElems;
6006     } else if (Elt >= 0) {
6007       Elt %= NumLaneElems;
6008     }
6009     Mask2.push_back(Elt);
6010   }
6011
6012   SDValue Shuf1 = DAG.getVectorShuffle(NVT, dl, Ops[0][0], Ops[0][1], &Mask1[0]);
6013   SDValue Shuf2 = DAG.getVectorShuffle(NVT, dl, Ops[1][0], Ops[1][1], &Mask2[0]);
6014
6015   // Concatenate the result back
6016   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Shuf1,
6017                                  DAG.getConstant(0, MVT::i32), DAG, dl);
6018   return Insert128BitVector(V, Shuf2, DAG.getConstant(NumElems/2, MVT::i32),
6019                             DAG, dl);
6020 }
6021
6022 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6023 /// 4 elements, and match them with several different shuffle types.
6024 static SDValue
6025 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6026   SDValue V1 = SVOp->getOperand(0);
6027   SDValue V2 = SVOp->getOperand(1);
6028   DebugLoc dl = SVOp->getDebugLoc();
6029   EVT VT = SVOp->getValueType(0);
6030
6031   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6032
6033   SmallVector<std::pair<int, int>, 8> Locs;
6034   Locs.resize(4);
6035   SmallVector<int, 8> Mask1(4U, -1);
6036   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6037
6038   unsigned NumHi = 0;
6039   unsigned NumLo = 0;
6040   for (unsigned i = 0; i != 4; ++i) {
6041     int Idx = PermMask[i];
6042     if (Idx < 0) {
6043       Locs[i] = std::make_pair(-1, -1);
6044     } else {
6045       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6046       if (Idx < 4) {
6047         Locs[i] = std::make_pair(0, NumLo);
6048         Mask1[NumLo] = Idx;
6049         NumLo++;
6050       } else {
6051         Locs[i] = std::make_pair(1, NumHi);
6052         if (2+NumHi < 4)
6053           Mask1[2+NumHi] = Idx;
6054         NumHi++;
6055       }
6056     }
6057   }
6058
6059   if (NumLo <= 2 && NumHi <= 2) {
6060     // If no more than two elements come from either vector. This can be
6061     // implemented with two shuffles. First shuffle gather the elements.
6062     // The second shuffle, which takes the first shuffle as both of its
6063     // vector operands, put the elements into the right order.
6064     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6065
6066     SmallVector<int, 8> Mask2(4U, -1);
6067
6068     for (unsigned i = 0; i != 4; ++i) {
6069       if (Locs[i].first == -1)
6070         continue;
6071       else {
6072         unsigned Idx = (i < 2) ? 0 : 4;
6073         Idx += Locs[i].first * 2 + Locs[i].second;
6074         Mask2[i] = Idx;
6075       }
6076     }
6077
6078     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6079   } else if (NumLo == 3 || NumHi == 3) {
6080     // Otherwise, we must have three elements from one vector, call it X, and
6081     // one element from the other, call it Y.  First, use a shufps to build an
6082     // intermediate vector with the one element from Y and the element from X
6083     // that will be in the same half in the final destination (the indexes don't
6084     // matter). Then, use a shufps to build the final vector, taking the half
6085     // containing the element from Y from the intermediate, and the other half
6086     // from X.
6087     if (NumHi == 3) {
6088       // Normalize it so the 3 elements come from V1.
6089       CommuteVectorShuffleMask(PermMask, 4);
6090       std::swap(V1, V2);
6091     }
6092
6093     // Find the element from V2.
6094     unsigned HiIndex;
6095     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6096       int Val = PermMask[HiIndex];
6097       if (Val < 0)
6098         continue;
6099       if (Val >= 4)
6100         break;
6101     }
6102
6103     Mask1[0] = PermMask[HiIndex];
6104     Mask1[1] = -1;
6105     Mask1[2] = PermMask[HiIndex^1];
6106     Mask1[3] = -1;
6107     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6108
6109     if (HiIndex >= 2) {
6110       Mask1[0] = PermMask[0];
6111       Mask1[1] = PermMask[1];
6112       Mask1[2] = HiIndex & 1 ? 6 : 4;
6113       Mask1[3] = HiIndex & 1 ? 4 : 6;
6114       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6115     } else {
6116       Mask1[0] = HiIndex & 1 ? 2 : 0;
6117       Mask1[1] = HiIndex & 1 ? 0 : 2;
6118       Mask1[2] = PermMask[2];
6119       Mask1[3] = PermMask[3];
6120       if (Mask1[2] >= 0)
6121         Mask1[2] += 4;
6122       if (Mask1[3] >= 0)
6123         Mask1[3] += 4;
6124       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6125     }
6126   }
6127
6128   // Break it into (shuffle shuffle_hi, shuffle_lo).
6129   Locs.clear();
6130   Locs.resize(4);
6131   SmallVector<int,8> LoMask(4U, -1);
6132   SmallVector<int,8> HiMask(4U, -1);
6133
6134   SmallVector<int,8> *MaskPtr = &LoMask;
6135   unsigned MaskIdx = 0;
6136   unsigned LoIdx = 0;
6137   unsigned HiIdx = 2;
6138   for (unsigned i = 0; i != 4; ++i) {
6139     if (i == 2) {
6140       MaskPtr = &HiMask;
6141       MaskIdx = 1;
6142       LoIdx = 0;
6143       HiIdx = 2;
6144     }
6145     int Idx = PermMask[i];
6146     if (Idx < 0) {
6147       Locs[i] = std::make_pair(-1, -1);
6148     } else if (Idx < 4) {
6149       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6150       (*MaskPtr)[LoIdx] = Idx;
6151       LoIdx++;
6152     } else {
6153       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6154       (*MaskPtr)[HiIdx] = Idx;
6155       HiIdx++;
6156     }
6157   }
6158
6159   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6160   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6161   SmallVector<int, 8> MaskOps;
6162   for (unsigned i = 0; i != 4; ++i) {
6163     if (Locs[i].first == -1) {
6164       MaskOps.push_back(-1);
6165     } else {
6166       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6167       MaskOps.push_back(Idx);
6168     }
6169   }
6170   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6171 }
6172
6173 static bool MayFoldVectorLoad(SDValue V) {
6174   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6175     V = V.getOperand(0);
6176   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6177     V = V.getOperand(0);
6178   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6179       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6180     // BUILD_VECTOR (load), undef
6181     V = V.getOperand(0);
6182   if (MayFoldLoad(V))
6183     return true;
6184   return false;
6185 }
6186
6187 // FIXME: the version above should always be used. Since there's
6188 // a bug where several vector shuffles can't be folded because the
6189 // DAG is not updated during lowering and a node claims to have two
6190 // uses while it only has one, use this version, and let isel match
6191 // another instruction if the load really happens to have more than
6192 // one use. Remove this version after this bug get fixed.
6193 // rdar://8434668, PR8156
6194 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6195   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6196     V = V.getOperand(0);
6197   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6198     V = V.getOperand(0);
6199   if (ISD::isNormalLoad(V.getNode()))
6200     return true;
6201   return false;
6202 }
6203
6204 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6205 /// a vector extract, and if both can be later optimized into a single load.
6206 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6207 /// here because otherwise a target specific shuffle node is going to be
6208 /// emitted for this shuffle, and the optimization not done.
6209 /// FIXME: This is probably not the best approach, but fix the problem
6210 /// until the right path is decided.
6211 static
6212 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6213                                          const TargetLowering &TLI) {
6214   EVT VT = V.getValueType();
6215   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6216
6217   // Be sure that the vector shuffle is present in a pattern like this:
6218   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6219   if (!V.hasOneUse())
6220     return false;
6221
6222   SDNode *N = *V.getNode()->use_begin();
6223   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6224     return false;
6225
6226   SDValue EltNo = N->getOperand(1);
6227   if (!isa<ConstantSDNode>(EltNo))
6228     return false;
6229
6230   // If the bit convert changed the number of elements, it is unsafe
6231   // to examine the mask.
6232   bool HasShuffleIntoBitcast = false;
6233   if (V.getOpcode() == ISD::BITCAST) {
6234     EVT SrcVT = V.getOperand(0).getValueType();
6235     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6236       return false;
6237     V = V.getOperand(0);
6238     HasShuffleIntoBitcast = true;
6239   }
6240
6241   // Select the input vector, guarding against out of range extract vector.
6242   unsigned NumElems = VT.getVectorNumElements();
6243   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6244   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6245   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6246
6247   // If we are accessing the upper part of a YMM register
6248   // then the EXTRACT_VECTOR_ELT is likely to be legalized to a sequence of
6249   // EXTRACT_SUBVECTOR + EXTRACT_VECTOR_ELT, which are not detected at this point
6250   // because the legalization of N did not happen yet.
6251   if (Idx >= (int)NumElems/2 && VT.getSizeInBits() == 256)
6252     return false;
6253
6254   // Skip one more bit_convert if necessary
6255   if (V.getOpcode() == ISD::BITCAST)
6256     V = V.getOperand(0);
6257
6258   if (!ISD::isNormalLoad(V.getNode()))
6259     return false;
6260
6261   // Is the original load suitable?
6262   LoadSDNode *LN0 = cast<LoadSDNode>(V);
6263
6264   if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
6265     return false;
6266
6267   if (!HasShuffleIntoBitcast)
6268     return true;
6269
6270   // If there's a bitcast before the shuffle, check if the load type and
6271   // alignment is valid.
6272   unsigned Align = LN0->getAlignment();
6273   unsigned NewAlign =
6274     TLI.getTargetData()->getABITypeAlignment(
6275                                   VT.getTypeForEVT(*DAG.getContext()));
6276
6277   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6278     return false;
6279
6280   return true;
6281 }
6282
6283 static
6284 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6285   EVT VT = Op.getValueType();
6286
6287   // Canonizalize to v2f64.
6288   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6289   return DAG.getNode(ISD::BITCAST, dl, VT,
6290                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6291                                           V1, DAG));
6292 }
6293
6294 static
6295 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6296                         bool HasSSE2) {
6297   SDValue V1 = Op.getOperand(0);
6298   SDValue V2 = Op.getOperand(1);
6299   EVT VT = Op.getValueType();
6300
6301   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6302
6303   if (HasSSE2 && VT == MVT::v2f64)
6304     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6305
6306   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6307   return DAG.getNode(ISD::BITCAST, dl, VT,
6308                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6309                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6310                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6311 }
6312
6313 static
6314 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6315   SDValue V1 = Op.getOperand(0);
6316   SDValue V2 = Op.getOperand(1);
6317   EVT VT = Op.getValueType();
6318
6319   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6320          "unsupported shuffle type");
6321
6322   if (V2.getOpcode() == ISD::UNDEF)
6323     V2 = V1;
6324
6325   // v4i32 or v4f32
6326   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6327 }
6328
6329 static
6330 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6331   SDValue V1 = Op.getOperand(0);
6332   SDValue V2 = Op.getOperand(1);
6333   EVT VT = Op.getValueType();
6334   unsigned NumElems = VT.getVectorNumElements();
6335
6336   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6337   // operand of these instructions is only memory, so check if there's a
6338   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6339   // same masks.
6340   bool CanFoldLoad = false;
6341
6342   // Trivial case, when V2 comes from a load.
6343   if (MayFoldVectorLoad(V2))
6344     CanFoldLoad = true;
6345
6346   // When V1 is a load, it can be folded later into a store in isel, example:
6347   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6348   //    turns into:
6349   //  (MOVLPSmr addr:$src1, VR128:$src2)
6350   // So, recognize this potential and also use MOVLPS or MOVLPD
6351   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6352     CanFoldLoad = true;
6353
6354   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6355   if (CanFoldLoad) {
6356     if (HasSSE2 && NumElems == 2)
6357       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6358
6359     if (NumElems == 4)
6360       // If we don't care about the second element, procede to use movss.
6361       if (SVOp->getMaskElt(1) != -1)
6362         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6363   }
6364
6365   // movl and movlp will both match v2i64, but v2i64 is never matched by
6366   // movl earlier because we make it strict to avoid messing with the movlp load
6367   // folding logic (see the code above getMOVLP call). Match it here then,
6368   // this is horrible, but will stay like this until we move all shuffle
6369   // matching to x86 specific nodes. Note that for the 1st condition all
6370   // types are matched with movsd.
6371   if (HasSSE2) {
6372     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6373     // as to remove this logic from here, as much as possible
6374     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6375       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6376     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6377   }
6378
6379   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6380
6381   // Invert the operand order and use SHUFPS to match it.
6382   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6383                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6384 }
6385
6386 static
6387 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6388                                const TargetLowering &TLI,
6389                                const X86Subtarget *Subtarget) {
6390   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6391   EVT VT = Op.getValueType();
6392   DebugLoc dl = Op.getDebugLoc();
6393   SDValue V1 = Op.getOperand(0);
6394   SDValue V2 = Op.getOperand(1);
6395
6396   if (isZeroShuffle(SVOp))
6397     return getZeroVector(VT, Subtarget->hasSSE2(), Subtarget->hasAVX2(),
6398                          DAG, dl);
6399
6400   // Handle splat operations
6401   if (SVOp->isSplat()) {
6402     unsigned NumElem = VT.getVectorNumElements();
6403     int Size = VT.getSizeInBits();
6404     // Special case, this is the only place now where it's allowed to return
6405     // a vector_shuffle operation without using a target specific node, because
6406     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6407     // this be moved to DAGCombine instead?
6408     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6409       return Op;
6410
6411     // Use vbroadcast whenever the splat comes from a foldable load
6412     SDValue LD = isVectorBroadcast(Op, Subtarget);
6413     if (LD.getNode())
6414       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6415
6416     // Handle splats by matching through known shuffle masks
6417     if ((Size == 128 && NumElem <= 4) ||
6418         (Size == 256 && NumElem < 8))
6419       return SDValue();
6420
6421     // All remaning splats are promoted to target supported vector shuffles.
6422     return PromoteSplat(SVOp, DAG);
6423   }
6424
6425   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6426   // do it!
6427   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6428     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6429     if (NewOp.getNode())
6430       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6431   } else if ((VT == MVT::v4i32 ||
6432              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6433     // FIXME: Figure out a cleaner way to do this.
6434     // Try to make use of movq to zero out the top part.
6435     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6436       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6437       if (NewOp.getNode()) {
6438         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6439           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6440                               DAG, Subtarget, dl);
6441       }
6442     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6443       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6444       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6445         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6446                             DAG, Subtarget, dl);
6447     }
6448   }
6449   return SDValue();
6450 }
6451
6452 SDValue
6453 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6454   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6455   SDValue V1 = Op.getOperand(0);
6456   SDValue V2 = Op.getOperand(1);
6457   EVT VT = Op.getValueType();
6458   DebugLoc dl = Op.getDebugLoc();
6459   unsigned NumElems = VT.getVectorNumElements();
6460   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6461   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6462   bool V1IsSplat = false;
6463   bool V2IsSplat = false;
6464   bool HasSSE2 = Subtarget->hasSSE2();
6465   bool HasAVX    = Subtarget->hasAVX();
6466   bool HasAVX2   = Subtarget->hasAVX2();
6467   MachineFunction &MF = DAG.getMachineFunction();
6468   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6469
6470   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6471
6472   if (V1IsUndef && V2IsUndef)
6473     return DAG.getUNDEF(VT);
6474
6475   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6476
6477   // Vector shuffle lowering takes 3 steps:
6478   //
6479   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6480   //    narrowing and commutation of operands should be handled.
6481   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6482   //    shuffle nodes.
6483   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6484   //    so the shuffle can be broken into other shuffles and the legalizer can
6485   //    try the lowering again.
6486   //
6487   // The general idea is that no vector_shuffle operation should be left to
6488   // be matched during isel, all of them must be converted to a target specific
6489   // node here.
6490
6491   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6492   // narrowing and commutation of operands should be handled. The actual code
6493   // doesn't include all of those, work in progress...
6494   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6495   if (NewOp.getNode())
6496     return NewOp;
6497
6498   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6499   // unpckh_undef). Only use pshufd if speed is more important than size.
6500   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp, HasAVX2))
6501     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6502   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp, HasAVX2))
6503     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6504
6505   if (X86::isMOVDDUPMask(SVOp) && Subtarget->hasSSE3() &&
6506       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6507     return getMOVDDup(Op, dl, V1, DAG);
6508
6509   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6510     return getMOVHighToLow(Op, dl, DAG);
6511
6512   // Use to match splats
6513   if (HasSSE2 && X86::isUNPCKHMask(SVOp, HasAVX2) && V2IsUndef &&
6514       (VT == MVT::v2f64 || VT == MVT::v2i64))
6515     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6516
6517   if (X86::isPSHUFDMask(SVOp)) {
6518     // The actual implementation will match the mask in the if above and then
6519     // during isel it can match several different instructions, not only pshufd
6520     // as its name says, sad but true, emulate the behavior for now...
6521     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6522         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6523
6524     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6525
6526     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6527       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6528
6529     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6530                                 TargetMask, DAG);
6531   }
6532
6533   // Check if this can be converted into a logical shift.
6534   bool isLeft = false;
6535   unsigned ShAmt = 0;
6536   SDValue ShVal;
6537   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6538   if (isShift && ShVal.hasOneUse()) {
6539     // If the shifted value has multiple uses, it may be cheaper to use
6540     // v_set0 + movlhps or movhlps, etc.
6541     EVT EltVT = VT.getVectorElementType();
6542     ShAmt *= EltVT.getSizeInBits();
6543     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6544   }
6545
6546   if (X86::isMOVLMask(SVOp)) {
6547     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6548       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6549     if (!X86::isMOVLPMask(SVOp)) {
6550       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6551         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6552
6553       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6554         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6555     }
6556   }
6557
6558   // FIXME: fold these into legal mask.
6559   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp, HasAVX2))
6560     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6561
6562   if (X86::isMOVHLPSMask(SVOp))
6563     return getMOVHighToLow(Op, dl, DAG);
6564
6565   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6566     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6567
6568   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6569     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6570
6571   if (X86::isMOVLPMask(SVOp))
6572     return getMOVLP(Op, dl, DAG, HasSSE2);
6573
6574   if (ShouldXformToMOVHLPS(SVOp) ||
6575       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6576     return CommuteVectorShuffle(SVOp, DAG);
6577
6578   if (isShift) {
6579     // No better options. Use a vshldq / vsrldq.
6580     EVT EltVT = VT.getVectorElementType();
6581     ShAmt *= EltVT.getSizeInBits();
6582     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6583   }
6584
6585   bool Commuted = false;
6586   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6587   // 1,1,1,1 -> v8i16 though.
6588   V1IsSplat = isSplatVector(V1.getNode());
6589   V2IsSplat = isSplatVector(V2.getNode());
6590
6591   // Canonicalize the splat or undef, if present, to be on the RHS.
6592   if (V1IsSplat && !V2IsSplat) {
6593     Op = CommuteVectorShuffle(SVOp, DAG);
6594     SVOp = cast<ShuffleVectorSDNode>(Op);
6595     V1 = SVOp->getOperand(0);
6596     V2 = SVOp->getOperand(1);
6597     std::swap(V1IsSplat, V2IsSplat);
6598     Commuted = true;
6599   }
6600
6601   ArrayRef<int> M = SVOp->getMask();
6602
6603   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6604     // Shuffling low element of v1 into undef, just return v1.
6605     if (V2IsUndef)
6606       return V1;
6607     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6608     // the instruction selector will not match, so get a canonical MOVL with
6609     // swapped operands to undo the commute.
6610     return getMOVL(DAG, dl, VT, V2, V1);
6611   }
6612
6613   if (isUNPCKLMask(M, VT, HasAVX2))
6614     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6615
6616   if (isUNPCKHMask(M, VT, HasAVX2))
6617     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6618
6619   if (V2IsSplat) {
6620     // Normalize mask so all entries that point to V2 points to its first
6621     // element then try to match unpck{h|l} again. If match, return a
6622     // new vector_shuffle with the corrected mask.
6623     SDValue NewMask = NormalizeMask(SVOp, DAG);
6624     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6625     if (NSVOp != SVOp) {
6626       if (X86::isUNPCKLMask(NSVOp, HasAVX2, true)) {
6627         return NewMask;
6628       } else if (X86::isUNPCKHMask(NSVOp, HasAVX2, true)) {
6629         return NewMask;
6630       }
6631     }
6632   }
6633
6634   if (Commuted) {
6635     // Commute is back and try unpck* again.
6636     // FIXME: this seems wrong.
6637     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6638     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6639
6640     if (X86::isUNPCKLMask(NewSVOp, HasAVX2))
6641       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V2, V1, DAG);
6642
6643     if (X86::isUNPCKHMask(NewSVOp, HasAVX2))
6644       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V2, V1, DAG);
6645   }
6646
6647   // Normalize the node to match x86 shuffle ops if needed
6648   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6649     return CommuteVectorShuffle(SVOp, DAG);
6650
6651   // The checks below are all present in isShuffleMaskLegal, but they are
6652   // inlined here right now to enable us to directly emit target specific
6653   // nodes, and remove one by one until they don't return Op anymore.
6654
6655   if (isPALIGNRMask(M, VT, Subtarget))
6656     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6657                                 getShufflePALIGNRImmediate(SVOp),
6658                                 DAG);
6659
6660   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6661       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6662     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6663       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6664   }
6665
6666   if (isPSHUFHWMask(M, VT))
6667     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6668                                 X86::getShufflePSHUFHWImmediate(SVOp),
6669                                 DAG);
6670
6671   if (isPSHUFLWMask(M, VT))
6672     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6673                                 X86::getShufflePSHUFLWImmediate(SVOp),
6674                                 DAG);
6675
6676   if (isSHUFPMask(M, VT, HasAVX))
6677     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6678                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6679
6680   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6681     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6682   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6683     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6684
6685   //===--------------------------------------------------------------------===//
6686   // Generate target specific nodes for 128 or 256-bit shuffles only
6687   // supported in the AVX instruction set.
6688   //
6689
6690   // Handle VMOVDDUPY permutations
6691   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6692     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6693
6694   // Handle VPERMILPS/D* permutations
6695   if (isVPERMILPMask(M, VT, HasAVX))
6696     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6697                                 getShuffleVPERMILPImmediate(SVOp), DAG);
6698
6699   // Handle VPERM2F128/VPERM2I128 permutations
6700   if (isVPERM2X128Mask(M, VT, HasAVX))
6701     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6702                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6703
6704   //===--------------------------------------------------------------------===//
6705   // Since no target specific shuffle was selected for this generic one,
6706   // lower it into other known shuffles. FIXME: this isn't true yet, but
6707   // this is the plan.
6708   //
6709
6710   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6711   if (VT == MVT::v8i16) {
6712     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6713     if (NewOp.getNode())
6714       return NewOp;
6715   }
6716
6717   if (VT == MVT::v16i8) {
6718     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6719     if (NewOp.getNode())
6720       return NewOp;
6721   }
6722
6723   // Handle all 128-bit wide vectors with 4 elements, and match them with
6724   // several different shuffle types.
6725   if (NumElems == 4 && VT.getSizeInBits() == 128)
6726     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6727
6728   // Handle general 256-bit shuffles
6729   if (VT.is256BitVector())
6730     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6731
6732   return SDValue();
6733 }
6734
6735 SDValue
6736 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6737                                                 SelectionDAG &DAG) const {
6738   EVT VT = Op.getValueType();
6739   DebugLoc dl = Op.getDebugLoc();
6740
6741   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6742     return SDValue();
6743
6744   if (VT.getSizeInBits() == 8) {
6745     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6746                                     Op.getOperand(0), Op.getOperand(1));
6747     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6748                                     DAG.getValueType(VT));
6749     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6750   } else if (VT.getSizeInBits() == 16) {
6751     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6752     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6753     if (Idx == 0)
6754       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6755                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6756                                      DAG.getNode(ISD::BITCAST, dl,
6757                                                  MVT::v4i32,
6758                                                  Op.getOperand(0)),
6759                                      Op.getOperand(1)));
6760     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6761                                     Op.getOperand(0), Op.getOperand(1));
6762     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6763                                     DAG.getValueType(VT));
6764     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6765   } else if (VT == MVT::f32) {
6766     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6767     // the result back to FR32 register. It's only worth matching if the
6768     // result has a single use which is a store or a bitcast to i32.  And in
6769     // the case of a store, it's not worth it if the index is a constant 0,
6770     // because a MOVSSmr can be used instead, which is smaller and faster.
6771     if (!Op.hasOneUse())
6772       return SDValue();
6773     SDNode *User = *Op.getNode()->use_begin();
6774     if ((User->getOpcode() != ISD::STORE ||
6775          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6776           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6777         (User->getOpcode() != ISD::BITCAST ||
6778          User->getValueType(0) != MVT::i32))
6779       return SDValue();
6780     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6781                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6782                                               Op.getOperand(0)),
6783                                               Op.getOperand(1));
6784     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6785   } else if (VT == MVT::i32 || VT == MVT::i64) {
6786     // ExtractPS/pextrq works with constant index.
6787     if (isa<ConstantSDNode>(Op.getOperand(1)))
6788       return Op;
6789   }
6790   return SDValue();
6791 }
6792
6793
6794 SDValue
6795 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6796                                            SelectionDAG &DAG) const {
6797   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6798     return SDValue();
6799
6800   SDValue Vec = Op.getOperand(0);
6801   EVT VecVT = Vec.getValueType();
6802
6803   // If this is a 256-bit vector result, first extract the 128-bit vector and
6804   // then extract the element from the 128-bit vector.
6805   if (VecVT.getSizeInBits() == 256) {
6806     DebugLoc dl = Op.getNode()->getDebugLoc();
6807     unsigned NumElems = VecVT.getVectorNumElements();
6808     SDValue Idx = Op.getOperand(1);
6809     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6810
6811     // Get the 128-bit vector.
6812     bool Upper = IdxVal >= NumElems/2;
6813     Vec = Extract128BitVector(Vec,
6814                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6815
6816     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6817                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6818   }
6819
6820   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6821
6822   if (Subtarget->hasSSE41()) {
6823     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6824     if (Res.getNode())
6825       return Res;
6826   }
6827
6828   EVT VT = Op.getValueType();
6829   DebugLoc dl = Op.getDebugLoc();
6830   // TODO: handle v16i8.
6831   if (VT.getSizeInBits() == 16) {
6832     SDValue Vec = Op.getOperand(0);
6833     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6834     if (Idx == 0)
6835       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6836                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6837                                      DAG.getNode(ISD::BITCAST, dl,
6838                                                  MVT::v4i32, Vec),
6839                                      Op.getOperand(1)));
6840     // Transform it so it match pextrw which produces a 32-bit result.
6841     EVT EltVT = MVT::i32;
6842     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6843                                     Op.getOperand(0), Op.getOperand(1));
6844     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6845                                     DAG.getValueType(VT));
6846     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6847   } else if (VT.getSizeInBits() == 32) {
6848     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6849     if (Idx == 0)
6850       return Op;
6851
6852     // SHUFPS the element to the lowest double word, then movss.
6853     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6854     EVT VVT = Op.getOperand(0).getValueType();
6855     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6856                                        DAG.getUNDEF(VVT), Mask);
6857     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6858                        DAG.getIntPtrConstant(0));
6859   } else if (VT.getSizeInBits() == 64) {
6860     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6861     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6862     //        to match extract_elt for f64.
6863     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6864     if (Idx == 0)
6865       return Op;
6866
6867     // UNPCKHPD the element to the lowest double word, then movsd.
6868     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6869     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6870     int Mask[2] = { 1, -1 };
6871     EVT VVT = Op.getOperand(0).getValueType();
6872     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6873                                        DAG.getUNDEF(VVT), Mask);
6874     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6875                        DAG.getIntPtrConstant(0));
6876   }
6877
6878   return SDValue();
6879 }
6880
6881 SDValue
6882 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6883                                                SelectionDAG &DAG) const {
6884   EVT VT = Op.getValueType();
6885   EVT EltVT = VT.getVectorElementType();
6886   DebugLoc dl = Op.getDebugLoc();
6887
6888   SDValue N0 = Op.getOperand(0);
6889   SDValue N1 = Op.getOperand(1);
6890   SDValue N2 = Op.getOperand(2);
6891
6892   if (VT.getSizeInBits() == 256)
6893     return SDValue();
6894
6895   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6896       isa<ConstantSDNode>(N2)) {
6897     unsigned Opc;
6898     if (VT == MVT::v8i16)
6899       Opc = X86ISD::PINSRW;
6900     else if (VT == MVT::v16i8)
6901       Opc = X86ISD::PINSRB;
6902     else
6903       Opc = X86ISD::PINSRB;
6904
6905     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6906     // argument.
6907     if (N1.getValueType() != MVT::i32)
6908       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6909     if (N2.getValueType() != MVT::i32)
6910       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6911     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6912   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6913     // Bits [7:6] of the constant are the source select.  This will always be
6914     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6915     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6916     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6917     // Bits [5:4] of the constant are the destination select.  This is the
6918     //  value of the incoming immediate.
6919     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6920     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6921     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6922     // Create this as a scalar to vector..
6923     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6924     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6925   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
6926              isa<ConstantSDNode>(N2)) {
6927     // PINSR* works with constant index.
6928     return Op;
6929   }
6930   return SDValue();
6931 }
6932
6933 SDValue
6934 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6935   EVT VT = Op.getValueType();
6936   EVT EltVT = VT.getVectorElementType();
6937
6938   DebugLoc dl = Op.getDebugLoc();
6939   SDValue N0 = Op.getOperand(0);
6940   SDValue N1 = Op.getOperand(1);
6941   SDValue N2 = Op.getOperand(2);
6942
6943   // If this is a 256-bit vector result, first extract the 128-bit vector,
6944   // insert the element into the extracted half and then place it back.
6945   if (VT.getSizeInBits() == 256) {
6946     if (!isa<ConstantSDNode>(N2))
6947       return SDValue();
6948
6949     // Get the desired 128-bit vector half.
6950     unsigned NumElems = VT.getVectorNumElements();
6951     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6952     bool Upper = IdxVal >= NumElems/2;
6953     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
6954     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6955
6956     // Insert the element into the desired half.
6957     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6958                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6959
6960     // Insert the changed part back to the 256-bit vector
6961     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6962   }
6963
6964   if (Subtarget->hasSSE41())
6965     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6966
6967   if (EltVT == MVT::i8)
6968     return SDValue();
6969
6970   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6971     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6972     // as its second argument.
6973     if (N1.getValueType() != MVT::i32)
6974       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6975     if (N2.getValueType() != MVT::i32)
6976       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6977     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6978   }
6979   return SDValue();
6980 }
6981
6982 SDValue
6983 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6984   LLVMContext *Context = DAG.getContext();
6985   DebugLoc dl = Op.getDebugLoc();
6986   EVT OpVT = Op.getValueType();
6987
6988   // If this is a 256-bit vector result, first insert into a 128-bit
6989   // vector and then insert into the 256-bit vector.
6990   if (OpVT.getSizeInBits() > 128) {
6991     // Insert into a 128-bit vector.
6992     EVT VT128 = EVT::getVectorVT(*Context,
6993                                  OpVT.getVectorElementType(),
6994                                  OpVT.getVectorNumElements() / 2);
6995
6996     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6997
6998     // Insert the 128-bit vector.
6999     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7000                               DAG.getConstant(0, MVT::i32),
7001                               DAG, dl);
7002   }
7003
7004   if (Op.getValueType() == MVT::v1i64 &&
7005       Op.getOperand(0).getValueType() == MVT::i64)
7006     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7007
7008   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7009   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7010          "Expected an SSE type!");
7011   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7012                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7013 }
7014
7015 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7016 // a simple subregister reference or explicit instructions to grab
7017 // upper bits of a vector.
7018 SDValue
7019 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7020   if (Subtarget->hasAVX()) {
7021     DebugLoc dl = Op.getNode()->getDebugLoc();
7022     SDValue Vec = Op.getNode()->getOperand(0);
7023     SDValue Idx = Op.getNode()->getOperand(1);
7024
7025     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7026         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7027         return Extract128BitVector(Vec, Idx, DAG, dl);
7028     }
7029   }
7030   return SDValue();
7031 }
7032
7033 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7034 // simple superregister reference or explicit instructions to insert
7035 // the upper bits of a vector.
7036 SDValue
7037 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7038   if (Subtarget->hasAVX()) {
7039     DebugLoc dl = Op.getNode()->getDebugLoc();
7040     SDValue Vec = Op.getNode()->getOperand(0);
7041     SDValue SubVec = Op.getNode()->getOperand(1);
7042     SDValue Idx = Op.getNode()->getOperand(2);
7043
7044     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7045         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7046       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7047     }
7048   }
7049   return SDValue();
7050 }
7051
7052 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7053 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7054 // one of the above mentioned nodes. It has to be wrapped because otherwise
7055 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7056 // be used to form addressing mode. These wrapped nodes will be selected
7057 // into MOV32ri.
7058 SDValue
7059 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7060   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7061
7062   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7063   // global base reg.
7064   unsigned char OpFlag = 0;
7065   unsigned WrapperKind = X86ISD::Wrapper;
7066   CodeModel::Model M = getTargetMachine().getCodeModel();
7067
7068   if (Subtarget->isPICStyleRIPRel() &&
7069       (M == CodeModel::Small || M == CodeModel::Kernel))
7070     WrapperKind = X86ISD::WrapperRIP;
7071   else if (Subtarget->isPICStyleGOT())
7072     OpFlag = X86II::MO_GOTOFF;
7073   else if (Subtarget->isPICStyleStubPIC())
7074     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7075
7076   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7077                                              CP->getAlignment(),
7078                                              CP->getOffset(), OpFlag);
7079   DebugLoc DL = CP->getDebugLoc();
7080   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7081   // With PIC, the address is actually $g + Offset.
7082   if (OpFlag) {
7083     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7084                          DAG.getNode(X86ISD::GlobalBaseReg,
7085                                      DebugLoc(), getPointerTy()),
7086                          Result);
7087   }
7088
7089   return Result;
7090 }
7091
7092 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7093   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7094
7095   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7096   // global base reg.
7097   unsigned char OpFlag = 0;
7098   unsigned WrapperKind = X86ISD::Wrapper;
7099   CodeModel::Model M = getTargetMachine().getCodeModel();
7100
7101   if (Subtarget->isPICStyleRIPRel() &&
7102       (M == CodeModel::Small || M == CodeModel::Kernel))
7103     WrapperKind = X86ISD::WrapperRIP;
7104   else if (Subtarget->isPICStyleGOT())
7105     OpFlag = X86II::MO_GOTOFF;
7106   else if (Subtarget->isPICStyleStubPIC())
7107     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7108
7109   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7110                                           OpFlag);
7111   DebugLoc DL = JT->getDebugLoc();
7112   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7113
7114   // With PIC, the address is actually $g + Offset.
7115   if (OpFlag)
7116     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7117                          DAG.getNode(X86ISD::GlobalBaseReg,
7118                                      DebugLoc(), getPointerTy()),
7119                          Result);
7120
7121   return Result;
7122 }
7123
7124 SDValue
7125 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7126   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7127
7128   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7129   // global base reg.
7130   unsigned char OpFlag = 0;
7131   unsigned WrapperKind = X86ISD::Wrapper;
7132   CodeModel::Model M = getTargetMachine().getCodeModel();
7133
7134   if (Subtarget->isPICStyleRIPRel() &&
7135       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7136     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7137       OpFlag = X86II::MO_GOTPCREL;
7138     WrapperKind = X86ISD::WrapperRIP;
7139   } else if (Subtarget->isPICStyleGOT()) {
7140     OpFlag = X86II::MO_GOT;
7141   } else if (Subtarget->isPICStyleStubPIC()) {
7142     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7143   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7144     OpFlag = X86II::MO_DARWIN_NONLAZY;
7145   }
7146
7147   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7148
7149   DebugLoc DL = Op.getDebugLoc();
7150   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7151
7152
7153   // With PIC, the address is actually $g + Offset.
7154   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7155       !Subtarget->is64Bit()) {
7156     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7157                          DAG.getNode(X86ISD::GlobalBaseReg,
7158                                      DebugLoc(), getPointerTy()),
7159                          Result);
7160   }
7161
7162   // For symbols that require a load from a stub to get the address, emit the
7163   // load.
7164   if (isGlobalStubReference(OpFlag))
7165     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7166                          MachinePointerInfo::getGOT(), false, false, false, 0);
7167
7168   return Result;
7169 }
7170
7171 SDValue
7172 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7173   // Create the TargetBlockAddressAddress node.
7174   unsigned char OpFlags =
7175     Subtarget->ClassifyBlockAddressReference();
7176   CodeModel::Model M = getTargetMachine().getCodeModel();
7177   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7178   DebugLoc dl = Op.getDebugLoc();
7179   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7180                                        /*isTarget=*/true, OpFlags);
7181
7182   if (Subtarget->isPICStyleRIPRel() &&
7183       (M == CodeModel::Small || M == CodeModel::Kernel))
7184     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7185   else
7186     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7187
7188   // With PIC, the address is actually $g + Offset.
7189   if (isGlobalRelativeToPICBase(OpFlags)) {
7190     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7191                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7192                          Result);
7193   }
7194
7195   return Result;
7196 }
7197
7198 SDValue
7199 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7200                                       int64_t Offset,
7201                                       SelectionDAG &DAG) const {
7202   // Create the TargetGlobalAddress node, folding in the constant
7203   // offset if it is legal.
7204   unsigned char OpFlags =
7205     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7206   CodeModel::Model M = getTargetMachine().getCodeModel();
7207   SDValue Result;
7208   if (OpFlags == X86II::MO_NO_FLAG &&
7209       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7210     // A direct static reference to a global.
7211     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7212     Offset = 0;
7213   } else {
7214     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7215   }
7216
7217   if (Subtarget->isPICStyleRIPRel() &&
7218       (M == CodeModel::Small || M == CodeModel::Kernel))
7219     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7220   else
7221     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7222
7223   // With PIC, the address is actually $g + Offset.
7224   if (isGlobalRelativeToPICBase(OpFlags)) {
7225     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7226                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7227                          Result);
7228   }
7229
7230   // For globals that require a load from a stub to get the address, emit the
7231   // load.
7232   if (isGlobalStubReference(OpFlags))
7233     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7234                          MachinePointerInfo::getGOT(), false, false, false, 0);
7235
7236   // If there was a non-zero offset that we didn't fold, create an explicit
7237   // addition for it.
7238   if (Offset != 0)
7239     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7240                          DAG.getConstant(Offset, getPointerTy()));
7241
7242   return Result;
7243 }
7244
7245 SDValue
7246 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7247   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7248   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7249   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7250 }
7251
7252 static SDValue
7253 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7254            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7255            unsigned char OperandFlags) {
7256   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7257   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7258   DebugLoc dl = GA->getDebugLoc();
7259   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7260                                            GA->getValueType(0),
7261                                            GA->getOffset(),
7262                                            OperandFlags);
7263   if (InFlag) {
7264     SDValue Ops[] = { Chain,  TGA, *InFlag };
7265     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7266   } else {
7267     SDValue Ops[]  = { Chain, TGA };
7268     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7269   }
7270
7271   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7272   MFI->setAdjustsStack(true);
7273
7274   SDValue Flag = Chain.getValue(1);
7275   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7276 }
7277
7278 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7279 static SDValue
7280 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7281                                 const EVT PtrVT) {
7282   SDValue InFlag;
7283   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7284   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7285                                      DAG.getNode(X86ISD::GlobalBaseReg,
7286                                                  DebugLoc(), PtrVT), InFlag);
7287   InFlag = Chain.getValue(1);
7288
7289   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7290 }
7291
7292 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7293 static SDValue
7294 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7295                                 const EVT PtrVT) {
7296   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7297                     X86::RAX, X86II::MO_TLSGD);
7298 }
7299
7300 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7301 // "local exec" model.
7302 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7303                                    const EVT PtrVT, TLSModel::Model model,
7304                                    bool is64Bit) {
7305   DebugLoc dl = GA->getDebugLoc();
7306
7307   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7308   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7309                                                          is64Bit ? 257 : 256));
7310
7311   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7312                                       DAG.getIntPtrConstant(0),
7313                                       MachinePointerInfo(Ptr),
7314                                       false, false, false, 0);
7315
7316   unsigned char OperandFlags = 0;
7317   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7318   // initialexec.
7319   unsigned WrapperKind = X86ISD::Wrapper;
7320   if (model == TLSModel::LocalExec) {
7321     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7322   } else if (is64Bit) {
7323     assert(model == TLSModel::InitialExec);
7324     OperandFlags = X86II::MO_GOTTPOFF;
7325     WrapperKind = X86ISD::WrapperRIP;
7326   } else {
7327     assert(model == TLSModel::InitialExec);
7328     OperandFlags = X86II::MO_INDNTPOFF;
7329   }
7330
7331   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7332   // exec)
7333   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7334                                            GA->getValueType(0),
7335                                            GA->getOffset(), OperandFlags);
7336   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7337
7338   if (model == TLSModel::InitialExec)
7339     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7340                          MachinePointerInfo::getGOT(), false, false, false, 0);
7341
7342   // The address of the thread local variable is the add of the thread
7343   // pointer with the offset of the variable.
7344   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7345 }
7346
7347 SDValue
7348 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7349
7350   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7351   const GlobalValue *GV = GA->getGlobal();
7352
7353   if (Subtarget->isTargetELF()) {
7354     // TODO: implement the "local dynamic" model
7355     // TODO: implement the "initial exec"model for pic executables
7356
7357     // If GV is an alias then use the aliasee for determining
7358     // thread-localness.
7359     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7360       GV = GA->resolveAliasedGlobal(false);
7361
7362     TLSModel::Model model
7363       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7364
7365     switch (model) {
7366       case TLSModel::GeneralDynamic:
7367       case TLSModel::LocalDynamic: // not implemented
7368         if (Subtarget->is64Bit())
7369           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7370         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7371
7372       case TLSModel::InitialExec:
7373       case TLSModel::LocalExec:
7374         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7375                                    Subtarget->is64Bit());
7376     }
7377   } else if (Subtarget->isTargetDarwin()) {
7378     // Darwin only has one model of TLS.  Lower to that.
7379     unsigned char OpFlag = 0;
7380     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7381                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7382
7383     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7384     // global base reg.
7385     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7386                   !Subtarget->is64Bit();
7387     if (PIC32)
7388       OpFlag = X86II::MO_TLVP_PIC_BASE;
7389     else
7390       OpFlag = X86II::MO_TLVP;
7391     DebugLoc DL = Op.getDebugLoc();
7392     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7393                                                 GA->getValueType(0),
7394                                                 GA->getOffset(), OpFlag);
7395     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7396
7397     // With PIC32, the address is actually $g + Offset.
7398     if (PIC32)
7399       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7400                            DAG.getNode(X86ISD::GlobalBaseReg,
7401                                        DebugLoc(), getPointerTy()),
7402                            Offset);
7403
7404     // Lowering the machine isd will make sure everything is in the right
7405     // location.
7406     SDValue Chain = DAG.getEntryNode();
7407     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7408     SDValue Args[] = { Chain, Offset };
7409     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7410
7411     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7412     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7413     MFI->setAdjustsStack(true);
7414
7415     // And our return value (tls address) is in the standard call return value
7416     // location.
7417     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7418     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7419                               Chain.getValue(1));
7420   }
7421
7422   llvm_unreachable("TLS not implemented for this target.");
7423 }
7424
7425
7426 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7427 /// and take a 2 x i32 value to shift plus a shift amount.
7428 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7429   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7430   EVT VT = Op.getValueType();
7431   unsigned VTBits = VT.getSizeInBits();
7432   DebugLoc dl = Op.getDebugLoc();
7433   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7434   SDValue ShOpLo = Op.getOperand(0);
7435   SDValue ShOpHi = Op.getOperand(1);
7436   SDValue ShAmt  = Op.getOperand(2);
7437   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7438                                      DAG.getConstant(VTBits - 1, MVT::i8))
7439                        : DAG.getConstant(0, VT);
7440
7441   SDValue Tmp2, Tmp3;
7442   if (Op.getOpcode() == ISD::SHL_PARTS) {
7443     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7444     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7445   } else {
7446     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7447     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7448   }
7449
7450   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7451                                 DAG.getConstant(VTBits, MVT::i8));
7452   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7453                              AndNode, DAG.getConstant(0, MVT::i8));
7454
7455   SDValue Hi, Lo;
7456   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7457   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7458   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7459
7460   if (Op.getOpcode() == ISD::SHL_PARTS) {
7461     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7462     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7463   } else {
7464     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7465     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7466   }
7467
7468   SDValue Ops[2] = { Lo, Hi };
7469   return DAG.getMergeValues(Ops, 2, dl);
7470 }
7471
7472 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7473                                            SelectionDAG &DAG) const {
7474   EVT SrcVT = Op.getOperand(0).getValueType();
7475
7476   if (SrcVT.isVector())
7477     return SDValue();
7478
7479   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7480          "Unknown SINT_TO_FP to lower!");
7481
7482   // These are really Legal; return the operand so the caller accepts it as
7483   // Legal.
7484   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7485     return Op;
7486   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7487       Subtarget->is64Bit()) {
7488     return Op;
7489   }
7490
7491   DebugLoc dl = Op.getDebugLoc();
7492   unsigned Size = SrcVT.getSizeInBits()/8;
7493   MachineFunction &MF = DAG.getMachineFunction();
7494   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7495   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7496   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7497                                StackSlot,
7498                                MachinePointerInfo::getFixedStack(SSFI),
7499                                false, false, 0);
7500   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7501 }
7502
7503 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7504                                      SDValue StackSlot,
7505                                      SelectionDAG &DAG) const {
7506   // Build the FILD
7507   DebugLoc DL = Op.getDebugLoc();
7508   SDVTList Tys;
7509   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7510   if (useSSE)
7511     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7512   else
7513     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7514
7515   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7516
7517   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7518   MachineMemOperand *MMO;
7519   if (FI) {
7520     int SSFI = FI->getIndex();
7521     MMO =
7522       DAG.getMachineFunction()
7523       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7524                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7525   } else {
7526     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7527     StackSlot = StackSlot.getOperand(1);
7528   }
7529   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7530   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7531                                            X86ISD::FILD, DL,
7532                                            Tys, Ops, array_lengthof(Ops),
7533                                            SrcVT, MMO);
7534
7535   if (useSSE) {
7536     Chain = Result.getValue(1);
7537     SDValue InFlag = Result.getValue(2);
7538
7539     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7540     // shouldn't be necessary except that RFP cannot be live across
7541     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7542     MachineFunction &MF = DAG.getMachineFunction();
7543     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7544     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7545     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7546     Tys = DAG.getVTList(MVT::Other);
7547     SDValue Ops[] = {
7548       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7549     };
7550     MachineMemOperand *MMO =
7551       DAG.getMachineFunction()
7552       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7553                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7554
7555     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7556                                     Ops, array_lengthof(Ops),
7557                                     Op.getValueType(), MMO);
7558     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7559                          MachinePointerInfo::getFixedStack(SSFI),
7560                          false, false, false, 0);
7561   }
7562
7563   return Result;
7564 }
7565
7566 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7567 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7568                                                SelectionDAG &DAG) const {
7569   // This algorithm is not obvious. Here it is what we're trying to output:
7570   /*
7571      movq       %rax,  %xmm0
7572      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7573      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7574      #ifdef __SSE3__
7575        haddpd   %xmm0, %xmm0          
7576      #else
7577        pshufd   $0x4e, %xmm0, %xmm1 
7578        addpd    %xmm1, %xmm0
7579      #endif
7580   */
7581
7582   DebugLoc dl = Op.getDebugLoc();
7583   LLVMContext *Context = DAG.getContext();
7584
7585   // Build some magic constants.
7586   SmallVector<Constant*,4> CV0;
7587   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7588   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7589   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7590   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7591   Constant *C0 = ConstantVector::get(CV0);
7592   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7593
7594   SmallVector<Constant*,2> CV1;
7595   CV1.push_back(
7596         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7597   CV1.push_back(
7598         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7599   Constant *C1 = ConstantVector::get(CV1);
7600   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7601
7602   // Load the 64-bit value into an XMM register.
7603   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7604                             Op.getOperand(0));
7605   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7606                               MachinePointerInfo::getConstantPool(),
7607                               false, false, false, 16);
7608   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7609                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7610                               CLod0);
7611
7612   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7613                               MachinePointerInfo::getConstantPool(),
7614                               false, false, false, 16);
7615   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7616   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7617   SDValue Result;
7618
7619   if (Subtarget->hasSSE3()) {
7620     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7621     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7622   } else {
7623     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7624     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7625                                            S2F, 0x4E, DAG);
7626     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7627                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7628                          Sub);
7629   }
7630
7631   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7632                      DAG.getIntPtrConstant(0));
7633 }
7634
7635 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7636 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7637                                                SelectionDAG &DAG) const {
7638   DebugLoc dl = Op.getDebugLoc();
7639   // FP constant to bias correct the final result.
7640   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7641                                    MVT::f64);
7642
7643   // Load the 32-bit value into an XMM register.
7644   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7645                              Op.getOperand(0));
7646
7647   // Zero out the upper parts of the register.
7648   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7649
7650   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7651                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7652                      DAG.getIntPtrConstant(0));
7653
7654   // Or the load with the bias.
7655   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7656                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7657                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7658                                                    MVT::v2f64, Load)),
7659                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7660                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7661                                                    MVT::v2f64, Bias)));
7662   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7663                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7664                    DAG.getIntPtrConstant(0));
7665
7666   // Subtract the bias.
7667   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7668
7669   // Handle final rounding.
7670   EVT DestVT = Op.getValueType();
7671
7672   if (DestVT.bitsLT(MVT::f64)) {
7673     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7674                        DAG.getIntPtrConstant(0));
7675   } else if (DestVT.bitsGT(MVT::f64)) {
7676     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7677   }
7678
7679   // Handle final rounding.
7680   return Sub;
7681 }
7682
7683 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7684                                            SelectionDAG &DAG) const {
7685   SDValue N0 = Op.getOperand(0);
7686   DebugLoc dl = Op.getDebugLoc();
7687
7688   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7689   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7690   // the optimization here.
7691   if (DAG.SignBitIsZero(N0))
7692     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7693
7694   EVT SrcVT = N0.getValueType();
7695   EVT DstVT = Op.getValueType();
7696   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7697     return LowerUINT_TO_FP_i64(Op, DAG);
7698   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7699     return LowerUINT_TO_FP_i32(Op, DAG);
7700   else if (Subtarget->is64Bit() &&
7701            SrcVT == MVT::i64 && DstVT == MVT::f32)
7702     return SDValue();
7703
7704   // Make a 64-bit buffer, and use it to build an FILD.
7705   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7706   if (SrcVT == MVT::i32) {
7707     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7708     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7709                                      getPointerTy(), StackSlot, WordOff);
7710     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7711                                   StackSlot, MachinePointerInfo(),
7712                                   false, false, 0);
7713     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7714                                   OffsetSlot, MachinePointerInfo(),
7715                                   false, false, 0);
7716     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7717     return Fild;
7718   }
7719
7720   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7721   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7722                                StackSlot, MachinePointerInfo(),
7723                                false, false, 0);
7724   // For i64 source, we need to add the appropriate power of 2 if the input
7725   // was negative.  This is the same as the optimization in
7726   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7727   // we must be careful to do the computation in x87 extended precision, not
7728   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7729   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7730   MachineMemOperand *MMO =
7731     DAG.getMachineFunction()
7732     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7733                           MachineMemOperand::MOLoad, 8, 8);
7734
7735   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7736   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7737   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7738                                          MVT::i64, MMO);
7739
7740   APInt FF(32, 0x5F800000ULL);
7741
7742   // Check whether the sign bit is set.
7743   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7744                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7745                                  ISD::SETLT);
7746
7747   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7748   SDValue FudgePtr = DAG.getConstantPool(
7749                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7750                                          getPointerTy());
7751
7752   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7753   SDValue Zero = DAG.getIntPtrConstant(0);
7754   SDValue Four = DAG.getIntPtrConstant(4);
7755   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7756                                Zero, Four);
7757   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7758
7759   // Load the value out, extending it from f32 to f80.
7760   // FIXME: Avoid the extend by constructing the right constant pool?
7761   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7762                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7763                                  MVT::f32, false, false, 4);
7764   // Extend everything to 80 bits to force it to be done on x87.
7765   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7766   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7767 }
7768
7769 std::pair<SDValue,SDValue> X86TargetLowering::
7770 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7771   DebugLoc DL = Op.getDebugLoc();
7772
7773   EVT DstTy = Op.getValueType();
7774
7775   if (!IsSigned) {
7776     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7777     DstTy = MVT::i64;
7778   }
7779
7780   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7781          DstTy.getSimpleVT() >= MVT::i16 &&
7782          "Unknown FP_TO_SINT to lower!");
7783
7784   // These are really Legal.
7785   if (DstTy == MVT::i32 &&
7786       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7787     return std::make_pair(SDValue(), SDValue());
7788   if (Subtarget->is64Bit() &&
7789       DstTy == MVT::i64 &&
7790       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7791     return std::make_pair(SDValue(), SDValue());
7792
7793   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7794   // stack slot.
7795   MachineFunction &MF = DAG.getMachineFunction();
7796   unsigned MemSize = DstTy.getSizeInBits()/8;
7797   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7798   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7799
7800
7801
7802   unsigned Opc;
7803   switch (DstTy.getSimpleVT().SimpleTy) {
7804   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7805   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7806   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7807   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7808   }
7809
7810   SDValue Chain = DAG.getEntryNode();
7811   SDValue Value = Op.getOperand(0);
7812   EVT TheVT = Op.getOperand(0).getValueType();
7813   if (isScalarFPTypeInSSEReg(TheVT)) {
7814     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7815     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7816                          MachinePointerInfo::getFixedStack(SSFI),
7817                          false, false, 0);
7818     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7819     SDValue Ops[] = {
7820       Chain, StackSlot, DAG.getValueType(TheVT)
7821     };
7822
7823     MachineMemOperand *MMO =
7824       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7825                               MachineMemOperand::MOLoad, MemSize, MemSize);
7826     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7827                                     DstTy, MMO);
7828     Chain = Value.getValue(1);
7829     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7830     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7831   }
7832
7833   MachineMemOperand *MMO =
7834     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7835                             MachineMemOperand::MOStore, MemSize, MemSize);
7836
7837   // Build the FP_TO_INT*_IN_MEM
7838   SDValue Ops[] = { Chain, Value, StackSlot };
7839   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7840                                          Ops, 3, DstTy, MMO);
7841
7842   return std::make_pair(FIST, StackSlot);
7843 }
7844
7845 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7846                                            SelectionDAG &DAG) const {
7847   if (Op.getValueType().isVector())
7848     return SDValue();
7849
7850   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7851   SDValue FIST = Vals.first, StackSlot = Vals.second;
7852   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7853   if (FIST.getNode() == 0) return Op;
7854
7855   // Load the result.
7856   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7857                      FIST, StackSlot, MachinePointerInfo(),
7858                      false, false, false, 0);
7859 }
7860
7861 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7862                                            SelectionDAG &DAG) const {
7863   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7864   SDValue FIST = Vals.first, StackSlot = Vals.second;
7865   assert(FIST.getNode() && "Unexpected failure");
7866
7867   // Load the result.
7868   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7869                      FIST, StackSlot, MachinePointerInfo(),
7870                      false, false, false, 0);
7871 }
7872
7873 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7874                                      SelectionDAG &DAG) const {
7875   LLVMContext *Context = DAG.getContext();
7876   DebugLoc dl = Op.getDebugLoc();
7877   EVT VT = Op.getValueType();
7878   EVT EltVT = VT;
7879   if (VT.isVector())
7880     EltVT = VT.getVectorElementType();
7881   Constant *C;
7882   if (EltVT == MVT::f64) {
7883     C = ConstantVector::getSplat(2, 
7884                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7885   } else {
7886     C = ConstantVector::getSplat(4,
7887                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7888   }
7889   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7890   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7891                              MachinePointerInfo::getConstantPool(),
7892                              false, false, false, 16);
7893   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7894 }
7895
7896 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7897   LLVMContext *Context = DAG.getContext();
7898   DebugLoc dl = Op.getDebugLoc();
7899   EVT VT = Op.getValueType();
7900   EVT EltVT = VT;
7901   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7902   if (VT.isVector()) {
7903     EltVT = VT.getVectorElementType();
7904     NumElts = VT.getVectorNumElements();
7905   }
7906   Constant *C;
7907   if (EltVT == MVT::f64)
7908     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7909   else
7910     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7911   C = ConstantVector::getSplat(NumElts, C);
7912   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7913   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7914                              MachinePointerInfo::getConstantPool(),
7915                              false, false, false, 16);
7916   if (VT.isVector()) {
7917     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7918     return DAG.getNode(ISD::BITCAST, dl, VT,
7919                        DAG.getNode(ISD::XOR, dl, XORVT,
7920                     DAG.getNode(ISD::BITCAST, dl, XORVT,
7921                                 Op.getOperand(0)),
7922                     DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7923   } else {
7924     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7925   }
7926 }
7927
7928 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7929   LLVMContext *Context = DAG.getContext();
7930   SDValue Op0 = Op.getOperand(0);
7931   SDValue Op1 = Op.getOperand(1);
7932   DebugLoc dl = Op.getDebugLoc();
7933   EVT VT = Op.getValueType();
7934   EVT SrcVT = Op1.getValueType();
7935
7936   // If second operand is smaller, extend it first.
7937   if (SrcVT.bitsLT(VT)) {
7938     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7939     SrcVT = VT;
7940   }
7941   // And if it is bigger, shrink it first.
7942   if (SrcVT.bitsGT(VT)) {
7943     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7944     SrcVT = VT;
7945   }
7946
7947   // At this point the operands and the result should have the same
7948   // type, and that won't be f80 since that is not custom lowered.
7949
7950   // First get the sign bit of second operand.
7951   SmallVector<Constant*,4> CV;
7952   if (SrcVT == MVT::f64) {
7953     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7954     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7955   } else {
7956     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7957     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7958     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7959     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7960   }
7961   Constant *C = ConstantVector::get(CV);
7962   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7963   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
7964                               MachinePointerInfo::getConstantPool(),
7965                               false, false, false, 16);
7966   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
7967
7968   // Shift sign bit right or left if the two operands have different types.
7969   if (SrcVT.bitsGT(VT)) {
7970     // Op0 is MVT::f32, Op1 is MVT::f64.
7971     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
7972     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
7973                           DAG.getConstant(32, MVT::i32));
7974     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
7975     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
7976                           DAG.getIntPtrConstant(0));
7977   }
7978
7979   // Clear first operand sign bit.
7980   CV.clear();
7981   if (VT == MVT::f64) {
7982     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7983     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7984   } else {
7985     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7986     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7987     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7988     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7989   }
7990   C = ConstantVector::get(CV);
7991   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7992   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7993                               MachinePointerInfo::getConstantPool(),
7994                               false, false, false, 16);
7995   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
7996
7997   // Or the value with the sign bit.
7998   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
7999 }
8000
8001 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8002   SDValue N0 = Op.getOperand(0);
8003   DebugLoc dl = Op.getDebugLoc();
8004   EVT VT = Op.getValueType();
8005
8006   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8007   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8008                                   DAG.getConstant(1, VT));
8009   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8010 }
8011
8012 /// Emit nodes that will be selected as "test Op0,Op0", or something
8013 /// equivalent.
8014 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8015                                     SelectionDAG &DAG) const {
8016   DebugLoc dl = Op.getDebugLoc();
8017
8018   // CF and OF aren't always set the way we want. Determine which
8019   // of these we need.
8020   bool NeedCF = false;
8021   bool NeedOF = false;
8022   switch (X86CC) {
8023   default: break;
8024   case X86::COND_A: case X86::COND_AE:
8025   case X86::COND_B: case X86::COND_BE:
8026     NeedCF = true;
8027     break;
8028   case X86::COND_G: case X86::COND_GE:
8029   case X86::COND_L: case X86::COND_LE:
8030   case X86::COND_O: case X86::COND_NO:
8031     NeedOF = true;
8032     break;
8033   }
8034
8035   // See if we can use the EFLAGS value from the operand instead of
8036   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8037   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8038   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8039     // Emit a CMP with 0, which is the TEST pattern.
8040     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8041                        DAG.getConstant(0, Op.getValueType()));
8042
8043   unsigned Opcode = 0;
8044   unsigned NumOperands = 0;
8045   switch (Op.getNode()->getOpcode()) {
8046   case ISD::ADD:
8047     // Due to an isel shortcoming, be conservative if this add is likely to be
8048     // selected as part of a load-modify-store instruction. When the root node
8049     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8050     // uses of other nodes in the match, such as the ADD in this case. This
8051     // leads to the ADD being left around and reselected, with the result being
8052     // two adds in the output.  Alas, even if none our users are stores, that
8053     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8054     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8055     // climbing the DAG back to the root, and it doesn't seem to be worth the
8056     // effort.
8057     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8058          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8059       if (UI->getOpcode() != ISD::CopyToReg &&
8060           UI->getOpcode() != ISD::SETCC &&
8061           UI->getOpcode() != ISD::STORE)
8062         goto default_case;
8063
8064     if (ConstantSDNode *C =
8065         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8066       // An add of one will be selected as an INC.
8067       if (C->getAPIntValue() == 1) {
8068         Opcode = X86ISD::INC;
8069         NumOperands = 1;
8070         break;
8071       }
8072
8073       // An add of negative one (subtract of one) will be selected as a DEC.
8074       if (C->getAPIntValue().isAllOnesValue()) {
8075         Opcode = X86ISD::DEC;
8076         NumOperands = 1;
8077         break;
8078       }
8079     }
8080
8081     // Otherwise use a regular EFLAGS-setting add.
8082     Opcode = X86ISD::ADD;
8083     NumOperands = 2;
8084     break;
8085   case ISD::AND: {
8086     // If the primary and result isn't used, don't bother using X86ISD::AND,
8087     // because a TEST instruction will be better.
8088     bool NonFlagUse = false;
8089     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8090            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8091       SDNode *User = *UI;
8092       unsigned UOpNo = UI.getOperandNo();
8093       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8094         // Look pass truncate.
8095         UOpNo = User->use_begin().getOperandNo();
8096         User = *User->use_begin();
8097       }
8098
8099       if (User->getOpcode() != ISD::BRCOND &&
8100           User->getOpcode() != ISD::SETCC &&
8101           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8102         NonFlagUse = true;
8103         break;
8104       }
8105     }
8106
8107     if (!NonFlagUse)
8108       break;
8109   }
8110     // FALL THROUGH
8111   case ISD::SUB:
8112   case ISD::OR:
8113   case ISD::XOR:
8114     // Due to the ISEL shortcoming noted above, be conservative if this op is
8115     // likely to be selected as part of a load-modify-store instruction.
8116     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8117            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8118       if (UI->getOpcode() == ISD::STORE)
8119         goto default_case;
8120
8121     // Otherwise use a regular EFLAGS-setting instruction.
8122     switch (Op.getNode()->getOpcode()) {
8123     default: llvm_unreachable("unexpected operator!");
8124     case ISD::SUB: Opcode = X86ISD::SUB; break;
8125     case ISD::OR:  Opcode = X86ISD::OR;  break;
8126     case ISD::XOR: Opcode = X86ISD::XOR; break;
8127     case ISD::AND: Opcode = X86ISD::AND; break;
8128     }
8129
8130     NumOperands = 2;
8131     break;
8132   case X86ISD::ADD:
8133   case X86ISD::SUB:
8134   case X86ISD::INC:
8135   case X86ISD::DEC:
8136   case X86ISD::OR:
8137   case X86ISD::XOR:
8138   case X86ISD::AND:
8139     return SDValue(Op.getNode(), 1);
8140   default:
8141   default_case:
8142     break;
8143   }
8144
8145   if (Opcode == 0)
8146     // Emit a CMP with 0, which is the TEST pattern.
8147     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8148                        DAG.getConstant(0, Op.getValueType()));
8149
8150   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8151   SmallVector<SDValue, 4> Ops;
8152   for (unsigned i = 0; i != NumOperands; ++i)
8153     Ops.push_back(Op.getOperand(i));
8154
8155   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8156   DAG.ReplaceAllUsesWith(Op, New);
8157   return SDValue(New.getNode(), 1);
8158 }
8159
8160 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8161 /// equivalent.
8162 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8163                                    SelectionDAG &DAG) const {
8164   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8165     if (C->getAPIntValue() == 0)
8166       return EmitTest(Op0, X86CC, DAG);
8167
8168   DebugLoc dl = Op0.getDebugLoc();
8169   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8170 }
8171
8172 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8173 /// if it's possible.
8174 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8175                                      DebugLoc dl, SelectionDAG &DAG) const {
8176   SDValue Op0 = And.getOperand(0);
8177   SDValue Op1 = And.getOperand(1);
8178   if (Op0.getOpcode() == ISD::TRUNCATE)
8179     Op0 = Op0.getOperand(0);
8180   if (Op1.getOpcode() == ISD::TRUNCATE)
8181     Op1 = Op1.getOperand(0);
8182
8183   SDValue LHS, RHS;
8184   if (Op1.getOpcode() == ISD::SHL)
8185     std::swap(Op0, Op1);
8186   if (Op0.getOpcode() == ISD::SHL) {
8187     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8188       if (And00C->getZExtValue() == 1) {
8189         // If we looked past a truncate, check that it's only truncating away
8190         // known zeros.
8191         unsigned BitWidth = Op0.getValueSizeInBits();
8192         unsigned AndBitWidth = And.getValueSizeInBits();
8193         if (BitWidth > AndBitWidth) {
8194           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8195           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8196           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8197             return SDValue();
8198         }
8199         LHS = Op1;
8200         RHS = Op0.getOperand(1);
8201       }
8202   } else if (Op1.getOpcode() == ISD::Constant) {
8203     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8204     uint64_t AndRHSVal = AndRHS->getZExtValue();
8205     SDValue AndLHS = Op0;
8206
8207     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8208       LHS = AndLHS.getOperand(0);
8209       RHS = AndLHS.getOperand(1);
8210     }
8211
8212     // Use BT if the immediate can't be encoded in a TEST instruction.
8213     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8214       LHS = AndLHS;
8215       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8216     }
8217   }
8218
8219   if (LHS.getNode()) {
8220     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8221     // instruction.  Since the shift amount is in-range-or-undefined, we know
8222     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8223     // the encoding for the i16 version is larger than the i32 version.
8224     // Also promote i16 to i32 for performance / code size reason.
8225     if (LHS.getValueType() == MVT::i8 ||
8226         LHS.getValueType() == MVT::i16)
8227       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8228
8229     // If the operand types disagree, extend the shift amount to match.  Since
8230     // BT ignores high bits (like shifts) we can use anyextend.
8231     if (LHS.getValueType() != RHS.getValueType())
8232       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8233
8234     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8235     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8236     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8237                        DAG.getConstant(Cond, MVT::i8), BT);
8238   }
8239
8240   return SDValue();
8241 }
8242
8243 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8244
8245   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8246
8247   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8248   SDValue Op0 = Op.getOperand(0);
8249   SDValue Op1 = Op.getOperand(1);
8250   DebugLoc dl = Op.getDebugLoc();
8251   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8252
8253   // Optimize to BT if possible.
8254   // Lower (X & (1 << N)) == 0 to BT(X, N).
8255   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8256   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8257   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8258       Op1.getOpcode() == ISD::Constant &&
8259       cast<ConstantSDNode>(Op1)->isNullValue() &&
8260       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8261     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8262     if (NewSetCC.getNode())
8263       return NewSetCC;
8264   }
8265
8266   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8267   // these.
8268   if (Op1.getOpcode() == ISD::Constant &&
8269       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8270        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8271       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8272
8273     // If the input is a setcc, then reuse the input setcc or use a new one with
8274     // the inverted condition.
8275     if (Op0.getOpcode() == X86ISD::SETCC) {
8276       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8277       bool Invert = (CC == ISD::SETNE) ^
8278         cast<ConstantSDNode>(Op1)->isNullValue();
8279       if (!Invert) return Op0;
8280
8281       CCode = X86::GetOppositeBranchCondition(CCode);
8282       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8283                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8284     }
8285   }
8286
8287   bool isFP = Op1.getValueType().isFloatingPoint();
8288   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8289   if (X86CC == X86::COND_INVALID)
8290     return SDValue();
8291
8292   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8293   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8294                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8295 }
8296
8297 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8298 // ones, and then concatenate the result back.
8299 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8300   EVT VT = Op.getValueType();
8301
8302   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8303          "Unsupported value type for operation");
8304
8305   int NumElems = VT.getVectorNumElements();
8306   DebugLoc dl = Op.getDebugLoc();
8307   SDValue CC = Op.getOperand(2);
8308   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8309   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8310
8311   // Extract the LHS vectors
8312   SDValue LHS = Op.getOperand(0);
8313   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8314   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8315
8316   // Extract the RHS vectors
8317   SDValue RHS = Op.getOperand(1);
8318   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8319   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8320
8321   // Issue the operation on the smaller types and concatenate the result back
8322   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8323   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8324   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8325                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8326                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8327 }
8328
8329
8330 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8331   SDValue Cond;
8332   SDValue Op0 = Op.getOperand(0);
8333   SDValue Op1 = Op.getOperand(1);
8334   SDValue CC = Op.getOperand(2);
8335   EVT VT = Op.getValueType();
8336   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8337   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8338   DebugLoc dl = Op.getDebugLoc();
8339
8340   if (isFP) {
8341     unsigned SSECC = 8;
8342     EVT EltVT = Op0.getValueType().getVectorElementType();
8343     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8344
8345     bool Swap = false;
8346
8347     // SSE Condition code mapping:
8348     //  0 - EQ
8349     //  1 - LT
8350     //  2 - LE
8351     //  3 - UNORD
8352     //  4 - NEQ
8353     //  5 - NLT
8354     //  6 - NLE
8355     //  7 - ORD
8356     switch (SetCCOpcode) {
8357     default: break;
8358     case ISD::SETOEQ:
8359     case ISD::SETEQ:  SSECC = 0; break;
8360     case ISD::SETOGT:
8361     case ISD::SETGT: Swap = true; // Fallthrough
8362     case ISD::SETLT:
8363     case ISD::SETOLT: SSECC = 1; break;
8364     case ISD::SETOGE:
8365     case ISD::SETGE: Swap = true; // Fallthrough
8366     case ISD::SETLE:
8367     case ISD::SETOLE: SSECC = 2; break;
8368     case ISD::SETUO:  SSECC = 3; break;
8369     case ISD::SETUNE:
8370     case ISD::SETNE:  SSECC = 4; break;
8371     case ISD::SETULE: Swap = true;
8372     case ISD::SETUGE: SSECC = 5; break;
8373     case ISD::SETULT: Swap = true;
8374     case ISD::SETUGT: SSECC = 6; break;
8375     case ISD::SETO:   SSECC = 7; break;
8376     }
8377     if (Swap)
8378       std::swap(Op0, Op1);
8379
8380     // In the two special cases we can't handle, emit two comparisons.
8381     if (SSECC == 8) {
8382       if (SetCCOpcode == ISD::SETUEQ) {
8383         SDValue UNORD, EQ;
8384         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8385                             DAG.getConstant(3, MVT::i8));
8386         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8387                          DAG.getConstant(0, MVT::i8));
8388         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8389       } else if (SetCCOpcode == ISD::SETONE) {
8390         SDValue ORD, NEQ;
8391         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8392                           DAG.getConstant(7, MVT::i8));
8393         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8394                           DAG.getConstant(4, MVT::i8));
8395         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8396       }
8397       llvm_unreachable("Illegal FP comparison");
8398     }
8399     // Handle all other FP comparisons here.
8400     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8401                        DAG.getConstant(SSECC, MVT::i8));
8402   }
8403
8404   // Break 256-bit integer vector compare into smaller ones.
8405   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8406     return Lower256IntVSETCC(Op, DAG);
8407
8408   // We are handling one of the integer comparisons here.  Since SSE only has
8409   // GT and EQ comparisons for integer, swapping operands and multiple
8410   // operations may be required for some comparisons.
8411   unsigned Opc = 0;
8412   bool Swap = false, Invert = false, FlipSigns = false;
8413
8414   switch (SetCCOpcode) {
8415   default: break;
8416   case ISD::SETNE:  Invert = true;
8417   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8418   case ISD::SETLT:  Swap = true;
8419   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8420   case ISD::SETGE:  Swap = true;
8421   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8422   case ISD::SETULT: Swap = true;
8423   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8424   case ISD::SETUGE: Swap = true;
8425   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8426   }
8427   if (Swap)
8428     std::swap(Op0, Op1);
8429
8430   // Check that the operation in question is available (most are plain SSE2,
8431   // but PCMPGTQ and PCMPEQQ have different requirements).
8432   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8433     return SDValue();
8434   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8435     return SDValue();
8436
8437   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8438   // bits of the inputs before performing those operations.
8439   if (FlipSigns) {
8440     EVT EltVT = VT.getVectorElementType();
8441     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8442                                       EltVT);
8443     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8444     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8445                                     SignBits.size());
8446     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8447     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8448   }
8449
8450   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8451
8452   // If the logical-not of the result is required, perform that now.
8453   if (Invert)
8454     Result = DAG.getNOT(dl, Result, VT);
8455
8456   return Result;
8457 }
8458
8459 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8460 static bool isX86LogicalCmp(SDValue Op) {
8461   unsigned Opc = Op.getNode()->getOpcode();
8462   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8463     return true;
8464   if (Op.getResNo() == 1 &&
8465       (Opc == X86ISD::ADD ||
8466        Opc == X86ISD::SUB ||
8467        Opc == X86ISD::ADC ||
8468        Opc == X86ISD::SBB ||
8469        Opc == X86ISD::SMUL ||
8470        Opc == X86ISD::UMUL ||
8471        Opc == X86ISD::INC ||
8472        Opc == X86ISD::DEC ||
8473        Opc == X86ISD::OR ||
8474        Opc == X86ISD::XOR ||
8475        Opc == X86ISD::AND))
8476     return true;
8477
8478   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8479     return true;
8480
8481   return false;
8482 }
8483
8484 static bool isZero(SDValue V) {
8485   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8486   return C && C->isNullValue();
8487 }
8488
8489 static bool isAllOnes(SDValue V) {
8490   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8491   return C && C->isAllOnesValue();
8492 }
8493
8494 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8495   bool addTest = true;
8496   SDValue Cond  = Op.getOperand(0);
8497   SDValue Op1 = Op.getOperand(1);
8498   SDValue Op2 = Op.getOperand(2);
8499   DebugLoc DL = Op.getDebugLoc();
8500   SDValue CC;
8501
8502   if (Cond.getOpcode() == ISD::SETCC) {
8503     SDValue NewCond = LowerSETCC(Cond, DAG);
8504     if (NewCond.getNode())
8505       Cond = NewCond;
8506   }
8507
8508   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8509   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8510   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8511   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8512   if (Cond.getOpcode() == X86ISD::SETCC &&
8513       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8514       isZero(Cond.getOperand(1).getOperand(1))) {
8515     SDValue Cmp = Cond.getOperand(1);
8516
8517     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8518
8519     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8520         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8521       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8522
8523       SDValue CmpOp0 = Cmp.getOperand(0);
8524       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8525                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8526
8527       SDValue Res =   // Res = 0 or -1.
8528         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8529                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8530
8531       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8532         Res = DAG.getNOT(DL, Res, Res.getValueType());
8533
8534       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8535       if (N2C == 0 || !N2C->isNullValue())
8536         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8537       return Res;
8538     }
8539   }
8540
8541   // Look past (and (setcc_carry (cmp ...)), 1).
8542   if (Cond.getOpcode() == ISD::AND &&
8543       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8544     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8545     if (C && C->getAPIntValue() == 1)
8546       Cond = Cond.getOperand(0);
8547   }
8548
8549   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8550   // setting operand in place of the X86ISD::SETCC.
8551   unsigned CondOpcode = Cond.getOpcode();
8552   if (CondOpcode == X86ISD::SETCC ||
8553       CondOpcode == X86ISD::SETCC_CARRY) {
8554     CC = Cond.getOperand(0);
8555
8556     SDValue Cmp = Cond.getOperand(1);
8557     unsigned Opc = Cmp.getOpcode();
8558     EVT VT = Op.getValueType();
8559
8560     bool IllegalFPCMov = false;
8561     if (VT.isFloatingPoint() && !VT.isVector() &&
8562         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8563       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8564
8565     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8566         Opc == X86ISD::BT) { // FIXME
8567       Cond = Cmp;
8568       addTest = false;
8569     }
8570   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8571              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8572              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8573               Cond.getOperand(0).getValueType() != MVT::i8)) {
8574     SDValue LHS = Cond.getOperand(0);
8575     SDValue RHS = Cond.getOperand(1);
8576     unsigned X86Opcode;
8577     unsigned X86Cond;
8578     SDVTList VTs;
8579     switch (CondOpcode) {
8580     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8581     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8582     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8583     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8584     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8585     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8586     default: llvm_unreachable("unexpected overflowing operator");
8587     }
8588     if (CondOpcode == ISD::UMULO)
8589       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8590                           MVT::i32);
8591     else
8592       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8593
8594     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8595
8596     if (CondOpcode == ISD::UMULO)
8597       Cond = X86Op.getValue(2);
8598     else
8599       Cond = X86Op.getValue(1);
8600
8601     CC = DAG.getConstant(X86Cond, MVT::i8);
8602     addTest = false;
8603   }
8604
8605   if (addTest) {
8606     // Look pass the truncate.
8607     if (Cond.getOpcode() == ISD::TRUNCATE)
8608       Cond = Cond.getOperand(0);
8609
8610     // We know the result of AND is compared against zero. Try to match
8611     // it to BT.
8612     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8613       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8614       if (NewSetCC.getNode()) {
8615         CC = NewSetCC.getOperand(0);
8616         Cond = NewSetCC.getOperand(1);
8617         addTest = false;
8618       }
8619     }
8620   }
8621
8622   if (addTest) {
8623     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8624     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8625   }
8626
8627   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8628   // a <  b ?  0 : -1 -> RES = setcc_carry
8629   // a >= b ? -1 :  0 -> RES = setcc_carry
8630   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8631   if (Cond.getOpcode() == X86ISD::CMP) {
8632     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8633
8634     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8635         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8636       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8637                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8638       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8639         return DAG.getNOT(DL, Res, Res.getValueType());
8640       return Res;
8641     }
8642   }
8643
8644   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8645   // condition is true.
8646   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8647   SDValue Ops[] = { Op2, Op1, CC, Cond };
8648   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8649 }
8650
8651 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8652 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8653 // from the AND / OR.
8654 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8655   Opc = Op.getOpcode();
8656   if (Opc != ISD::OR && Opc != ISD::AND)
8657     return false;
8658   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8659           Op.getOperand(0).hasOneUse() &&
8660           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8661           Op.getOperand(1).hasOneUse());
8662 }
8663
8664 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8665 // 1 and that the SETCC node has a single use.
8666 static bool isXor1OfSetCC(SDValue Op) {
8667   if (Op.getOpcode() != ISD::XOR)
8668     return false;
8669   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8670   if (N1C && N1C->getAPIntValue() == 1) {
8671     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8672       Op.getOperand(0).hasOneUse();
8673   }
8674   return false;
8675 }
8676
8677 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8678   bool addTest = true;
8679   SDValue Chain = Op.getOperand(0);
8680   SDValue Cond  = Op.getOperand(1);
8681   SDValue Dest  = Op.getOperand(2);
8682   DebugLoc dl = Op.getDebugLoc();
8683   SDValue CC;
8684   bool Inverted = false;
8685
8686   if (Cond.getOpcode() == ISD::SETCC) {
8687     // Check for setcc([su]{add,sub,mul}o == 0).
8688     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8689         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8690         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8691         Cond.getOperand(0).getResNo() == 1 &&
8692         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8693          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8694          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8695          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8696          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8697          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8698       Inverted = true;
8699       Cond = Cond.getOperand(0);
8700     } else {
8701       SDValue NewCond = LowerSETCC(Cond, DAG);
8702       if (NewCond.getNode())
8703         Cond = NewCond;
8704     }
8705   }
8706 #if 0
8707   // FIXME: LowerXALUO doesn't handle these!!
8708   else if (Cond.getOpcode() == X86ISD::ADD  ||
8709            Cond.getOpcode() == X86ISD::SUB  ||
8710            Cond.getOpcode() == X86ISD::SMUL ||
8711            Cond.getOpcode() == X86ISD::UMUL)
8712     Cond = LowerXALUO(Cond, DAG);
8713 #endif
8714
8715   // Look pass (and (setcc_carry (cmp ...)), 1).
8716   if (Cond.getOpcode() == ISD::AND &&
8717       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8718     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8719     if (C && C->getAPIntValue() == 1)
8720       Cond = Cond.getOperand(0);
8721   }
8722
8723   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8724   // setting operand in place of the X86ISD::SETCC.
8725   unsigned CondOpcode = Cond.getOpcode();
8726   if (CondOpcode == X86ISD::SETCC ||
8727       CondOpcode == X86ISD::SETCC_CARRY) {
8728     CC = Cond.getOperand(0);
8729
8730     SDValue Cmp = Cond.getOperand(1);
8731     unsigned Opc = Cmp.getOpcode();
8732     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8733     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8734       Cond = Cmp;
8735       addTest = false;
8736     } else {
8737       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8738       default: break;
8739       case X86::COND_O:
8740       case X86::COND_B:
8741         // These can only come from an arithmetic instruction with overflow,
8742         // e.g. SADDO, UADDO.
8743         Cond = Cond.getNode()->getOperand(1);
8744         addTest = false;
8745         break;
8746       }
8747     }
8748   }
8749   CondOpcode = Cond.getOpcode();
8750   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8751       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8752       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8753        Cond.getOperand(0).getValueType() != MVT::i8)) {
8754     SDValue LHS = Cond.getOperand(0);
8755     SDValue RHS = Cond.getOperand(1);
8756     unsigned X86Opcode;
8757     unsigned X86Cond;
8758     SDVTList VTs;
8759     switch (CondOpcode) {
8760     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8761     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8762     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8763     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8764     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8765     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8766     default: llvm_unreachable("unexpected overflowing operator");
8767     }
8768     if (Inverted)
8769       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8770     if (CondOpcode == ISD::UMULO)
8771       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8772                           MVT::i32);
8773     else
8774       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8775
8776     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8777
8778     if (CondOpcode == ISD::UMULO)
8779       Cond = X86Op.getValue(2);
8780     else
8781       Cond = X86Op.getValue(1);
8782
8783     CC = DAG.getConstant(X86Cond, MVT::i8);
8784     addTest = false;
8785   } else {
8786     unsigned CondOpc;
8787     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8788       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8789       if (CondOpc == ISD::OR) {
8790         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8791         // two branches instead of an explicit OR instruction with a
8792         // separate test.
8793         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8794             isX86LogicalCmp(Cmp)) {
8795           CC = Cond.getOperand(0).getOperand(0);
8796           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8797                               Chain, Dest, CC, Cmp);
8798           CC = Cond.getOperand(1).getOperand(0);
8799           Cond = Cmp;
8800           addTest = false;
8801         }
8802       } else { // ISD::AND
8803         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8804         // two branches instead of an explicit AND instruction with a
8805         // separate test. However, we only do this if this block doesn't
8806         // have a fall-through edge, because this requires an explicit
8807         // jmp when the condition is false.
8808         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8809             isX86LogicalCmp(Cmp) &&
8810             Op.getNode()->hasOneUse()) {
8811           X86::CondCode CCode =
8812             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8813           CCode = X86::GetOppositeBranchCondition(CCode);
8814           CC = DAG.getConstant(CCode, MVT::i8);
8815           SDNode *User = *Op.getNode()->use_begin();
8816           // Look for an unconditional branch following this conditional branch.
8817           // We need this because we need to reverse the successors in order
8818           // to implement FCMP_OEQ.
8819           if (User->getOpcode() == ISD::BR) {
8820             SDValue FalseBB = User->getOperand(1);
8821             SDNode *NewBR =
8822               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8823             assert(NewBR == User);
8824             (void)NewBR;
8825             Dest = FalseBB;
8826
8827             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8828                                 Chain, Dest, CC, Cmp);
8829             X86::CondCode CCode =
8830               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8831             CCode = X86::GetOppositeBranchCondition(CCode);
8832             CC = DAG.getConstant(CCode, MVT::i8);
8833             Cond = Cmp;
8834             addTest = false;
8835           }
8836         }
8837       }
8838     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8839       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8840       // It should be transformed during dag combiner except when the condition
8841       // is set by a arithmetics with overflow node.
8842       X86::CondCode CCode =
8843         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8844       CCode = X86::GetOppositeBranchCondition(CCode);
8845       CC = DAG.getConstant(CCode, MVT::i8);
8846       Cond = Cond.getOperand(0).getOperand(1);
8847       addTest = false;
8848     } else if (Cond.getOpcode() == ISD::SETCC &&
8849                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8850       // For FCMP_OEQ, we can emit
8851       // two branches instead of an explicit AND instruction with a
8852       // separate test. However, we only do this if this block doesn't
8853       // have a fall-through edge, because this requires an explicit
8854       // jmp when the condition is false.
8855       if (Op.getNode()->hasOneUse()) {
8856         SDNode *User = *Op.getNode()->use_begin();
8857         // Look for an unconditional branch following this conditional branch.
8858         // We need this because we need to reverse the successors in order
8859         // to implement FCMP_OEQ.
8860         if (User->getOpcode() == ISD::BR) {
8861           SDValue FalseBB = User->getOperand(1);
8862           SDNode *NewBR =
8863             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8864           assert(NewBR == User);
8865           (void)NewBR;
8866           Dest = FalseBB;
8867
8868           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8869                                     Cond.getOperand(0), Cond.getOperand(1));
8870           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8871           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8872                               Chain, Dest, CC, Cmp);
8873           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8874           Cond = Cmp;
8875           addTest = false;
8876         }
8877       }
8878     } else if (Cond.getOpcode() == ISD::SETCC &&
8879                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8880       // For FCMP_UNE, we can emit
8881       // two branches instead of an explicit AND instruction with a
8882       // separate test. However, we only do this if this block doesn't
8883       // have a fall-through edge, because this requires an explicit
8884       // jmp when the condition is false.
8885       if (Op.getNode()->hasOneUse()) {
8886         SDNode *User = *Op.getNode()->use_begin();
8887         // Look for an unconditional branch following this conditional branch.
8888         // We need this because we need to reverse the successors in order
8889         // to implement FCMP_UNE.
8890         if (User->getOpcode() == ISD::BR) {
8891           SDValue FalseBB = User->getOperand(1);
8892           SDNode *NewBR =
8893             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8894           assert(NewBR == User);
8895           (void)NewBR;
8896
8897           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8898                                     Cond.getOperand(0), Cond.getOperand(1));
8899           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8900           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8901                               Chain, Dest, CC, Cmp);
8902           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8903           Cond = Cmp;
8904           addTest = false;
8905           Dest = FalseBB;
8906         }
8907       }
8908     }
8909   }
8910
8911   if (addTest) {
8912     // Look pass the truncate.
8913     if (Cond.getOpcode() == ISD::TRUNCATE)
8914       Cond = Cond.getOperand(0);
8915
8916     // We know the result of AND is compared against zero. Try to match
8917     // it to BT.
8918     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8919       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8920       if (NewSetCC.getNode()) {
8921         CC = NewSetCC.getOperand(0);
8922         Cond = NewSetCC.getOperand(1);
8923         addTest = false;
8924       }
8925     }
8926   }
8927
8928   if (addTest) {
8929     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8930     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8931   }
8932   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8933                      Chain, Dest, CC, Cond);
8934 }
8935
8936
8937 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8938 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8939 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8940 // that the guard pages used by the OS virtual memory manager are allocated in
8941 // correct sequence.
8942 SDValue
8943 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8944                                            SelectionDAG &DAG) const {
8945   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8946           getTargetMachine().Options.EnableSegmentedStacks) &&
8947          "This should be used only on Windows targets or when segmented stacks "
8948          "are being used");
8949   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8950   DebugLoc dl = Op.getDebugLoc();
8951
8952   // Get the inputs.
8953   SDValue Chain = Op.getOperand(0);
8954   SDValue Size  = Op.getOperand(1);
8955   // FIXME: Ensure alignment here
8956
8957   bool Is64Bit = Subtarget->is64Bit();
8958   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8959
8960   if (getTargetMachine().Options.EnableSegmentedStacks) {
8961     MachineFunction &MF = DAG.getMachineFunction();
8962     MachineRegisterInfo &MRI = MF.getRegInfo();
8963
8964     if (Is64Bit) {
8965       // The 64 bit implementation of segmented stacks needs to clobber both r10
8966       // r11. This makes it impossible to use it along with nested parameters.
8967       const Function *F = MF.getFunction();
8968
8969       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8970            I != E; I++)
8971         if (I->hasNestAttr())
8972           report_fatal_error("Cannot use segmented stacks with functions that "
8973                              "have nested arguments.");
8974     }
8975
8976     const TargetRegisterClass *AddrRegClass =
8977       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8978     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8979     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8980     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8981                                 DAG.getRegister(Vreg, SPTy));
8982     SDValue Ops1[2] = { Value, Chain };
8983     return DAG.getMergeValues(Ops1, 2, dl);
8984   } else {
8985     SDValue Flag;
8986     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8987
8988     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8989     Flag = Chain.getValue(1);
8990     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8991
8992     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8993     Flag = Chain.getValue(1);
8994
8995     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8996
8997     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8998     return DAG.getMergeValues(Ops1, 2, dl);
8999   }
9000 }
9001
9002 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9003   MachineFunction &MF = DAG.getMachineFunction();
9004   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9005
9006   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9007   DebugLoc DL = Op.getDebugLoc();
9008
9009   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9010     // vastart just stores the address of the VarArgsFrameIndex slot into the
9011     // memory location argument.
9012     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9013                                    getPointerTy());
9014     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9015                         MachinePointerInfo(SV), false, false, 0);
9016   }
9017
9018   // __va_list_tag:
9019   //   gp_offset         (0 - 6 * 8)
9020   //   fp_offset         (48 - 48 + 8 * 16)
9021   //   overflow_arg_area (point to parameters coming in memory).
9022   //   reg_save_area
9023   SmallVector<SDValue, 8> MemOps;
9024   SDValue FIN = Op.getOperand(1);
9025   // Store gp_offset
9026   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9027                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9028                                                MVT::i32),
9029                                FIN, MachinePointerInfo(SV), false, false, 0);
9030   MemOps.push_back(Store);
9031
9032   // Store fp_offset
9033   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9034                     FIN, DAG.getIntPtrConstant(4));
9035   Store = DAG.getStore(Op.getOperand(0), DL,
9036                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9037                                        MVT::i32),
9038                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9039   MemOps.push_back(Store);
9040
9041   // Store ptr to overflow_arg_area
9042   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9043                     FIN, DAG.getIntPtrConstant(4));
9044   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9045                                     getPointerTy());
9046   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9047                        MachinePointerInfo(SV, 8),
9048                        false, false, 0);
9049   MemOps.push_back(Store);
9050
9051   // Store ptr to reg_save_area.
9052   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9053                     FIN, DAG.getIntPtrConstant(8));
9054   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9055                                     getPointerTy());
9056   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9057                        MachinePointerInfo(SV, 16), false, false, 0);
9058   MemOps.push_back(Store);
9059   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9060                      &MemOps[0], MemOps.size());
9061 }
9062
9063 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9064   assert(Subtarget->is64Bit() &&
9065          "LowerVAARG only handles 64-bit va_arg!");
9066   assert((Subtarget->isTargetLinux() ||
9067           Subtarget->isTargetDarwin()) &&
9068           "Unhandled target in LowerVAARG");
9069   assert(Op.getNode()->getNumOperands() == 4);
9070   SDValue Chain = Op.getOperand(0);
9071   SDValue SrcPtr = Op.getOperand(1);
9072   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9073   unsigned Align = Op.getConstantOperandVal(3);
9074   DebugLoc dl = Op.getDebugLoc();
9075
9076   EVT ArgVT = Op.getNode()->getValueType(0);
9077   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9078   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9079   uint8_t ArgMode;
9080
9081   // Decide which area this value should be read from.
9082   // TODO: Implement the AMD64 ABI in its entirety. This simple
9083   // selection mechanism works only for the basic types.
9084   if (ArgVT == MVT::f80) {
9085     llvm_unreachable("va_arg for f80 not yet implemented");
9086   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9087     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9088   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9089     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9090   } else {
9091     llvm_unreachable("Unhandled argument type in LowerVAARG");
9092   }
9093
9094   if (ArgMode == 2) {
9095     // Sanity Check: Make sure using fp_offset makes sense.
9096     assert(!getTargetMachine().Options.UseSoftFloat &&
9097            !(DAG.getMachineFunction()
9098                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9099            Subtarget->hasSSE1());
9100   }
9101
9102   // Insert VAARG_64 node into the DAG
9103   // VAARG_64 returns two values: Variable Argument Address, Chain
9104   SmallVector<SDValue, 11> InstOps;
9105   InstOps.push_back(Chain);
9106   InstOps.push_back(SrcPtr);
9107   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9108   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9109   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9110   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9111   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9112                                           VTs, &InstOps[0], InstOps.size(),
9113                                           MVT::i64,
9114                                           MachinePointerInfo(SV),
9115                                           /*Align=*/0,
9116                                           /*Volatile=*/false,
9117                                           /*ReadMem=*/true,
9118                                           /*WriteMem=*/true);
9119   Chain = VAARG.getValue(1);
9120
9121   // Load the next argument and return it
9122   return DAG.getLoad(ArgVT, dl,
9123                      Chain,
9124                      VAARG,
9125                      MachinePointerInfo(),
9126                      false, false, false, 0);
9127 }
9128
9129 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9130   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9131   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9132   SDValue Chain = Op.getOperand(0);
9133   SDValue DstPtr = Op.getOperand(1);
9134   SDValue SrcPtr = Op.getOperand(2);
9135   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9136   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9137   DebugLoc DL = Op.getDebugLoc();
9138
9139   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9140                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9141                        false,
9142                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9143 }
9144
9145 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9146 // may or may not be a constant. Takes immediate version of shift as input.
9147 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9148                                    SDValue SrcOp, SDValue ShAmt,
9149                                    SelectionDAG &DAG) {
9150   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9151
9152   if (isa<ConstantSDNode>(ShAmt)) {
9153     switch (Opc) {
9154       default: llvm_unreachable("Unknown target vector shift node");
9155       case X86ISD::VSHLI:
9156       case X86ISD::VSRLI:
9157       case X86ISD::VSRAI:
9158         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9159     }
9160   }
9161
9162   // Change opcode to non-immediate version
9163   switch (Opc) {
9164     default: llvm_unreachable("Unknown target vector shift node");
9165     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9166     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9167     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9168   }
9169
9170   // Need to build a vector containing shift amount
9171   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9172   SDValue ShOps[4];
9173   ShOps[0] = ShAmt;
9174   ShOps[1] = DAG.getConstant(0, MVT::i32);
9175   ShOps[2] = DAG.getUNDEF(MVT::i32);
9176   ShOps[3] = DAG.getUNDEF(MVT::i32);
9177   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9178   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9179   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9180 }
9181
9182 SDValue
9183 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9184   DebugLoc dl = Op.getDebugLoc();
9185   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9186   switch (IntNo) {
9187   default: return SDValue();    // Don't custom lower most intrinsics.
9188   // Comparison intrinsics.
9189   case Intrinsic::x86_sse_comieq_ss:
9190   case Intrinsic::x86_sse_comilt_ss:
9191   case Intrinsic::x86_sse_comile_ss:
9192   case Intrinsic::x86_sse_comigt_ss:
9193   case Intrinsic::x86_sse_comige_ss:
9194   case Intrinsic::x86_sse_comineq_ss:
9195   case Intrinsic::x86_sse_ucomieq_ss:
9196   case Intrinsic::x86_sse_ucomilt_ss:
9197   case Intrinsic::x86_sse_ucomile_ss:
9198   case Intrinsic::x86_sse_ucomigt_ss:
9199   case Intrinsic::x86_sse_ucomige_ss:
9200   case Intrinsic::x86_sse_ucomineq_ss:
9201   case Intrinsic::x86_sse2_comieq_sd:
9202   case Intrinsic::x86_sse2_comilt_sd:
9203   case Intrinsic::x86_sse2_comile_sd:
9204   case Intrinsic::x86_sse2_comigt_sd:
9205   case Intrinsic::x86_sse2_comige_sd:
9206   case Intrinsic::x86_sse2_comineq_sd:
9207   case Intrinsic::x86_sse2_ucomieq_sd:
9208   case Intrinsic::x86_sse2_ucomilt_sd:
9209   case Intrinsic::x86_sse2_ucomile_sd:
9210   case Intrinsic::x86_sse2_ucomigt_sd:
9211   case Intrinsic::x86_sse2_ucomige_sd:
9212   case Intrinsic::x86_sse2_ucomineq_sd: {
9213     unsigned Opc = 0;
9214     ISD::CondCode CC = ISD::SETCC_INVALID;
9215     switch (IntNo) {
9216     default: break;
9217     case Intrinsic::x86_sse_comieq_ss:
9218     case Intrinsic::x86_sse2_comieq_sd:
9219       Opc = X86ISD::COMI;
9220       CC = ISD::SETEQ;
9221       break;
9222     case Intrinsic::x86_sse_comilt_ss:
9223     case Intrinsic::x86_sse2_comilt_sd:
9224       Opc = X86ISD::COMI;
9225       CC = ISD::SETLT;
9226       break;
9227     case Intrinsic::x86_sse_comile_ss:
9228     case Intrinsic::x86_sse2_comile_sd:
9229       Opc = X86ISD::COMI;
9230       CC = ISD::SETLE;
9231       break;
9232     case Intrinsic::x86_sse_comigt_ss:
9233     case Intrinsic::x86_sse2_comigt_sd:
9234       Opc = X86ISD::COMI;
9235       CC = ISD::SETGT;
9236       break;
9237     case Intrinsic::x86_sse_comige_ss:
9238     case Intrinsic::x86_sse2_comige_sd:
9239       Opc = X86ISD::COMI;
9240       CC = ISD::SETGE;
9241       break;
9242     case Intrinsic::x86_sse_comineq_ss:
9243     case Intrinsic::x86_sse2_comineq_sd:
9244       Opc = X86ISD::COMI;
9245       CC = ISD::SETNE;
9246       break;
9247     case Intrinsic::x86_sse_ucomieq_ss:
9248     case Intrinsic::x86_sse2_ucomieq_sd:
9249       Opc = X86ISD::UCOMI;
9250       CC = ISD::SETEQ;
9251       break;
9252     case Intrinsic::x86_sse_ucomilt_ss:
9253     case Intrinsic::x86_sse2_ucomilt_sd:
9254       Opc = X86ISD::UCOMI;
9255       CC = ISD::SETLT;
9256       break;
9257     case Intrinsic::x86_sse_ucomile_ss:
9258     case Intrinsic::x86_sse2_ucomile_sd:
9259       Opc = X86ISD::UCOMI;
9260       CC = ISD::SETLE;
9261       break;
9262     case Intrinsic::x86_sse_ucomigt_ss:
9263     case Intrinsic::x86_sse2_ucomigt_sd:
9264       Opc = X86ISD::UCOMI;
9265       CC = ISD::SETGT;
9266       break;
9267     case Intrinsic::x86_sse_ucomige_ss:
9268     case Intrinsic::x86_sse2_ucomige_sd:
9269       Opc = X86ISD::UCOMI;
9270       CC = ISD::SETGE;
9271       break;
9272     case Intrinsic::x86_sse_ucomineq_ss:
9273     case Intrinsic::x86_sse2_ucomineq_sd:
9274       Opc = X86ISD::UCOMI;
9275       CC = ISD::SETNE;
9276       break;
9277     }
9278
9279     SDValue LHS = Op.getOperand(1);
9280     SDValue RHS = Op.getOperand(2);
9281     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9282     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9283     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9284     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9285                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9286     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9287   }
9288   // Arithmetic intrinsics.
9289   case Intrinsic::x86_sse3_hadd_ps:
9290   case Intrinsic::x86_sse3_hadd_pd:
9291   case Intrinsic::x86_avx_hadd_ps_256:
9292   case Intrinsic::x86_avx_hadd_pd_256:
9293     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9294                        Op.getOperand(1), Op.getOperand(2));
9295   case Intrinsic::x86_sse3_hsub_ps:
9296   case Intrinsic::x86_sse3_hsub_pd:
9297   case Intrinsic::x86_avx_hsub_ps_256:
9298   case Intrinsic::x86_avx_hsub_pd_256:
9299     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9300                        Op.getOperand(1), Op.getOperand(2));
9301   case Intrinsic::x86_ssse3_phadd_w_128:
9302   case Intrinsic::x86_ssse3_phadd_d_128:
9303   case Intrinsic::x86_avx2_phadd_w:
9304   case Intrinsic::x86_avx2_phadd_d:
9305     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9306                        Op.getOperand(1), Op.getOperand(2));
9307   case Intrinsic::x86_ssse3_phsub_w_128:
9308   case Intrinsic::x86_ssse3_phsub_d_128:
9309   case Intrinsic::x86_avx2_phsub_w:
9310   case Intrinsic::x86_avx2_phsub_d:
9311     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9312                        Op.getOperand(1), Op.getOperand(2));
9313   case Intrinsic::x86_avx2_psllv_d:
9314   case Intrinsic::x86_avx2_psllv_q:
9315   case Intrinsic::x86_avx2_psllv_d_256:
9316   case Intrinsic::x86_avx2_psllv_q_256:
9317     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9318                       Op.getOperand(1), Op.getOperand(2));
9319   case Intrinsic::x86_avx2_psrlv_d:
9320   case Intrinsic::x86_avx2_psrlv_q:
9321   case Intrinsic::x86_avx2_psrlv_d_256:
9322   case Intrinsic::x86_avx2_psrlv_q_256:
9323     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9324                       Op.getOperand(1), Op.getOperand(2));
9325   case Intrinsic::x86_avx2_psrav_d:
9326   case Intrinsic::x86_avx2_psrav_d_256:
9327     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9328                       Op.getOperand(1), Op.getOperand(2));
9329   case Intrinsic::x86_sse2_pcmpeq_b:
9330   case Intrinsic::x86_sse2_pcmpeq_w:
9331   case Intrinsic::x86_sse2_pcmpeq_d:
9332   case Intrinsic::x86_sse41_pcmpeqq:
9333   case Intrinsic::x86_avx2_pcmpeq_b:
9334   case Intrinsic::x86_avx2_pcmpeq_w:
9335   case Intrinsic::x86_avx2_pcmpeq_d:
9336   case Intrinsic::x86_avx2_pcmpeq_q:
9337     return DAG.getNode(X86ISD::PCMPEQ, dl, Op.getValueType(),
9338                        Op.getOperand(1), Op.getOperand(2));
9339   case Intrinsic::x86_sse2_pcmpgt_b:
9340   case Intrinsic::x86_sse2_pcmpgt_w:
9341   case Intrinsic::x86_sse2_pcmpgt_d:
9342   case Intrinsic::x86_sse42_pcmpgtq:
9343   case Intrinsic::x86_avx2_pcmpgt_b:
9344   case Intrinsic::x86_avx2_pcmpgt_w:
9345   case Intrinsic::x86_avx2_pcmpgt_d:
9346   case Intrinsic::x86_avx2_pcmpgt_q:
9347     return DAG.getNode(X86ISD::PCMPGT, dl, Op.getValueType(),
9348                        Op.getOperand(1), Op.getOperand(2));
9349   case Intrinsic::x86_ssse3_pshuf_b_128:
9350   case Intrinsic::x86_avx2_pshuf_b:
9351     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9352                        Op.getOperand(1), Op.getOperand(2));
9353   case Intrinsic::x86_ssse3_psign_b_128:
9354   case Intrinsic::x86_ssse3_psign_w_128:
9355   case Intrinsic::x86_ssse3_psign_d_128:
9356   case Intrinsic::x86_avx2_psign_b:
9357   case Intrinsic::x86_avx2_psign_w:
9358   case Intrinsic::x86_avx2_psign_d:
9359     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9360                        Op.getOperand(1), Op.getOperand(2));
9361
9362   // ptest and testp intrinsics. The intrinsic these come from are designed to
9363   // return an integer value, not just an instruction so lower it to the ptest
9364   // or testp pattern and a setcc for the result.
9365   case Intrinsic::x86_sse41_ptestz:
9366   case Intrinsic::x86_sse41_ptestc:
9367   case Intrinsic::x86_sse41_ptestnzc:
9368   case Intrinsic::x86_avx_ptestz_256:
9369   case Intrinsic::x86_avx_ptestc_256:
9370   case Intrinsic::x86_avx_ptestnzc_256:
9371   case Intrinsic::x86_avx_vtestz_ps:
9372   case Intrinsic::x86_avx_vtestc_ps:
9373   case Intrinsic::x86_avx_vtestnzc_ps:
9374   case Intrinsic::x86_avx_vtestz_pd:
9375   case Intrinsic::x86_avx_vtestc_pd:
9376   case Intrinsic::x86_avx_vtestnzc_pd:
9377   case Intrinsic::x86_avx_vtestz_ps_256:
9378   case Intrinsic::x86_avx_vtestc_ps_256:
9379   case Intrinsic::x86_avx_vtestnzc_ps_256:
9380   case Intrinsic::x86_avx_vtestz_pd_256:
9381   case Intrinsic::x86_avx_vtestc_pd_256:
9382   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9383     bool IsTestPacked = false;
9384     unsigned X86CC = 0;
9385     switch (IntNo) {
9386     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9387     case Intrinsic::x86_avx_vtestz_ps:
9388     case Intrinsic::x86_avx_vtestz_pd:
9389     case Intrinsic::x86_avx_vtestz_ps_256:
9390     case Intrinsic::x86_avx_vtestz_pd_256:
9391       IsTestPacked = true; // Fallthrough
9392     case Intrinsic::x86_sse41_ptestz:
9393     case Intrinsic::x86_avx_ptestz_256:
9394       // ZF = 1
9395       X86CC = X86::COND_E;
9396       break;
9397     case Intrinsic::x86_avx_vtestc_ps:
9398     case Intrinsic::x86_avx_vtestc_pd:
9399     case Intrinsic::x86_avx_vtestc_ps_256:
9400     case Intrinsic::x86_avx_vtestc_pd_256:
9401       IsTestPacked = true; // Fallthrough
9402     case Intrinsic::x86_sse41_ptestc:
9403     case Intrinsic::x86_avx_ptestc_256:
9404       // CF = 1
9405       X86CC = X86::COND_B;
9406       break;
9407     case Intrinsic::x86_avx_vtestnzc_ps:
9408     case Intrinsic::x86_avx_vtestnzc_pd:
9409     case Intrinsic::x86_avx_vtestnzc_ps_256:
9410     case Intrinsic::x86_avx_vtestnzc_pd_256:
9411       IsTestPacked = true; // Fallthrough
9412     case Intrinsic::x86_sse41_ptestnzc:
9413     case Intrinsic::x86_avx_ptestnzc_256:
9414       // ZF and CF = 0
9415       X86CC = X86::COND_A;
9416       break;
9417     }
9418
9419     SDValue LHS = Op.getOperand(1);
9420     SDValue RHS = Op.getOperand(2);
9421     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9422     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9423     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9424     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9425     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9426   }
9427
9428   // SSE/AVX shift intrinsics
9429   case Intrinsic::x86_sse2_psll_w:
9430   case Intrinsic::x86_sse2_psll_d:
9431   case Intrinsic::x86_sse2_psll_q:
9432   case Intrinsic::x86_avx2_psll_w:
9433   case Intrinsic::x86_avx2_psll_d:
9434   case Intrinsic::x86_avx2_psll_q:
9435     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9436                        Op.getOperand(1), Op.getOperand(2));
9437   case Intrinsic::x86_sse2_psrl_w:
9438   case Intrinsic::x86_sse2_psrl_d:
9439   case Intrinsic::x86_sse2_psrl_q:
9440   case Intrinsic::x86_avx2_psrl_w:
9441   case Intrinsic::x86_avx2_psrl_d:
9442   case Intrinsic::x86_avx2_psrl_q:
9443     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9444                        Op.getOperand(1), Op.getOperand(2));
9445   case Intrinsic::x86_sse2_psra_w:
9446   case Intrinsic::x86_sse2_psra_d:
9447   case Intrinsic::x86_avx2_psra_w:
9448   case Intrinsic::x86_avx2_psra_d:
9449     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9450                        Op.getOperand(1), Op.getOperand(2));
9451   case Intrinsic::x86_sse2_pslli_w:
9452   case Intrinsic::x86_sse2_pslli_d:
9453   case Intrinsic::x86_sse2_pslli_q:
9454   case Intrinsic::x86_avx2_pslli_w:
9455   case Intrinsic::x86_avx2_pslli_d:
9456   case Intrinsic::x86_avx2_pslli_q:
9457     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9458                                Op.getOperand(1), Op.getOperand(2), DAG);
9459   case Intrinsic::x86_sse2_psrli_w:
9460   case Intrinsic::x86_sse2_psrli_d:
9461   case Intrinsic::x86_sse2_psrli_q:
9462   case Intrinsic::x86_avx2_psrli_w:
9463   case Intrinsic::x86_avx2_psrli_d:
9464   case Intrinsic::x86_avx2_psrli_q:
9465     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9466                                Op.getOperand(1), Op.getOperand(2), DAG);
9467   case Intrinsic::x86_sse2_psrai_w:
9468   case Intrinsic::x86_sse2_psrai_d:
9469   case Intrinsic::x86_avx2_psrai_w:
9470   case Intrinsic::x86_avx2_psrai_d:
9471     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9472                                Op.getOperand(1), Op.getOperand(2), DAG);
9473   // Fix vector shift instructions where the last operand is a non-immediate
9474   // i32 value.
9475   case Intrinsic::x86_mmx_pslli_w:
9476   case Intrinsic::x86_mmx_pslli_d:
9477   case Intrinsic::x86_mmx_pslli_q:
9478   case Intrinsic::x86_mmx_psrli_w:
9479   case Intrinsic::x86_mmx_psrli_d:
9480   case Intrinsic::x86_mmx_psrli_q:
9481   case Intrinsic::x86_mmx_psrai_w:
9482   case Intrinsic::x86_mmx_psrai_d: {
9483     SDValue ShAmt = Op.getOperand(2);
9484     if (isa<ConstantSDNode>(ShAmt))
9485       return SDValue();
9486
9487     unsigned NewIntNo = 0;
9488     switch (IntNo) {
9489     case Intrinsic::x86_mmx_pslli_w:
9490       NewIntNo = Intrinsic::x86_mmx_psll_w;
9491       break;
9492     case Intrinsic::x86_mmx_pslli_d:
9493       NewIntNo = Intrinsic::x86_mmx_psll_d;
9494       break;
9495     case Intrinsic::x86_mmx_pslli_q:
9496       NewIntNo = Intrinsic::x86_mmx_psll_q;
9497       break;
9498     case Intrinsic::x86_mmx_psrli_w:
9499       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9500       break;
9501     case Intrinsic::x86_mmx_psrli_d:
9502       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9503       break;
9504     case Intrinsic::x86_mmx_psrli_q:
9505       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9506       break;
9507     case Intrinsic::x86_mmx_psrai_w:
9508       NewIntNo = Intrinsic::x86_mmx_psra_w;
9509       break;
9510     case Intrinsic::x86_mmx_psrai_d:
9511       NewIntNo = Intrinsic::x86_mmx_psra_d;
9512       break;
9513     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9514     }
9515
9516     // The vector shift intrinsics with scalars uses 32b shift amounts but
9517     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9518     // to be zero.
9519     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9520                          DAG.getConstant(0, MVT::i32));
9521 // FIXME this must be lowered to get rid of the invalid type.
9522
9523     EVT VT = Op.getValueType();
9524     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9525     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9526                        DAG.getConstant(NewIntNo, MVT::i32),
9527                        Op.getOperand(1), ShAmt);
9528   }
9529   }
9530 }
9531
9532 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9533                                            SelectionDAG &DAG) const {
9534   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9535   MFI->setReturnAddressIsTaken(true);
9536
9537   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9538   DebugLoc dl = Op.getDebugLoc();
9539
9540   if (Depth > 0) {
9541     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9542     SDValue Offset =
9543       DAG.getConstant(TD->getPointerSize(),
9544                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9545     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9546                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9547                                    FrameAddr, Offset),
9548                        MachinePointerInfo(), false, false, false, 0);
9549   }
9550
9551   // Just load the return address.
9552   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9553   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9554                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9555 }
9556
9557 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9558   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9559   MFI->setFrameAddressIsTaken(true);
9560
9561   EVT VT = Op.getValueType();
9562   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9563   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9564   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9565   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9566   while (Depth--)
9567     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9568                             MachinePointerInfo(),
9569                             false, false, false, 0);
9570   return FrameAddr;
9571 }
9572
9573 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9574                                                      SelectionDAG &DAG) const {
9575   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9576 }
9577
9578 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9579   MachineFunction &MF = DAG.getMachineFunction();
9580   SDValue Chain     = Op.getOperand(0);
9581   SDValue Offset    = Op.getOperand(1);
9582   SDValue Handler   = Op.getOperand(2);
9583   DebugLoc dl       = Op.getDebugLoc();
9584
9585   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9586                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9587                                      getPointerTy());
9588   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9589
9590   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9591                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9592   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9593   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9594                        false, false, 0);
9595   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9596   MF.getRegInfo().addLiveOut(StoreAddrReg);
9597
9598   return DAG.getNode(X86ISD::EH_RETURN, dl,
9599                      MVT::Other,
9600                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9601 }
9602
9603 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9604                                                   SelectionDAG &DAG) const {
9605   return Op.getOperand(0);
9606 }
9607
9608 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9609                                                 SelectionDAG &DAG) const {
9610   SDValue Root = Op.getOperand(0);
9611   SDValue Trmp = Op.getOperand(1); // trampoline
9612   SDValue FPtr = Op.getOperand(2); // nested function
9613   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9614   DebugLoc dl  = Op.getDebugLoc();
9615
9616   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9617
9618   if (Subtarget->is64Bit()) {
9619     SDValue OutChains[6];
9620
9621     // Large code-model.
9622     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9623     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9624
9625     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9626     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9627
9628     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9629
9630     // Load the pointer to the nested function into R11.
9631     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9632     SDValue Addr = Trmp;
9633     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9634                                 Addr, MachinePointerInfo(TrmpAddr),
9635                                 false, false, 0);
9636
9637     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9638                        DAG.getConstant(2, MVT::i64));
9639     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9640                                 MachinePointerInfo(TrmpAddr, 2),
9641                                 false, false, 2);
9642
9643     // Load the 'nest' parameter value into R10.
9644     // R10 is specified in X86CallingConv.td
9645     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9646     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9647                        DAG.getConstant(10, MVT::i64));
9648     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9649                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9650                                 false, false, 0);
9651
9652     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9653                        DAG.getConstant(12, MVT::i64));
9654     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9655                                 MachinePointerInfo(TrmpAddr, 12),
9656                                 false, false, 2);
9657
9658     // Jump to the nested function.
9659     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9661                        DAG.getConstant(20, MVT::i64));
9662     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9663                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9664                                 false, false, 0);
9665
9666     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9667     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9668                        DAG.getConstant(22, MVT::i64));
9669     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9670                                 MachinePointerInfo(TrmpAddr, 22),
9671                                 false, false, 0);
9672
9673     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9674   } else {
9675     const Function *Func =
9676       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9677     CallingConv::ID CC = Func->getCallingConv();
9678     unsigned NestReg;
9679
9680     switch (CC) {
9681     default:
9682       llvm_unreachable("Unsupported calling convention");
9683     case CallingConv::C:
9684     case CallingConv::X86_StdCall: {
9685       // Pass 'nest' parameter in ECX.
9686       // Must be kept in sync with X86CallingConv.td
9687       NestReg = X86::ECX;
9688
9689       // Check that ECX wasn't needed by an 'inreg' parameter.
9690       FunctionType *FTy = Func->getFunctionType();
9691       const AttrListPtr &Attrs = Func->getAttributes();
9692
9693       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9694         unsigned InRegCount = 0;
9695         unsigned Idx = 1;
9696
9697         for (FunctionType::param_iterator I = FTy->param_begin(),
9698              E = FTy->param_end(); I != E; ++I, ++Idx)
9699           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9700             // FIXME: should only count parameters that are lowered to integers.
9701             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9702
9703         if (InRegCount > 2) {
9704           report_fatal_error("Nest register in use - reduce number of inreg"
9705                              " parameters!");
9706         }
9707       }
9708       break;
9709     }
9710     case CallingConv::X86_FastCall:
9711     case CallingConv::X86_ThisCall:
9712     case CallingConv::Fast:
9713       // Pass 'nest' parameter in EAX.
9714       // Must be kept in sync with X86CallingConv.td
9715       NestReg = X86::EAX;
9716       break;
9717     }
9718
9719     SDValue OutChains[4];
9720     SDValue Addr, Disp;
9721
9722     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9723                        DAG.getConstant(10, MVT::i32));
9724     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9725
9726     // This is storing the opcode for MOV32ri.
9727     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9728     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9729     OutChains[0] = DAG.getStore(Root, dl,
9730                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9731                                 Trmp, MachinePointerInfo(TrmpAddr),
9732                                 false, false, 0);
9733
9734     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9735                        DAG.getConstant(1, MVT::i32));
9736     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9737                                 MachinePointerInfo(TrmpAddr, 1),
9738                                 false, false, 1);
9739
9740     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9741     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9742                        DAG.getConstant(5, MVT::i32));
9743     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9744                                 MachinePointerInfo(TrmpAddr, 5),
9745                                 false, false, 1);
9746
9747     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9748                        DAG.getConstant(6, MVT::i32));
9749     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9750                                 MachinePointerInfo(TrmpAddr, 6),
9751                                 false, false, 1);
9752
9753     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9754   }
9755 }
9756
9757 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9758                                             SelectionDAG &DAG) const {
9759   /*
9760    The rounding mode is in bits 11:10 of FPSR, and has the following
9761    settings:
9762      00 Round to nearest
9763      01 Round to -inf
9764      10 Round to +inf
9765      11 Round to 0
9766
9767   FLT_ROUNDS, on the other hand, expects the following:
9768     -1 Undefined
9769      0 Round to 0
9770      1 Round to nearest
9771      2 Round to +inf
9772      3 Round to -inf
9773
9774   To perform the conversion, we do:
9775     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9776   */
9777
9778   MachineFunction &MF = DAG.getMachineFunction();
9779   const TargetMachine &TM = MF.getTarget();
9780   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9781   unsigned StackAlignment = TFI.getStackAlignment();
9782   EVT VT = Op.getValueType();
9783   DebugLoc DL = Op.getDebugLoc();
9784
9785   // Save FP Control Word to stack slot
9786   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9787   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9788
9789
9790   MachineMemOperand *MMO =
9791    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9792                            MachineMemOperand::MOStore, 2, 2);
9793
9794   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9795   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9796                                           DAG.getVTList(MVT::Other),
9797                                           Ops, 2, MVT::i16, MMO);
9798
9799   // Load FP Control Word from stack slot
9800   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9801                             MachinePointerInfo(), false, false, false, 0);
9802
9803   // Transform as necessary
9804   SDValue CWD1 =
9805     DAG.getNode(ISD::SRL, DL, MVT::i16,
9806                 DAG.getNode(ISD::AND, DL, MVT::i16,
9807                             CWD, DAG.getConstant(0x800, MVT::i16)),
9808                 DAG.getConstant(11, MVT::i8));
9809   SDValue CWD2 =
9810     DAG.getNode(ISD::SRL, DL, MVT::i16,
9811                 DAG.getNode(ISD::AND, DL, MVT::i16,
9812                             CWD, DAG.getConstant(0x400, MVT::i16)),
9813                 DAG.getConstant(9, MVT::i8));
9814
9815   SDValue RetVal =
9816     DAG.getNode(ISD::AND, DL, MVT::i16,
9817                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9818                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9819                             DAG.getConstant(1, MVT::i16)),
9820                 DAG.getConstant(3, MVT::i16));
9821
9822
9823   return DAG.getNode((VT.getSizeInBits() < 16 ?
9824                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9825 }
9826
9827 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9828   EVT VT = Op.getValueType();
9829   EVT OpVT = VT;
9830   unsigned NumBits = VT.getSizeInBits();
9831   DebugLoc dl = Op.getDebugLoc();
9832
9833   Op = Op.getOperand(0);
9834   if (VT == MVT::i8) {
9835     // Zero extend to i32 since there is not an i8 bsr.
9836     OpVT = MVT::i32;
9837     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9838   }
9839
9840   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9841   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9842   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9843
9844   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9845   SDValue Ops[] = {
9846     Op,
9847     DAG.getConstant(NumBits+NumBits-1, OpVT),
9848     DAG.getConstant(X86::COND_E, MVT::i8),
9849     Op.getValue(1)
9850   };
9851   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9852
9853   // Finally xor with NumBits-1.
9854   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9855
9856   if (VT == MVT::i8)
9857     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9858   return Op;
9859 }
9860
9861 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
9862                                                 SelectionDAG &DAG) const {
9863   EVT VT = Op.getValueType();
9864   EVT OpVT = VT;
9865   unsigned NumBits = VT.getSizeInBits();
9866   DebugLoc dl = Op.getDebugLoc();
9867
9868   Op = Op.getOperand(0);
9869   if (VT == MVT::i8) {
9870     // Zero extend to i32 since there is not an i8 bsr.
9871     OpVT = MVT::i32;
9872     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9873   }
9874
9875   // Issue a bsr (scan bits in reverse).
9876   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9877   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9878
9879   // And xor with NumBits-1.
9880   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9881
9882   if (VT == MVT::i8)
9883     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9884   return Op;
9885 }
9886
9887 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9888   EVT VT = Op.getValueType();
9889   unsigned NumBits = VT.getSizeInBits();
9890   DebugLoc dl = Op.getDebugLoc();
9891   Op = Op.getOperand(0);
9892
9893   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9894   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9895   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9896
9897   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9898   SDValue Ops[] = {
9899     Op,
9900     DAG.getConstant(NumBits, VT),
9901     DAG.getConstant(X86::COND_E, MVT::i8),
9902     Op.getValue(1)
9903   };
9904   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
9905 }
9906
9907 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9908 // ones, and then concatenate the result back.
9909 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9910   EVT VT = Op.getValueType();
9911
9912   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9913          "Unsupported value type for operation");
9914
9915   int NumElems = VT.getVectorNumElements();
9916   DebugLoc dl = Op.getDebugLoc();
9917   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9918   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9919
9920   // Extract the LHS vectors
9921   SDValue LHS = Op.getOperand(0);
9922   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9923   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9924
9925   // Extract the RHS vectors
9926   SDValue RHS = Op.getOperand(1);
9927   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9928   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9929
9930   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9931   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9932
9933   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9934                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9935                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9936 }
9937
9938 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9939   assert(Op.getValueType().getSizeInBits() == 256 &&
9940          Op.getValueType().isInteger() &&
9941          "Only handle AVX 256-bit vector integer operation");
9942   return Lower256IntArith(Op, DAG);
9943 }
9944
9945 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9946   assert(Op.getValueType().getSizeInBits() == 256 &&
9947          Op.getValueType().isInteger() &&
9948          "Only handle AVX 256-bit vector integer operation");
9949   return Lower256IntArith(Op, DAG);
9950 }
9951
9952 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9953   EVT VT = Op.getValueType();
9954
9955   // Decompose 256-bit ops into smaller 128-bit ops.
9956   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
9957     return Lower256IntArith(Op, DAG);
9958
9959   DebugLoc dl = Op.getDebugLoc();
9960
9961   SDValue A = Op.getOperand(0);
9962   SDValue B = Op.getOperand(1);
9963
9964   if (VT == MVT::v4i64) {
9965     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
9966
9967     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
9968     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
9969     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
9970     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
9971     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
9972     //
9973     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
9974     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
9975     //  return AloBlo + AloBhi + AhiBlo;
9976
9977     SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A,
9978                               DAG.getConstant(32, MVT::i32));
9979     SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B,
9980                               DAG.getConstant(32, MVT::i32));
9981     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9982                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9983                          A, B);
9984     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9985                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9986                          A, Bhi);
9987     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9988                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
9989                          Ahi, B);
9990     AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi,
9991                          DAG.getConstant(32, MVT::i32));
9992     AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo,
9993                          DAG.getConstant(32, MVT::i32));
9994     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9995     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9996     return Res;
9997   }
9998
9999   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10000
10001   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10002   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10003   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10004   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10005   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10006   //
10007   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10008   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10009   //  return AloBlo + AloBhi + AhiBlo;
10010
10011   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A,
10012                             DAG.getConstant(32, MVT::i32));
10013   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B,
10014                             DAG.getConstant(32, MVT::i32));
10015   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10016                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10017                        A, B);
10018   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10019                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10020                        A, Bhi);
10021   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10022                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10023                        Ahi, B);
10024   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi,
10025                        DAG.getConstant(32, MVT::i32));
10026   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo,
10027                        DAG.getConstant(32, MVT::i32));
10028   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10029   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10030   return Res;
10031 }
10032
10033 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10034
10035   EVT VT = Op.getValueType();
10036   DebugLoc dl = Op.getDebugLoc();
10037   SDValue R = Op.getOperand(0);
10038   SDValue Amt = Op.getOperand(1);
10039   LLVMContext *Context = DAG.getContext();
10040
10041   if (!Subtarget->hasSSE2())
10042     return SDValue();
10043
10044   // Optimize shl/srl/sra with constant shift amount.
10045   if (isSplatVector(Amt.getNode())) {
10046     SDValue SclrAmt = Amt->getOperand(0);
10047     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10048       uint64_t ShiftAmt = C->getZExtValue();
10049
10050       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10051           (Subtarget->hasAVX2() &&
10052            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10053         if (Op.getOpcode() == ISD::SHL)
10054           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10055                              DAG.getConstant(ShiftAmt, MVT::i32));
10056         if (Op.getOpcode() == ISD::SRL)
10057           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10058                              DAG.getConstant(ShiftAmt, MVT::i32));
10059         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10060           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10061                              DAG.getConstant(ShiftAmt, MVT::i32));
10062       }
10063
10064       if (VT == MVT::v16i8) {
10065         if (Op.getOpcode() == ISD::SHL) {
10066           // Make a large shift.
10067           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10068                                     DAG.getConstant(ShiftAmt, MVT::i32));
10069           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10070           // Zero out the rightmost bits.
10071           SmallVector<SDValue, 16> V(16,
10072                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10073                                                      MVT::i8));
10074           return DAG.getNode(ISD::AND, dl, VT, SHL,
10075                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10076         }
10077         if (Op.getOpcode() == ISD::SRL) {
10078           // Make a large shift.
10079           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10080                                     DAG.getConstant(ShiftAmt, MVT::i32));
10081           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10082           // Zero out the leftmost bits.
10083           SmallVector<SDValue, 16> V(16,
10084                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10085                                                      MVT::i8));
10086           return DAG.getNode(ISD::AND, dl, VT, SRL,
10087                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10088         }
10089         if (Op.getOpcode() == ISD::SRA) {
10090           if (ShiftAmt == 7) {
10091             // R s>> 7  ===  R s< 0
10092             SDValue Zeros = getZeroVector(VT, /* HasSSE2 */true,
10093                                           /* HasAVX2 */false, DAG, dl);
10094             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10095           }
10096
10097           // R s>> a === ((R u>> a) ^ m) - m
10098           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10099           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10100                                                          MVT::i8));
10101           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10102           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10103           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10104           return Res;
10105         }
10106       }
10107
10108       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10109         if (Op.getOpcode() == ISD::SHL) {
10110           // Make a large shift.
10111           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10112                                     DAG.getConstant(ShiftAmt, MVT::i32));
10113           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10114           // Zero out the rightmost bits.
10115           SmallVector<SDValue, 32> V(32,
10116                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10117                                                      MVT::i8));
10118           return DAG.getNode(ISD::AND, dl, VT, SHL,
10119                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10120         }
10121         if (Op.getOpcode() == ISD::SRL) {
10122           // Make a large shift.
10123           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10124                                     DAG.getConstant(ShiftAmt, MVT::i32));
10125           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10126           // Zero out the leftmost bits.
10127           SmallVector<SDValue, 32> V(32,
10128                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10129                                                      MVT::i8));
10130           return DAG.getNode(ISD::AND, dl, VT, SRL,
10131                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10132         }
10133         if (Op.getOpcode() == ISD::SRA) {
10134           if (ShiftAmt == 7) {
10135             // R s>> 7  ===  R s< 0
10136             SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */,
10137                                           true /* HasAVX2 */, DAG, dl);
10138             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10139           }
10140
10141           // R s>> a === ((R u>> a) ^ m) - m
10142           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10143           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10144                                                          MVT::i8));
10145           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10146           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10147           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10148           return Res;
10149         }
10150       }
10151     }
10152   }
10153
10154   // Lower SHL with variable shift amount.
10155   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10156     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10157                      DAG.getConstant(23, MVT::i32));
10158
10159     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10160     Constant *C = ConstantVector::getSplat(4, CI);
10161     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10162     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10163                                  MachinePointerInfo::getConstantPool(),
10164                                  false, false, false, 16);
10165
10166     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10167     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10168     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10169     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10170   }
10171   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10172     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10173
10174     // a = a << 5;
10175     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10176                      DAG.getConstant(5, MVT::i32));
10177     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10178
10179     // Turn 'a' into a mask suitable for VSELECT
10180     SDValue VSelM = DAG.getConstant(0x80, VT);
10181     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10182     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10183
10184     SDValue CM1 = DAG.getConstant(0x0f, VT);
10185     SDValue CM2 = DAG.getConstant(0x3f, VT);
10186
10187     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10188     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10189     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10190                             DAG.getConstant(4, MVT::i32), DAG);
10191     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10192     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10193
10194     // a += a
10195     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10196     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10197     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10198
10199     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10200     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10201     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10202                             DAG.getConstant(2, MVT::i32), DAG);
10203     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10204     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10205
10206     // a += a
10207     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10208     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10209     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10210
10211     // return VSELECT(r, r+r, a);
10212     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10213                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10214     return R;
10215   }
10216
10217   // Decompose 256-bit shifts into smaller 128-bit shifts.
10218   if (VT.getSizeInBits() == 256) {
10219     unsigned NumElems = VT.getVectorNumElements();
10220     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10221     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10222
10223     // Extract the two vectors
10224     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10225     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10226                                      DAG, dl);
10227
10228     // Recreate the shift amount vectors
10229     SDValue Amt1, Amt2;
10230     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10231       // Constant shift amount
10232       SmallVector<SDValue, 4> Amt1Csts;
10233       SmallVector<SDValue, 4> Amt2Csts;
10234       for (unsigned i = 0; i != NumElems/2; ++i)
10235         Amt1Csts.push_back(Amt->getOperand(i));
10236       for (unsigned i = NumElems/2; i != NumElems; ++i)
10237         Amt2Csts.push_back(Amt->getOperand(i));
10238
10239       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10240                                  &Amt1Csts[0], NumElems/2);
10241       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10242                                  &Amt2Csts[0], NumElems/2);
10243     } else {
10244       // Variable shift amount
10245       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10246       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10247                                  DAG, dl);
10248     }
10249
10250     // Issue new vector shifts for the smaller types
10251     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10252     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10253
10254     // Concatenate the result back
10255     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10256   }
10257
10258   return SDValue();
10259 }
10260
10261 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10262   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10263   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10264   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10265   // has only one use.
10266   SDNode *N = Op.getNode();
10267   SDValue LHS = N->getOperand(0);
10268   SDValue RHS = N->getOperand(1);
10269   unsigned BaseOp = 0;
10270   unsigned Cond = 0;
10271   DebugLoc DL = Op.getDebugLoc();
10272   switch (Op.getOpcode()) {
10273   default: llvm_unreachable("Unknown ovf instruction!");
10274   case ISD::SADDO:
10275     // A subtract of one will be selected as a INC. Note that INC doesn't
10276     // set CF, so we can't do this for UADDO.
10277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10278       if (C->isOne()) {
10279         BaseOp = X86ISD::INC;
10280         Cond = X86::COND_O;
10281         break;
10282       }
10283     BaseOp = X86ISD::ADD;
10284     Cond = X86::COND_O;
10285     break;
10286   case ISD::UADDO:
10287     BaseOp = X86ISD::ADD;
10288     Cond = X86::COND_B;
10289     break;
10290   case ISD::SSUBO:
10291     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10292     // set CF, so we can't do this for USUBO.
10293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10294       if (C->isOne()) {
10295         BaseOp = X86ISD::DEC;
10296         Cond = X86::COND_O;
10297         break;
10298       }
10299     BaseOp = X86ISD::SUB;
10300     Cond = X86::COND_O;
10301     break;
10302   case ISD::USUBO:
10303     BaseOp = X86ISD::SUB;
10304     Cond = X86::COND_B;
10305     break;
10306   case ISD::SMULO:
10307     BaseOp = X86ISD::SMUL;
10308     Cond = X86::COND_O;
10309     break;
10310   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10311     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10312                                  MVT::i32);
10313     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10314
10315     SDValue SetCC =
10316       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10317                   DAG.getConstant(X86::COND_O, MVT::i32),
10318                   SDValue(Sum.getNode(), 2));
10319
10320     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10321   }
10322   }
10323
10324   // Also sets EFLAGS.
10325   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10326   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10327
10328   SDValue SetCC =
10329     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10330                 DAG.getConstant(Cond, MVT::i32),
10331                 SDValue(Sum.getNode(), 1));
10332
10333   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10334 }
10335
10336 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10337                                                   SelectionDAG &DAG) const {
10338   DebugLoc dl = Op.getDebugLoc();
10339   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10340   EVT VT = Op.getValueType();
10341
10342   if (!Subtarget->hasSSE2() || !VT.isVector())
10343     return SDValue();
10344
10345   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10346                       ExtraVT.getScalarType().getSizeInBits();
10347   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10348
10349   switch (VT.getSimpleVT().SimpleTy) {
10350     default: return SDValue();
10351     case MVT::v8i32:
10352     case MVT::v16i16:
10353       if (!Subtarget->hasAVX())
10354         return SDValue();
10355       if (!Subtarget->hasAVX2()) {
10356         // needs to be split
10357         int NumElems = VT.getVectorNumElements();
10358         SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10359         SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10360
10361         // Extract the LHS vectors
10362         SDValue LHS = Op.getOperand(0);
10363         SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10364         SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10365
10366         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10367         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10368
10369         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10370         int ExtraNumElems = ExtraVT.getVectorNumElements();
10371         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10372                                    ExtraNumElems/2);
10373         SDValue Extra = DAG.getValueType(ExtraVT);
10374
10375         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10376         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10377
10378         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10379       }
10380       // fall through
10381     case MVT::v4i32:
10382     case MVT::v8i16: {
10383       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10384                                          Op.getOperand(0), ShAmt, DAG);
10385       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10386     }
10387   }
10388 }
10389
10390
10391 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10392   DebugLoc dl = Op.getDebugLoc();
10393
10394   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10395   // There isn't any reason to disable it if the target processor supports it.
10396   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10397     SDValue Chain = Op.getOperand(0);
10398     SDValue Zero = DAG.getConstant(0, MVT::i32);
10399     SDValue Ops[] = {
10400       DAG.getRegister(X86::ESP, MVT::i32), // Base
10401       DAG.getTargetConstant(1, MVT::i8),   // Scale
10402       DAG.getRegister(0, MVT::i32),        // Index
10403       DAG.getTargetConstant(0, MVT::i32),  // Disp
10404       DAG.getRegister(0, MVT::i32),        // Segment.
10405       Zero,
10406       Chain
10407     };
10408     SDNode *Res =
10409       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10410                           array_lengthof(Ops));
10411     return SDValue(Res, 0);
10412   }
10413
10414   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10415   if (!isDev)
10416     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10417
10418   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10419   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10420   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10421   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10422
10423   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10424   if (!Op1 && !Op2 && !Op3 && Op4)
10425     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10426
10427   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10428   if (Op1 && !Op2 && !Op3 && !Op4)
10429     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10430
10431   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10432   //           (MFENCE)>;
10433   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10434 }
10435
10436 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10437                                              SelectionDAG &DAG) const {
10438   DebugLoc dl = Op.getDebugLoc();
10439   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10440     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10441   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10442     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10443
10444   // The only fence that needs an instruction is a sequentially-consistent
10445   // cross-thread fence.
10446   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10447     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10448     // no-sse2). There isn't any reason to disable it if the target processor
10449     // supports it.
10450     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10451       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10452
10453     SDValue Chain = Op.getOperand(0);
10454     SDValue Zero = DAG.getConstant(0, MVT::i32);
10455     SDValue Ops[] = {
10456       DAG.getRegister(X86::ESP, MVT::i32), // Base
10457       DAG.getTargetConstant(1, MVT::i8),   // Scale
10458       DAG.getRegister(0, MVT::i32),        // Index
10459       DAG.getTargetConstant(0, MVT::i32),  // Disp
10460       DAG.getRegister(0, MVT::i32),        // Segment.
10461       Zero,
10462       Chain
10463     };
10464     SDNode *Res =
10465       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10466                          array_lengthof(Ops));
10467     return SDValue(Res, 0);
10468   }
10469
10470   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10471   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10472 }
10473
10474
10475 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10476   EVT T = Op.getValueType();
10477   DebugLoc DL = Op.getDebugLoc();
10478   unsigned Reg = 0;
10479   unsigned size = 0;
10480   switch(T.getSimpleVT().SimpleTy) {
10481   default:
10482     assert(false && "Invalid value type!");
10483   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10484   case MVT::i16: Reg = X86::AX;  size = 2; break;
10485   case MVT::i32: Reg = X86::EAX; size = 4; break;
10486   case MVT::i64:
10487     assert(Subtarget->is64Bit() && "Node not type legal!");
10488     Reg = X86::RAX; size = 8;
10489     break;
10490   }
10491   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10492                                     Op.getOperand(2), SDValue());
10493   SDValue Ops[] = { cpIn.getValue(0),
10494                     Op.getOperand(1),
10495                     Op.getOperand(3),
10496                     DAG.getTargetConstant(size, MVT::i8),
10497                     cpIn.getValue(1) };
10498   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10499   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10500   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10501                                            Ops, 5, T, MMO);
10502   SDValue cpOut =
10503     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10504   return cpOut;
10505 }
10506
10507 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10508                                                  SelectionDAG &DAG) const {
10509   assert(Subtarget->is64Bit() && "Result not type legalized?");
10510   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10511   SDValue TheChain = Op.getOperand(0);
10512   DebugLoc dl = Op.getDebugLoc();
10513   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10514   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10515   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10516                                    rax.getValue(2));
10517   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10518                             DAG.getConstant(32, MVT::i8));
10519   SDValue Ops[] = {
10520     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10521     rdx.getValue(1)
10522   };
10523   return DAG.getMergeValues(Ops, 2, dl);
10524 }
10525
10526 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10527                                             SelectionDAG &DAG) const {
10528   EVT SrcVT = Op.getOperand(0).getValueType();
10529   EVT DstVT = Op.getValueType();
10530   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10531          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10532   assert((DstVT == MVT::i64 ||
10533           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10534          "Unexpected custom BITCAST");
10535   // i64 <=> MMX conversions are Legal.
10536   if (SrcVT==MVT::i64 && DstVT.isVector())
10537     return Op;
10538   if (DstVT==MVT::i64 && SrcVT.isVector())
10539     return Op;
10540   // MMX <=> MMX conversions are Legal.
10541   if (SrcVT.isVector() && DstVT.isVector())
10542     return Op;
10543   // All other conversions need to be expanded.
10544   return SDValue();
10545 }
10546
10547 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10548   SDNode *Node = Op.getNode();
10549   DebugLoc dl = Node->getDebugLoc();
10550   EVT T = Node->getValueType(0);
10551   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10552                               DAG.getConstant(0, T), Node->getOperand(2));
10553   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10554                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10555                        Node->getOperand(0),
10556                        Node->getOperand(1), negOp,
10557                        cast<AtomicSDNode>(Node)->getSrcValue(),
10558                        cast<AtomicSDNode>(Node)->getAlignment(),
10559                        cast<AtomicSDNode>(Node)->getOrdering(),
10560                        cast<AtomicSDNode>(Node)->getSynchScope());
10561 }
10562
10563 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10564   SDNode *Node = Op.getNode();
10565   DebugLoc dl = Node->getDebugLoc();
10566   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10567
10568   // Convert seq_cst store -> xchg
10569   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10570   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10571   //        (The only way to get a 16-byte store is cmpxchg16b)
10572   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10573   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10574       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10575     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10576                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10577                                  Node->getOperand(0),
10578                                  Node->getOperand(1), Node->getOperand(2),
10579                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10580                                  cast<AtomicSDNode>(Node)->getOrdering(),
10581                                  cast<AtomicSDNode>(Node)->getSynchScope());
10582     return Swap.getValue(1);
10583   }
10584   // Other atomic stores have a simple pattern.
10585   return Op;
10586 }
10587
10588 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10589   EVT VT = Op.getNode()->getValueType(0);
10590
10591   // Let legalize expand this if it isn't a legal type yet.
10592   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10593     return SDValue();
10594
10595   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10596
10597   unsigned Opc;
10598   bool ExtraOp = false;
10599   switch (Op.getOpcode()) {
10600   default: assert(0 && "Invalid code");
10601   case ISD::ADDC: Opc = X86ISD::ADD; break;
10602   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10603   case ISD::SUBC: Opc = X86ISD::SUB; break;
10604   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10605   }
10606
10607   if (!ExtraOp)
10608     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10609                        Op.getOperand(1));
10610   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10611                      Op.getOperand(1), Op.getOperand(2));
10612 }
10613
10614 /// LowerOperation - Provide custom lowering hooks for some operations.
10615 ///
10616 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10617   switch (Op.getOpcode()) {
10618   default: llvm_unreachable("Should not custom lower this!");
10619   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10620   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10621   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10622   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10623   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10624   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10625   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10626   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10627   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10628   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10629   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10630   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10631   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10632   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10633   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10634   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10635   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10636   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10637   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10638   case ISD::SHL_PARTS:
10639   case ISD::SRA_PARTS:
10640   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10641   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10642   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10643   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10644   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10645   case ISD::FABS:               return LowerFABS(Op, DAG);
10646   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10647   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10648   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10649   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10650   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10651   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10652   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10653   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10654   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10655   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10656   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10657   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10658   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10659   case ISD::FRAME_TO_ARGS_OFFSET:
10660                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10661   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10662   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10663   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10664   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10665   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10666   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10667   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10668   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10669   case ISD::MUL:                return LowerMUL(Op, DAG);
10670   case ISD::SRA:
10671   case ISD::SRL:
10672   case ISD::SHL:                return LowerShift(Op, DAG);
10673   case ISD::SADDO:
10674   case ISD::UADDO:
10675   case ISD::SSUBO:
10676   case ISD::USUBO:
10677   case ISD::SMULO:
10678   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10679   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10680   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10681   case ISD::ADDC:
10682   case ISD::ADDE:
10683   case ISD::SUBC:
10684   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10685   case ISD::ADD:                return LowerADD(Op, DAG);
10686   case ISD::SUB:                return LowerSUB(Op, DAG);
10687   }
10688 }
10689
10690 static void ReplaceATOMIC_LOAD(SDNode *Node,
10691                                   SmallVectorImpl<SDValue> &Results,
10692                                   SelectionDAG &DAG) {
10693   DebugLoc dl = Node->getDebugLoc();
10694   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10695
10696   // Convert wide load -> cmpxchg8b/cmpxchg16b
10697   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10698   //        (The only way to get a 16-byte load is cmpxchg16b)
10699   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10700   SDValue Zero = DAG.getConstant(0, VT);
10701   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10702                                Node->getOperand(0),
10703                                Node->getOperand(1), Zero, Zero,
10704                                cast<AtomicSDNode>(Node)->getMemOperand(),
10705                                cast<AtomicSDNode>(Node)->getOrdering(),
10706                                cast<AtomicSDNode>(Node)->getSynchScope());
10707   Results.push_back(Swap.getValue(0));
10708   Results.push_back(Swap.getValue(1));
10709 }
10710
10711 void X86TargetLowering::
10712 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10713                         SelectionDAG &DAG, unsigned NewOp) const {
10714   DebugLoc dl = Node->getDebugLoc();
10715   assert (Node->getValueType(0) == MVT::i64 &&
10716           "Only know how to expand i64 atomics");
10717
10718   SDValue Chain = Node->getOperand(0);
10719   SDValue In1 = Node->getOperand(1);
10720   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10721                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10722   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10723                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10724   SDValue Ops[] = { Chain, In1, In2L, In2H };
10725   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10726   SDValue Result =
10727     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10728                             cast<MemSDNode>(Node)->getMemOperand());
10729   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10730   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10731   Results.push_back(Result.getValue(2));
10732 }
10733
10734 /// ReplaceNodeResults - Replace a node with an illegal result type
10735 /// with a new node built out of custom code.
10736 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10737                                            SmallVectorImpl<SDValue>&Results,
10738                                            SelectionDAG &DAG) const {
10739   DebugLoc dl = N->getDebugLoc();
10740   switch (N->getOpcode()) {
10741   default:
10742     assert(false && "Do not know how to custom type legalize this operation!");
10743     return;
10744   case ISD::SIGN_EXTEND_INREG:
10745   case ISD::ADDC:
10746   case ISD::ADDE:
10747   case ISD::SUBC:
10748   case ISD::SUBE:
10749     // We don't want to expand or promote these.
10750     return;
10751   case ISD::FP_TO_SINT: {
10752     std::pair<SDValue,SDValue> Vals =
10753         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10754     SDValue FIST = Vals.first, StackSlot = Vals.second;
10755     if (FIST.getNode() != 0) {
10756       EVT VT = N->getValueType(0);
10757       // Return a load from the stack slot.
10758       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10759                                     MachinePointerInfo(), 
10760                                     false, false, false, 0));
10761     }
10762     return;
10763   }
10764   case ISD::READCYCLECOUNTER: {
10765     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10766     SDValue TheChain = N->getOperand(0);
10767     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10768     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10769                                      rd.getValue(1));
10770     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10771                                      eax.getValue(2));
10772     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10773     SDValue Ops[] = { eax, edx };
10774     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10775     Results.push_back(edx.getValue(1));
10776     return;
10777   }
10778   case ISD::ATOMIC_CMP_SWAP: {
10779     EVT T = N->getValueType(0);
10780     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10781     bool Regs64bit = T == MVT::i128;
10782     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10783     SDValue cpInL, cpInH;
10784     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10785                         DAG.getConstant(0, HalfT));
10786     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10787                         DAG.getConstant(1, HalfT));
10788     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10789                              Regs64bit ? X86::RAX : X86::EAX,
10790                              cpInL, SDValue());
10791     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10792                              Regs64bit ? X86::RDX : X86::EDX,
10793                              cpInH, cpInL.getValue(1));
10794     SDValue swapInL, swapInH;
10795     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10796                           DAG.getConstant(0, HalfT));
10797     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10798                           DAG.getConstant(1, HalfT));
10799     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10800                                Regs64bit ? X86::RBX : X86::EBX,
10801                                swapInL, cpInH.getValue(1));
10802     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10803                                Regs64bit ? X86::RCX : X86::ECX, 
10804                                swapInH, swapInL.getValue(1));
10805     SDValue Ops[] = { swapInH.getValue(0),
10806                       N->getOperand(1),
10807                       swapInH.getValue(1) };
10808     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10809     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10810     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10811                                   X86ISD::LCMPXCHG8_DAG;
10812     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10813                                              Ops, 3, T, MMO);
10814     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10815                                         Regs64bit ? X86::RAX : X86::EAX,
10816                                         HalfT, Result.getValue(1));
10817     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10818                                         Regs64bit ? X86::RDX : X86::EDX,
10819                                         HalfT, cpOutL.getValue(2));
10820     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10821     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10822     Results.push_back(cpOutH.getValue(1));
10823     return;
10824   }
10825   case ISD::ATOMIC_LOAD_ADD:
10826     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10827     return;
10828   case ISD::ATOMIC_LOAD_AND:
10829     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10830     return;
10831   case ISD::ATOMIC_LOAD_NAND:
10832     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10833     return;
10834   case ISD::ATOMIC_LOAD_OR:
10835     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10836     return;
10837   case ISD::ATOMIC_LOAD_SUB:
10838     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10839     return;
10840   case ISD::ATOMIC_LOAD_XOR:
10841     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10842     return;
10843   case ISD::ATOMIC_SWAP:
10844     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10845     return;
10846   case ISD::ATOMIC_LOAD:
10847     ReplaceATOMIC_LOAD(N, Results, DAG);
10848   }
10849 }
10850
10851 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10852   switch (Opcode) {
10853   default: return NULL;
10854   case X86ISD::BSF:                return "X86ISD::BSF";
10855   case X86ISD::BSR:                return "X86ISD::BSR";
10856   case X86ISD::SHLD:               return "X86ISD::SHLD";
10857   case X86ISD::SHRD:               return "X86ISD::SHRD";
10858   case X86ISD::FAND:               return "X86ISD::FAND";
10859   case X86ISD::FOR:                return "X86ISD::FOR";
10860   case X86ISD::FXOR:               return "X86ISD::FXOR";
10861   case X86ISD::FSRL:               return "X86ISD::FSRL";
10862   case X86ISD::FILD:               return "X86ISD::FILD";
10863   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10864   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10865   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10866   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10867   case X86ISD::FLD:                return "X86ISD::FLD";
10868   case X86ISD::FST:                return "X86ISD::FST";
10869   case X86ISD::CALL:               return "X86ISD::CALL";
10870   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10871   case X86ISD::BT:                 return "X86ISD::BT";
10872   case X86ISD::CMP:                return "X86ISD::CMP";
10873   case X86ISD::COMI:               return "X86ISD::COMI";
10874   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10875   case X86ISD::SETCC:              return "X86ISD::SETCC";
10876   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10877   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10878   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10879   case X86ISD::CMOV:               return "X86ISD::CMOV";
10880   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10881   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10882   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10883   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10884   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10885   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10886   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10887   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10888   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10889   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10890   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10891   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10892   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10893   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10894   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
10895   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
10896   case X86ISD::HADD:               return "X86ISD::HADD";
10897   case X86ISD::HSUB:               return "X86ISD::HSUB";
10898   case X86ISD::FHADD:              return "X86ISD::FHADD";
10899   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10900   case X86ISD::FMAX:               return "X86ISD::FMAX";
10901   case X86ISD::FMIN:               return "X86ISD::FMIN";
10902   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10903   case X86ISD::FRCP:               return "X86ISD::FRCP";
10904   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10905   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10906   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10907   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10908   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10909   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10910   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10911   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10912   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10913   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10914   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10915   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10916   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10917   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10918   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10919   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
10920   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
10921   case X86ISD::VSHL:               return "X86ISD::VSHL";
10922   case X86ISD::VSRL:               return "X86ISD::VSRL";
10923   case X86ISD::VSRA:               return "X86ISD::VSRA";
10924   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
10925   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
10926   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
10927   case X86ISD::CMPP:               return "X86ISD::CMPP";
10928   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
10929   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
10930   case X86ISD::ADD:                return "X86ISD::ADD";
10931   case X86ISD::SUB:                return "X86ISD::SUB";
10932   case X86ISD::ADC:                return "X86ISD::ADC";
10933   case X86ISD::SBB:                return "X86ISD::SBB";
10934   case X86ISD::SMUL:               return "X86ISD::SMUL";
10935   case X86ISD::UMUL:               return "X86ISD::UMUL";
10936   case X86ISD::INC:                return "X86ISD::INC";
10937   case X86ISD::DEC:                return "X86ISD::DEC";
10938   case X86ISD::OR:                 return "X86ISD::OR";
10939   case X86ISD::XOR:                return "X86ISD::XOR";
10940   case X86ISD::AND:                return "X86ISD::AND";
10941   case X86ISD::ANDN:               return "X86ISD::ANDN";
10942   case X86ISD::BLSI:               return "X86ISD::BLSI";
10943   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
10944   case X86ISD::BLSR:               return "X86ISD::BLSR";
10945   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10946   case X86ISD::PTEST:              return "X86ISD::PTEST";
10947   case X86ISD::TESTP:              return "X86ISD::TESTP";
10948   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10949   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10950   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10951   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10952   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
10953   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10954   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10955   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10956   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10957   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10958   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10959   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10960   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10961   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10962   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10963   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
10964   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
10965   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10966   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
10967   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
10968   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10969   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10970   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10971   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10972   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10973   }
10974 }
10975
10976 // isLegalAddressingMode - Return true if the addressing mode represented
10977 // by AM is legal for this target, for a load/store of the specified type.
10978 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10979                                               Type *Ty) const {
10980   // X86 supports extremely general addressing modes.
10981   CodeModel::Model M = getTargetMachine().getCodeModel();
10982   Reloc::Model R = getTargetMachine().getRelocationModel();
10983
10984   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10985   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10986     return false;
10987
10988   if (AM.BaseGV) {
10989     unsigned GVFlags =
10990       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10991
10992     // If a reference to this global requires an extra load, we can't fold it.
10993     if (isGlobalStubReference(GVFlags))
10994       return false;
10995
10996     // If BaseGV requires a register for the PIC base, we cannot also have a
10997     // BaseReg specified.
10998     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10999       return false;
11000
11001     // If lower 4G is not available, then we must use rip-relative addressing.
11002     if ((M != CodeModel::Small || R != Reloc::Static) &&
11003         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11004       return false;
11005   }
11006
11007   switch (AM.Scale) {
11008   case 0:
11009   case 1:
11010   case 2:
11011   case 4:
11012   case 8:
11013     // These scales always work.
11014     break;
11015   case 3:
11016   case 5:
11017   case 9:
11018     // These scales are formed with basereg+scalereg.  Only accept if there is
11019     // no basereg yet.
11020     if (AM.HasBaseReg)
11021       return false;
11022     break;
11023   default:  // Other stuff never works.
11024     return false;
11025   }
11026
11027   return true;
11028 }
11029
11030
11031 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11032   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11033     return false;
11034   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11035   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11036   if (NumBits1 <= NumBits2)
11037     return false;
11038   return true;
11039 }
11040
11041 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11042   if (!VT1.isInteger() || !VT2.isInteger())
11043     return false;
11044   unsigned NumBits1 = VT1.getSizeInBits();
11045   unsigned NumBits2 = VT2.getSizeInBits();
11046   if (NumBits1 <= NumBits2)
11047     return false;
11048   return true;
11049 }
11050
11051 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11052   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11053   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11054 }
11055
11056 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11057   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11058   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11059 }
11060
11061 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11062   // i16 instructions are longer (0x66 prefix) and potentially slower.
11063   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11064 }
11065
11066 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11067 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11068 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11069 /// are assumed to be legal.
11070 bool
11071 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11072                                       EVT VT) const {
11073   // Very little shuffling can be done for 64-bit vectors right now.
11074   if (VT.getSizeInBits() == 64)
11075     return false;
11076
11077   // FIXME: pshufb, blends, shifts.
11078   return (VT.getVectorNumElements() == 2 ||
11079           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11080           isMOVLMask(M, VT) ||
11081           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11082           isPSHUFDMask(M, VT) ||
11083           isPSHUFHWMask(M, VT) ||
11084           isPSHUFLWMask(M, VT) ||
11085           isPALIGNRMask(M, VT, Subtarget) ||
11086           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11087           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11088           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11089           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11090 }
11091
11092 bool
11093 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11094                                           EVT VT) const {
11095   unsigned NumElts = VT.getVectorNumElements();
11096   // FIXME: This collection of masks seems suspect.
11097   if (NumElts == 2)
11098     return true;
11099   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11100     return (isMOVLMask(Mask, VT)  ||
11101             isCommutedMOVLMask(Mask, VT, true) ||
11102             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11103             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11104   }
11105   return false;
11106 }
11107
11108 //===----------------------------------------------------------------------===//
11109 //                           X86 Scheduler Hooks
11110 //===----------------------------------------------------------------------===//
11111
11112 // private utility function
11113 MachineBasicBlock *
11114 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11115                                                        MachineBasicBlock *MBB,
11116                                                        unsigned regOpc,
11117                                                        unsigned immOpc,
11118                                                        unsigned LoadOpc,
11119                                                        unsigned CXchgOpc,
11120                                                        unsigned notOpc,
11121                                                        unsigned EAXreg,
11122                                                        TargetRegisterClass *RC,
11123                                                        bool invSrc) const {
11124   // For the atomic bitwise operator, we generate
11125   //   thisMBB:
11126   //   newMBB:
11127   //     ld  t1 = [bitinstr.addr]
11128   //     op  t2 = t1, [bitinstr.val]
11129   //     mov EAX = t1
11130   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11131   //     bz  newMBB
11132   //     fallthrough -->nextMBB
11133   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11134   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11135   MachineFunction::iterator MBBIter = MBB;
11136   ++MBBIter;
11137
11138   /// First build the CFG
11139   MachineFunction *F = MBB->getParent();
11140   MachineBasicBlock *thisMBB = MBB;
11141   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11142   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11143   F->insert(MBBIter, newMBB);
11144   F->insert(MBBIter, nextMBB);
11145
11146   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11147   nextMBB->splice(nextMBB->begin(), thisMBB,
11148                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11149                   thisMBB->end());
11150   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11151
11152   // Update thisMBB to fall through to newMBB
11153   thisMBB->addSuccessor(newMBB);
11154
11155   // newMBB jumps to itself and fall through to nextMBB
11156   newMBB->addSuccessor(nextMBB);
11157   newMBB->addSuccessor(newMBB);
11158
11159   // Insert instructions into newMBB based on incoming instruction
11160   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11161          "unexpected number of operands");
11162   DebugLoc dl = bInstr->getDebugLoc();
11163   MachineOperand& destOper = bInstr->getOperand(0);
11164   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11165   int numArgs = bInstr->getNumOperands() - 1;
11166   for (int i=0; i < numArgs; ++i)
11167     argOpers[i] = &bInstr->getOperand(i+1);
11168
11169   // x86 address has 4 operands: base, index, scale, and displacement
11170   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11171   int valArgIndx = lastAddrIndx + 1;
11172
11173   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11174   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11175   for (int i=0; i <= lastAddrIndx; ++i)
11176     (*MIB).addOperand(*argOpers[i]);
11177
11178   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11179   if (invSrc) {
11180     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11181   }
11182   else
11183     tt = t1;
11184
11185   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11186   assert((argOpers[valArgIndx]->isReg() ||
11187           argOpers[valArgIndx]->isImm()) &&
11188          "invalid operand");
11189   if (argOpers[valArgIndx]->isReg())
11190     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11191   else
11192     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11193   MIB.addReg(tt);
11194   (*MIB).addOperand(*argOpers[valArgIndx]);
11195
11196   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11197   MIB.addReg(t1);
11198
11199   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11200   for (int i=0; i <= lastAddrIndx; ++i)
11201     (*MIB).addOperand(*argOpers[i]);
11202   MIB.addReg(t2);
11203   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11204   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11205                     bInstr->memoperands_end());
11206
11207   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11208   MIB.addReg(EAXreg);
11209
11210   // insert branch
11211   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11212
11213   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11214   return nextMBB;
11215 }
11216
11217 // private utility function:  64 bit atomics on 32 bit host.
11218 MachineBasicBlock *
11219 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11220                                                        MachineBasicBlock *MBB,
11221                                                        unsigned regOpcL,
11222                                                        unsigned regOpcH,
11223                                                        unsigned immOpcL,
11224                                                        unsigned immOpcH,
11225                                                        bool invSrc) const {
11226   // For the atomic bitwise operator, we generate
11227   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11228   //     ld t1,t2 = [bitinstr.addr]
11229   //   newMBB:
11230   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11231   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11232   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11233   //     mov ECX, EBX <- t5, t6
11234   //     mov EAX, EDX <- t1, t2
11235   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11236   //     mov t3, t4 <- EAX, EDX
11237   //     bz  newMBB
11238   //     result in out1, out2
11239   //     fallthrough -->nextMBB
11240
11241   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11242   const unsigned LoadOpc = X86::MOV32rm;
11243   const unsigned NotOpc = X86::NOT32r;
11244   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11245   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11246   MachineFunction::iterator MBBIter = MBB;
11247   ++MBBIter;
11248
11249   /// First build the CFG
11250   MachineFunction *F = MBB->getParent();
11251   MachineBasicBlock *thisMBB = MBB;
11252   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11253   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11254   F->insert(MBBIter, newMBB);
11255   F->insert(MBBIter, nextMBB);
11256
11257   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11258   nextMBB->splice(nextMBB->begin(), thisMBB,
11259                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11260                   thisMBB->end());
11261   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11262
11263   // Update thisMBB to fall through to newMBB
11264   thisMBB->addSuccessor(newMBB);
11265
11266   // newMBB jumps to itself and fall through to nextMBB
11267   newMBB->addSuccessor(nextMBB);
11268   newMBB->addSuccessor(newMBB);
11269
11270   DebugLoc dl = bInstr->getDebugLoc();
11271   // Insert instructions into newMBB based on incoming instruction
11272   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11273   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11274          "unexpected number of operands");
11275   MachineOperand& dest1Oper = bInstr->getOperand(0);
11276   MachineOperand& dest2Oper = bInstr->getOperand(1);
11277   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11278   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11279     argOpers[i] = &bInstr->getOperand(i+2);
11280
11281     // We use some of the operands multiple times, so conservatively just
11282     // clear any kill flags that might be present.
11283     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11284       argOpers[i]->setIsKill(false);
11285   }
11286
11287   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11288   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11289
11290   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11291   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11292   for (int i=0; i <= lastAddrIndx; ++i)
11293     (*MIB).addOperand(*argOpers[i]);
11294   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11295   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11296   // add 4 to displacement.
11297   for (int i=0; i <= lastAddrIndx-2; ++i)
11298     (*MIB).addOperand(*argOpers[i]);
11299   MachineOperand newOp3 = *(argOpers[3]);
11300   if (newOp3.isImm())
11301     newOp3.setImm(newOp3.getImm()+4);
11302   else
11303     newOp3.setOffset(newOp3.getOffset()+4);
11304   (*MIB).addOperand(newOp3);
11305   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11306
11307   // t3/4 are defined later, at the bottom of the loop
11308   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11309   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11310   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11311     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11312   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11313     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11314
11315   // The subsequent operations should be using the destination registers of
11316   //the PHI instructions.
11317   if (invSrc) {
11318     t1 = F->getRegInfo().createVirtualRegister(RC);
11319     t2 = F->getRegInfo().createVirtualRegister(RC);
11320     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11321     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11322   } else {
11323     t1 = dest1Oper.getReg();
11324     t2 = dest2Oper.getReg();
11325   }
11326
11327   int valArgIndx = lastAddrIndx + 1;
11328   assert((argOpers[valArgIndx]->isReg() ||
11329           argOpers[valArgIndx]->isImm()) &&
11330          "invalid operand");
11331   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11332   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11333   if (argOpers[valArgIndx]->isReg())
11334     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11335   else
11336     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11337   if (regOpcL != X86::MOV32rr)
11338     MIB.addReg(t1);
11339   (*MIB).addOperand(*argOpers[valArgIndx]);
11340   assert(argOpers[valArgIndx + 1]->isReg() ==
11341          argOpers[valArgIndx]->isReg());
11342   assert(argOpers[valArgIndx + 1]->isImm() ==
11343          argOpers[valArgIndx]->isImm());
11344   if (argOpers[valArgIndx + 1]->isReg())
11345     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11346   else
11347     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11348   if (regOpcH != X86::MOV32rr)
11349     MIB.addReg(t2);
11350   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11351
11352   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11353   MIB.addReg(t1);
11354   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11355   MIB.addReg(t2);
11356
11357   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11358   MIB.addReg(t5);
11359   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11360   MIB.addReg(t6);
11361
11362   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11363   for (int i=0; i <= lastAddrIndx; ++i)
11364     (*MIB).addOperand(*argOpers[i]);
11365
11366   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11367   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11368                     bInstr->memoperands_end());
11369
11370   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11371   MIB.addReg(X86::EAX);
11372   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11373   MIB.addReg(X86::EDX);
11374
11375   // insert branch
11376   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11377
11378   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11379   return nextMBB;
11380 }
11381
11382 // private utility function
11383 MachineBasicBlock *
11384 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11385                                                       MachineBasicBlock *MBB,
11386                                                       unsigned cmovOpc) const {
11387   // For the atomic min/max operator, we generate
11388   //   thisMBB:
11389   //   newMBB:
11390   //     ld t1 = [min/max.addr]
11391   //     mov t2 = [min/max.val]
11392   //     cmp  t1, t2
11393   //     cmov[cond] t2 = t1
11394   //     mov EAX = t1
11395   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11396   //     bz   newMBB
11397   //     fallthrough -->nextMBB
11398   //
11399   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11400   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11401   MachineFunction::iterator MBBIter = MBB;
11402   ++MBBIter;
11403
11404   /// First build the CFG
11405   MachineFunction *F = MBB->getParent();
11406   MachineBasicBlock *thisMBB = MBB;
11407   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11408   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11409   F->insert(MBBIter, newMBB);
11410   F->insert(MBBIter, nextMBB);
11411
11412   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11413   nextMBB->splice(nextMBB->begin(), thisMBB,
11414                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11415                   thisMBB->end());
11416   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11417
11418   // Update thisMBB to fall through to newMBB
11419   thisMBB->addSuccessor(newMBB);
11420
11421   // newMBB jumps to newMBB and fall through to nextMBB
11422   newMBB->addSuccessor(nextMBB);
11423   newMBB->addSuccessor(newMBB);
11424
11425   DebugLoc dl = mInstr->getDebugLoc();
11426   // Insert instructions into newMBB based on incoming instruction
11427   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11428          "unexpected number of operands");
11429   MachineOperand& destOper = mInstr->getOperand(0);
11430   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11431   int numArgs = mInstr->getNumOperands() - 1;
11432   for (int i=0; i < numArgs; ++i)
11433     argOpers[i] = &mInstr->getOperand(i+1);
11434
11435   // x86 address has 4 operands: base, index, scale, and displacement
11436   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11437   int valArgIndx = lastAddrIndx + 1;
11438
11439   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11440   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11441   for (int i=0; i <= lastAddrIndx; ++i)
11442     (*MIB).addOperand(*argOpers[i]);
11443
11444   // We only support register and immediate values
11445   assert((argOpers[valArgIndx]->isReg() ||
11446           argOpers[valArgIndx]->isImm()) &&
11447          "invalid operand");
11448
11449   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11450   if (argOpers[valArgIndx]->isReg())
11451     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11452   else
11453     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11454   (*MIB).addOperand(*argOpers[valArgIndx]);
11455
11456   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11457   MIB.addReg(t1);
11458
11459   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11460   MIB.addReg(t1);
11461   MIB.addReg(t2);
11462
11463   // Generate movc
11464   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11465   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11466   MIB.addReg(t2);
11467   MIB.addReg(t1);
11468
11469   // Cmp and exchange if none has modified the memory location
11470   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11471   for (int i=0; i <= lastAddrIndx; ++i)
11472     (*MIB).addOperand(*argOpers[i]);
11473   MIB.addReg(t3);
11474   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11475   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11476                     mInstr->memoperands_end());
11477
11478   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11479   MIB.addReg(X86::EAX);
11480
11481   // insert branch
11482   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11483
11484   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11485   return nextMBB;
11486 }
11487
11488 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11489 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11490 // in the .td file.
11491 MachineBasicBlock *
11492 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11493                             unsigned numArgs, bool memArg) const {
11494   assert(Subtarget->hasSSE42() &&
11495          "Target must have SSE4.2 or AVX features enabled");
11496
11497   DebugLoc dl = MI->getDebugLoc();
11498   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11499   unsigned Opc;
11500   if (!Subtarget->hasAVX()) {
11501     if (memArg)
11502       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11503     else
11504       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11505   } else {
11506     if (memArg)
11507       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11508     else
11509       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11510   }
11511
11512   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11513   for (unsigned i = 0; i < numArgs; ++i) {
11514     MachineOperand &Op = MI->getOperand(i+1);
11515     if (!(Op.isReg() && Op.isImplicit()))
11516       MIB.addOperand(Op);
11517   }
11518   BuildMI(*BB, MI, dl,
11519     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11520              MI->getOperand(0).getReg())
11521     .addReg(X86::XMM0);
11522
11523   MI->eraseFromParent();
11524   return BB;
11525 }
11526
11527 MachineBasicBlock *
11528 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11529   DebugLoc dl = MI->getDebugLoc();
11530   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11531
11532   // Address into RAX/EAX, other two args into ECX, EDX.
11533   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11534   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11535   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11536   for (int i = 0; i < X86::AddrNumOperands; ++i)
11537     MIB.addOperand(MI->getOperand(i));
11538
11539   unsigned ValOps = X86::AddrNumOperands;
11540   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11541     .addReg(MI->getOperand(ValOps).getReg());
11542   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11543     .addReg(MI->getOperand(ValOps+1).getReg());
11544
11545   // The instruction doesn't actually take any operands though.
11546   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11547
11548   MI->eraseFromParent(); // The pseudo is gone now.
11549   return BB;
11550 }
11551
11552 MachineBasicBlock *
11553 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11554   DebugLoc dl = MI->getDebugLoc();
11555   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11556
11557   // First arg in ECX, the second in EAX.
11558   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11559     .addReg(MI->getOperand(0).getReg());
11560   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11561     .addReg(MI->getOperand(1).getReg());
11562
11563   // The instruction doesn't actually take any operands though.
11564   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11565
11566   MI->eraseFromParent(); // The pseudo is gone now.
11567   return BB;
11568 }
11569
11570 MachineBasicBlock *
11571 X86TargetLowering::EmitVAARG64WithCustomInserter(
11572                    MachineInstr *MI,
11573                    MachineBasicBlock *MBB) const {
11574   // Emit va_arg instruction on X86-64.
11575
11576   // Operands to this pseudo-instruction:
11577   // 0  ) Output        : destination address (reg)
11578   // 1-5) Input         : va_list address (addr, i64mem)
11579   // 6  ) ArgSize       : Size (in bytes) of vararg type
11580   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11581   // 8  ) Align         : Alignment of type
11582   // 9  ) EFLAGS (implicit-def)
11583
11584   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11585   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11586
11587   unsigned DestReg = MI->getOperand(0).getReg();
11588   MachineOperand &Base = MI->getOperand(1);
11589   MachineOperand &Scale = MI->getOperand(2);
11590   MachineOperand &Index = MI->getOperand(3);
11591   MachineOperand &Disp = MI->getOperand(4);
11592   MachineOperand &Segment = MI->getOperand(5);
11593   unsigned ArgSize = MI->getOperand(6).getImm();
11594   unsigned ArgMode = MI->getOperand(7).getImm();
11595   unsigned Align = MI->getOperand(8).getImm();
11596
11597   // Memory Reference
11598   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11599   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11600   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11601
11602   // Machine Information
11603   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11604   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11605   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11606   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11607   DebugLoc DL = MI->getDebugLoc();
11608
11609   // struct va_list {
11610   //   i32   gp_offset
11611   //   i32   fp_offset
11612   //   i64   overflow_area (address)
11613   //   i64   reg_save_area (address)
11614   // }
11615   // sizeof(va_list) = 24
11616   // alignment(va_list) = 8
11617
11618   unsigned TotalNumIntRegs = 6;
11619   unsigned TotalNumXMMRegs = 8;
11620   bool UseGPOffset = (ArgMode == 1);
11621   bool UseFPOffset = (ArgMode == 2);
11622   unsigned MaxOffset = TotalNumIntRegs * 8 +
11623                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11624
11625   /* Align ArgSize to a multiple of 8 */
11626   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11627   bool NeedsAlign = (Align > 8);
11628
11629   MachineBasicBlock *thisMBB = MBB;
11630   MachineBasicBlock *overflowMBB;
11631   MachineBasicBlock *offsetMBB;
11632   MachineBasicBlock *endMBB;
11633
11634   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11635   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11636   unsigned OffsetReg = 0;
11637
11638   if (!UseGPOffset && !UseFPOffset) {
11639     // If we only pull from the overflow region, we don't create a branch.
11640     // We don't need to alter control flow.
11641     OffsetDestReg = 0; // unused
11642     OverflowDestReg = DestReg;
11643
11644     offsetMBB = NULL;
11645     overflowMBB = thisMBB;
11646     endMBB = thisMBB;
11647   } else {
11648     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11649     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11650     // If not, pull from overflow_area. (branch to overflowMBB)
11651     //
11652     //       thisMBB
11653     //         |     .
11654     //         |        .
11655     //     offsetMBB   overflowMBB
11656     //         |        .
11657     //         |     .
11658     //        endMBB
11659
11660     // Registers for the PHI in endMBB
11661     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11662     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11663
11664     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11665     MachineFunction *MF = MBB->getParent();
11666     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11667     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11668     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11669
11670     MachineFunction::iterator MBBIter = MBB;
11671     ++MBBIter;
11672
11673     // Insert the new basic blocks
11674     MF->insert(MBBIter, offsetMBB);
11675     MF->insert(MBBIter, overflowMBB);
11676     MF->insert(MBBIter, endMBB);
11677
11678     // Transfer the remainder of MBB and its successor edges to endMBB.
11679     endMBB->splice(endMBB->begin(), thisMBB,
11680                     llvm::next(MachineBasicBlock::iterator(MI)),
11681                     thisMBB->end());
11682     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11683
11684     // Make offsetMBB and overflowMBB successors of thisMBB
11685     thisMBB->addSuccessor(offsetMBB);
11686     thisMBB->addSuccessor(overflowMBB);
11687
11688     // endMBB is a successor of both offsetMBB and overflowMBB
11689     offsetMBB->addSuccessor(endMBB);
11690     overflowMBB->addSuccessor(endMBB);
11691
11692     // Load the offset value into a register
11693     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11694     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11695       .addOperand(Base)
11696       .addOperand(Scale)
11697       .addOperand(Index)
11698       .addDisp(Disp, UseFPOffset ? 4 : 0)
11699       .addOperand(Segment)
11700       .setMemRefs(MMOBegin, MMOEnd);
11701
11702     // Check if there is enough room left to pull this argument.
11703     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11704       .addReg(OffsetReg)
11705       .addImm(MaxOffset + 8 - ArgSizeA8);
11706
11707     // Branch to "overflowMBB" if offset >= max
11708     // Fall through to "offsetMBB" otherwise
11709     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11710       .addMBB(overflowMBB);
11711   }
11712
11713   // In offsetMBB, emit code to use the reg_save_area.
11714   if (offsetMBB) {
11715     assert(OffsetReg != 0);
11716
11717     // Read the reg_save_area address.
11718     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11719     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11720       .addOperand(Base)
11721       .addOperand(Scale)
11722       .addOperand(Index)
11723       .addDisp(Disp, 16)
11724       .addOperand(Segment)
11725       .setMemRefs(MMOBegin, MMOEnd);
11726
11727     // Zero-extend the offset
11728     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11729       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11730         .addImm(0)
11731         .addReg(OffsetReg)
11732         .addImm(X86::sub_32bit);
11733
11734     // Add the offset to the reg_save_area to get the final address.
11735     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11736       .addReg(OffsetReg64)
11737       .addReg(RegSaveReg);
11738
11739     // Compute the offset for the next argument
11740     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11741     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11742       .addReg(OffsetReg)
11743       .addImm(UseFPOffset ? 16 : 8);
11744
11745     // Store it back into the va_list.
11746     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11747       .addOperand(Base)
11748       .addOperand(Scale)
11749       .addOperand(Index)
11750       .addDisp(Disp, UseFPOffset ? 4 : 0)
11751       .addOperand(Segment)
11752       .addReg(NextOffsetReg)
11753       .setMemRefs(MMOBegin, MMOEnd);
11754
11755     // Jump to endMBB
11756     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11757       .addMBB(endMBB);
11758   }
11759
11760   //
11761   // Emit code to use overflow area
11762   //
11763
11764   // Load the overflow_area address into a register.
11765   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11766   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11767     .addOperand(Base)
11768     .addOperand(Scale)
11769     .addOperand(Index)
11770     .addDisp(Disp, 8)
11771     .addOperand(Segment)
11772     .setMemRefs(MMOBegin, MMOEnd);
11773
11774   // If we need to align it, do so. Otherwise, just copy the address
11775   // to OverflowDestReg.
11776   if (NeedsAlign) {
11777     // Align the overflow address
11778     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11779     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11780
11781     // aligned_addr = (addr + (align-1)) & ~(align-1)
11782     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11783       .addReg(OverflowAddrReg)
11784       .addImm(Align-1);
11785
11786     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11787       .addReg(TmpReg)
11788       .addImm(~(uint64_t)(Align-1));
11789   } else {
11790     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11791       .addReg(OverflowAddrReg);
11792   }
11793
11794   // Compute the next overflow address after this argument.
11795   // (the overflow address should be kept 8-byte aligned)
11796   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11797   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11798     .addReg(OverflowDestReg)
11799     .addImm(ArgSizeA8);
11800
11801   // Store the new overflow address.
11802   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11803     .addOperand(Base)
11804     .addOperand(Scale)
11805     .addOperand(Index)
11806     .addDisp(Disp, 8)
11807     .addOperand(Segment)
11808     .addReg(NextAddrReg)
11809     .setMemRefs(MMOBegin, MMOEnd);
11810
11811   // If we branched, emit the PHI to the front of endMBB.
11812   if (offsetMBB) {
11813     BuildMI(*endMBB, endMBB->begin(), DL,
11814             TII->get(X86::PHI), DestReg)
11815       .addReg(OffsetDestReg).addMBB(offsetMBB)
11816       .addReg(OverflowDestReg).addMBB(overflowMBB);
11817   }
11818
11819   // Erase the pseudo instruction
11820   MI->eraseFromParent();
11821
11822   return endMBB;
11823 }
11824
11825 MachineBasicBlock *
11826 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11827                                                  MachineInstr *MI,
11828                                                  MachineBasicBlock *MBB) const {
11829   // Emit code to save XMM registers to the stack. The ABI says that the
11830   // number of registers to save is given in %al, so it's theoretically
11831   // possible to do an indirect jump trick to avoid saving all of them,
11832   // however this code takes a simpler approach and just executes all
11833   // of the stores if %al is non-zero. It's less code, and it's probably
11834   // easier on the hardware branch predictor, and stores aren't all that
11835   // expensive anyway.
11836
11837   // Create the new basic blocks. One block contains all the XMM stores,
11838   // and one block is the final destination regardless of whether any
11839   // stores were performed.
11840   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11841   MachineFunction *F = MBB->getParent();
11842   MachineFunction::iterator MBBIter = MBB;
11843   ++MBBIter;
11844   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11845   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11846   F->insert(MBBIter, XMMSaveMBB);
11847   F->insert(MBBIter, EndMBB);
11848
11849   // Transfer the remainder of MBB and its successor edges to EndMBB.
11850   EndMBB->splice(EndMBB->begin(), MBB,
11851                  llvm::next(MachineBasicBlock::iterator(MI)),
11852                  MBB->end());
11853   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11854
11855   // The original block will now fall through to the XMM save block.
11856   MBB->addSuccessor(XMMSaveMBB);
11857   // The XMMSaveMBB will fall through to the end block.
11858   XMMSaveMBB->addSuccessor(EndMBB);
11859
11860   // Now add the instructions.
11861   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11862   DebugLoc DL = MI->getDebugLoc();
11863
11864   unsigned CountReg = MI->getOperand(0).getReg();
11865   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11866   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11867
11868   if (!Subtarget->isTargetWin64()) {
11869     // If %al is 0, branch around the XMM save block.
11870     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11871     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11872     MBB->addSuccessor(EndMBB);
11873   }
11874
11875   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11876   // In the XMM save block, save all the XMM argument registers.
11877   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11878     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11879     MachineMemOperand *MMO =
11880       F->getMachineMemOperand(
11881           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11882         MachineMemOperand::MOStore,
11883         /*Size=*/16, /*Align=*/16);
11884     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11885       .addFrameIndex(RegSaveFrameIndex)
11886       .addImm(/*Scale=*/1)
11887       .addReg(/*IndexReg=*/0)
11888       .addImm(/*Disp=*/Offset)
11889       .addReg(/*Segment=*/0)
11890       .addReg(MI->getOperand(i).getReg())
11891       .addMemOperand(MMO);
11892   }
11893
11894   MI->eraseFromParent();   // The pseudo instruction is gone now.
11895
11896   return EndMBB;
11897 }
11898
11899 MachineBasicBlock *
11900 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11901                                      MachineBasicBlock *BB) const {
11902   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11903   DebugLoc DL = MI->getDebugLoc();
11904
11905   // To "insert" a SELECT_CC instruction, we actually have to insert the
11906   // diamond control-flow pattern.  The incoming instruction knows the
11907   // destination vreg to set, the condition code register to branch on, the
11908   // true/false values to select between, and a branch opcode to use.
11909   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11910   MachineFunction::iterator It = BB;
11911   ++It;
11912
11913   //  thisMBB:
11914   //  ...
11915   //   TrueVal = ...
11916   //   cmpTY ccX, r1, r2
11917   //   bCC copy1MBB
11918   //   fallthrough --> copy0MBB
11919   MachineBasicBlock *thisMBB = BB;
11920   MachineFunction *F = BB->getParent();
11921   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11922   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11923   F->insert(It, copy0MBB);
11924   F->insert(It, sinkMBB);
11925
11926   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11927   // live into the sink and copy blocks.
11928   if (!MI->killsRegister(X86::EFLAGS)) {
11929     copy0MBB->addLiveIn(X86::EFLAGS);
11930     sinkMBB->addLiveIn(X86::EFLAGS);
11931   }
11932
11933   // Transfer the remainder of BB and its successor edges to sinkMBB.
11934   sinkMBB->splice(sinkMBB->begin(), BB,
11935                   llvm::next(MachineBasicBlock::iterator(MI)),
11936                   BB->end());
11937   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11938
11939   // Add the true and fallthrough blocks as its successors.
11940   BB->addSuccessor(copy0MBB);
11941   BB->addSuccessor(sinkMBB);
11942
11943   // Create the conditional branch instruction.
11944   unsigned Opc =
11945     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11946   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11947
11948   //  copy0MBB:
11949   //   %FalseValue = ...
11950   //   # fallthrough to sinkMBB
11951   copy0MBB->addSuccessor(sinkMBB);
11952
11953   //  sinkMBB:
11954   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11955   //  ...
11956   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11957           TII->get(X86::PHI), MI->getOperand(0).getReg())
11958     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11959     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11960
11961   MI->eraseFromParent();   // The pseudo instruction is gone now.
11962   return sinkMBB;
11963 }
11964
11965 MachineBasicBlock *
11966 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11967                                         bool Is64Bit) const {
11968   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11969   DebugLoc DL = MI->getDebugLoc();
11970   MachineFunction *MF = BB->getParent();
11971   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11972
11973   assert(getTargetMachine().Options.EnableSegmentedStacks);
11974
11975   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11976   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11977
11978   // BB:
11979   //  ... [Till the alloca]
11980   // If stacklet is not large enough, jump to mallocMBB
11981   //
11982   // bumpMBB:
11983   //  Allocate by subtracting from RSP
11984   //  Jump to continueMBB
11985   //
11986   // mallocMBB:
11987   //  Allocate by call to runtime
11988   //
11989   // continueMBB:
11990   //  ...
11991   //  [rest of original BB]
11992   //
11993
11994   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11995   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11996   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11997
11998   MachineRegisterInfo &MRI = MF->getRegInfo();
11999   const TargetRegisterClass *AddrRegClass =
12000     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12001
12002   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12003     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12004     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12005     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12006     sizeVReg = MI->getOperand(1).getReg(),
12007     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12008
12009   MachineFunction::iterator MBBIter = BB;
12010   ++MBBIter;
12011
12012   MF->insert(MBBIter, bumpMBB);
12013   MF->insert(MBBIter, mallocMBB);
12014   MF->insert(MBBIter, continueMBB);
12015
12016   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12017                       (MachineBasicBlock::iterator(MI)), BB->end());
12018   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12019
12020   // Add code to the main basic block to check if the stack limit has been hit,
12021   // and if so, jump to mallocMBB otherwise to bumpMBB.
12022   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12023   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12024     .addReg(tmpSPVReg).addReg(sizeVReg);
12025   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12026     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12027     .addReg(SPLimitVReg);
12028   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12029
12030   // bumpMBB simply decreases the stack pointer, since we know the current
12031   // stacklet has enough space.
12032   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12033     .addReg(SPLimitVReg);
12034   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12035     .addReg(SPLimitVReg);
12036   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12037
12038   // Calls into a routine in libgcc to allocate more space from the heap.
12039   if (Is64Bit) {
12040     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12041       .addReg(sizeVReg);
12042     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12043     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12044   } else {
12045     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12046       .addImm(12);
12047     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12048     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12049       .addExternalSymbol("__morestack_allocate_stack_space");
12050   }
12051
12052   if (!Is64Bit)
12053     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12054       .addImm(16);
12055
12056   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12057     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12058   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12059
12060   // Set up the CFG correctly.
12061   BB->addSuccessor(bumpMBB);
12062   BB->addSuccessor(mallocMBB);
12063   mallocMBB->addSuccessor(continueMBB);
12064   bumpMBB->addSuccessor(continueMBB);
12065
12066   // Take care of the PHI nodes.
12067   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12068           MI->getOperand(0).getReg())
12069     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12070     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12071
12072   // Delete the original pseudo instruction.
12073   MI->eraseFromParent();
12074
12075   // And we're done.
12076   return continueMBB;
12077 }
12078
12079 MachineBasicBlock *
12080 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12081                                           MachineBasicBlock *BB) const {
12082   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12083   DebugLoc DL = MI->getDebugLoc();
12084
12085   assert(!Subtarget->isTargetEnvMacho());
12086
12087   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12088   // non-trivial part is impdef of ESP.
12089
12090   if (Subtarget->isTargetWin64()) {
12091     if (Subtarget->isTargetCygMing()) {
12092       // ___chkstk(Mingw64):
12093       // Clobbers R10, R11, RAX and EFLAGS.
12094       // Updates RSP.
12095       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12096         .addExternalSymbol("___chkstk")
12097         .addReg(X86::RAX, RegState::Implicit)
12098         .addReg(X86::RSP, RegState::Implicit)
12099         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12100         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12101         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12102     } else {
12103       // __chkstk(MSVCRT): does not update stack pointer.
12104       // Clobbers R10, R11 and EFLAGS.
12105       // FIXME: RAX(allocated size) might be reused and not killed.
12106       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12107         .addExternalSymbol("__chkstk")
12108         .addReg(X86::RAX, RegState::Implicit)
12109         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12110       // RAX has the offset to subtracted from RSP.
12111       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12112         .addReg(X86::RSP)
12113         .addReg(X86::RAX);
12114     }
12115   } else {
12116     const char *StackProbeSymbol =
12117       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12118
12119     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12120       .addExternalSymbol(StackProbeSymbol)
12121       .addReg(X86::EAX, RegState::Implicit)
12122       .addReg(X86::ESP, RegState::Implicit)
12123       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12124       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12125       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12126   }
12127
12128   MI->eraseFromParent();   // The pseudo instruction is gone now.
12129   return BB;
12130 }
12131
12132 MachineBasicBlock *
12133 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12134                                       MachineBasicBlock *BB) const {
12135   // This is pretty easy.  We're taking the value that we received from
12136   // our load from the relocation, sticking it in either RDI (x86-64)
12137   // or EAX and doing an indirect call.  The return value will then
12138   // be in the normal return register.
12139   const X86InstrInfo *TII
12140     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12141   DebugLoc DL = MI->getDebugLoc();
12142   MachineFunction *F = BB->getParent();
12143
12144   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12145   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12146
12147   if (Subtarget->is64Bit()) {
12148     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12149                                       TII->get(X86::MOV64rm), X86::RDI)
12150     .addReg(X86::RIP)
12151     .addImm(0).addReg(0)
12152     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12153                       MI->getOperand(3).getTargetFlags())
12154     .addReg(0);
12155     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12156     addDirectMem(MIB, X86::RDI);
12157   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12158     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12159                                       TII->get(X86::MOV32rm), X86::EAX)
12160     .addReg(0)
12161     .addImm(0).addReg(0)
12162     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12163                       MI->getOperand(3).getTargetFlags())
12164     .addReg(0);
12165     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12166     addDirectMem(MIB, X86::EAX);
12167   } else {
12168     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12169                                       TII->get(X86::MOV32rm), X86::EAX)
12170     .addReg(TII->getGlobalBaseReg(F))
12171     .addImm(0).addReg(0)
12172     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12173                       MI->getOperand(3).getTargetFlags())
12174     .addReg(0);
12175     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12176     addDirectMem(MIB, X86::EAX);
12177   }
12178
12179   MI->eraseFromParent(); // The pseudo instruction is gone now.
12180   return BB;
12181 }
12182
12183 MachineBasicBlock *
12184 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12185                                                MachineBasicBlock *BB) const {
12186   switch (MI->getOpcode()) {
12187   default: assert(0 && "Unexpected instr type to insert");
12188   case X86::TAILJMPd64:
12189   case X86::TAILJMPr64:
12190   case X86::TAILJMPm64:
12191     assert(0 && "TAILJMP64 would not be touched here.");
12192   case X86::TCRETURNdi64:
12193   case X86::TCRETURNri64:
12194   case X86::TCRETURNmi64:
12195     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12196     // On AMD64, additional defs should be added before register allocation.
12197     if (!Subtarget->isTargetWin64()) {
12198       MI->addRegisterDefined(X86::RSI);
12199       MI->addRegisterDefined(X86::RDI);
12200       MI->addRegisterDefined(X86::XMM6);
12201       MI->addRegisterDefined(X86::XMM7);
12202       MI->addRegisterDefined(X86::XMM8);
12203       MI->addRegisterDefined(X86::XMM9);
12204       MI->addRegisterDefined(X86::XMM10);
12205       MI->addRegisterDefined(X86::XMM11);
12206       MI->addRegisterDefined(X86::XMM12);
12207       MI->addRegisterDefined(X86::XMM13);
12208       MI->addRegisterDefined(X86::XMM14);
12209       MI->addRegisterDefined(X86::XMM15);
12210     }
12211     return BB;
12212   case X86::WIN_ALLOCA:
12213     return EmitLoweredWinAlloca(MI, BB);
12214   case X86::SEG_ALLOCA_32:
12215     return EmitLoweredSegAlloca(MI, BB, false);
12216   case X86::SEG_ALLOCA_64:
12217     return EmitLoweredSegAlloca(MI, BB, true);
12218   case X86::TLSCall_32:
12219   case X86::TLSCall_64:
12220     return EmitLoweredTLSCall(MI, BB);
12221   case X86::CMOV_GR8:
12222   case X86::CMOV_FR32:
12223   case X86::CMOV_FR64:
12224   case X86::CMOV_V4F32:
12225   case X86::CMOV_V2F64:
12226   case X86::CMOV_V2I64:
12227   case X86::CMOV_V8F32:
12228   case X86::CMOV_V4F64:
12229   case X86::CMOV_V4I64:
12230   case X86::CMOV_GR16:
12231   case X86::CMOV_GR32:
12232   case X86::CMOV_RFP32:
12233   case X86::CMOV_RFP64:
12234   case X86::CMOV_RFP80:
12235     return EmitLoweredSelect(MI, BB);
12236
12237   case X86::FP32_TO_INT16_IN_MEM:
12238   case X86::FP32_TO_INT32_IN_MEM:
12239   case X86::FP32_TO_INT64_IN_MEM:
12240   case X86::FP64_TO_INT16_IN_MEM:
12241   case X86::FP64_TO_INT32_IN_MEM:
12242   case X86::FP64_TO_INT64_IN_MEM:
12243   case X86::FP80_TO_INT16_IN_MEM:
12244   case X86::FP80_TO_INT32_IN_MEM:
12245   case X86::FP80_TO_INT64_IN_MEM: {
12246     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12247     DebugLoc DL = MI->getDebugLoc();
12248
12249     // Change the floating point control register to use "round towards zero"
12250     // mode when truncating to an integer value.
12251     MachineFunction *F = BB->getParent();
12252     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12253     addFrameReference(BuildMI(*BB, MI, DL,
12254                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12255
12256     // Load the old value of the high byte of the control word...
12257     unsigned OldCW =
12258       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12259     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12260                       CWFrameIdx);
12261
12262     // Set the high part to be round to zero...
12263     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12264       .addImm(0xC7F);
12265
12266     // Reload the modified control word now...
12267     addFrameReference(BuildMI(*BB, MI, DL,
12268                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12269
12270     // Restore the memory image of control word to original value
12271     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12272       .addReg(OldCW);
12273
12274     // Get the X86 opcode to use.
12275     unsigned Opc;
12276     switch (MI->getOpcode()) {
12277     default: llvm_unreachable("illegal opcode!");
12278     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12279     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12280     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12281     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12282     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12283     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12284     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12285     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12286     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12287     }
12288
12289     X86AddressMode AM;
12290     MachineOperand &Op = MI->getOperand(0);
12291     if (Op.isReg()) {
12292       AM.BaseType = X86AddressMode::RegBase;
12293       AM.Base.Reg = Op.getReg();
12294     } else {
12295       AM.BaseType = X86AddressMode::FrameIndexBase;
12296       AM.Base.FrameIndex = Op.getIndex();
12297     }
12298     Op = MI->getOperand(1);
12299     if (Op.isImm())
12300       AM.Scale = Op.getImm();
12301     Op = MI->getOperand(2);
12302     if (Op.isImm())
12303       AM.IndexReg = Op.getImm();
12304     Op = MI->getOperand(3);
12305     if (Op.isGlobal()) {
12306       AM.GV = Op.getGlobal();
12307     } else {
12308       AM.Disp = Op.getImm();
12309     }
12310     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12311                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12312
12313     // Reload the original control word now.
12314     addFrameReference(BuildMI(*BB, MI, DL,
12315                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12316
12317     MI->eraseFromParent();   // The pseudo instruction is gone now.
12318     return BB;
12319   }
12320     // String/text processing lowering.
12321   case X86::PCMPISTRM128REG:
12322   case X86::VPCMPISTRM128REG:
12323     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12324   case X86::PCMPISTRM128MEM:
12325   case X86::VPCMPISTRM128MEM:
12326     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12327   case X86::PCMPESTRM128REG:
12328   case X86::VPCMPESTRM128REG:
12329     return EmitPCMP(MI, BB, 5, false /* in mem */);
12330   case X86::PCMPESTRM128MEM:
12331   case X86::VPCMPESTRM128MEM:
12332     return EmitPCMP(MI, BB, 5, true /* in mem */);
12333
12334     // Thread synchronization.
12335   case X86::MONITOR:
12336     return EmitMonitor(MI, BB);
12337   case X86::MWAIT:
12338     return EmitMwait(MI, BB);
12339
12340     // Atomic Lowering.
12341   case X86::ATOMAND32:
12342     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12343                                                X86::AND32ri, X86::MOV32rm,
12344                                                X86::LCMPXCHG32,
12345                                                X86::NOT32r, X86::EAX,
12346                                                X86::GR32RegisterClass);
12347   case X86::ATOMOR32:
12348     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12349                                                X86::OR32ri, X86::MOV32rm,
12350                                                X86::LCMPXCHG32,
12351                                                X86::NOT32r, X86::EAX,
12352                                                X86::GR32RegisterClass);
12353   case X86::ATOMXOR32:
12354     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12355                                                X86::XOR32ri, X86::MOV32rm,
12356                                                X86::LCMPXCHG32,
12357                                                X86::NOT32r, X86::EAX,
12358                                                X86::GR32RegisterClass);
12359   case X86::ATOMNAND32:
12360     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12361                                                X86::AND32ri, X86::MOV32rm,
12362                                                X86::LCMPXCHG32,
12363                                                X86::NOT32r, X86::EAX,
12364                                                X86::GR32RegisterClass, true);
12365   case X86::ATOMMIN32:
12366     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12367   case X86::ATOMMAX32:
12368     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12369   case X86::ATOMUMIN32:
12370     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12371   case X86::ATOMUMAX32:
12372     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12373
12374   case X86::ATOMAND16:
12375     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12376                                                X86::AND16ri, X86::MOV16rm,
12377                                                X86::LCMPXCHG16,
12378                                                X86::NOT16r, X86::AX,
12379                                                X86::GR16RegisterClass);
12380   case X86::ATOMOR16:
12381     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12382                                                X86::OR16ri, X86::MOV16rm,
12383                                                X86::LCMPXCHG16,
12384                                                X86::NOT16r, X86::AX,
12385                                                X86::GR16RegisterClass);
12386   case X86::ATOMXOR16:
12387     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12388                                                X86::XOR16ri, X86::MOV16rm,
12389                                                X86::LCMPXCHG16,
12390                                                X86::NOT16r, X86::AX,
12391                                                X86::GR16RegisterClass);
12392   case X86::ATOMNAND16:
12393     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12394                                                X86::AND16ri, X86::MOV16rm,
12395                                                X86::LCMPXCHG16,
12396                                                X86::NOT16r, X86::AX,
12397                                                X86::GR16RegisterClass, true);
12398   case X86::ATOMMIN16:
12399     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12400   case X86::ATOMMAX16:
12401     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12402   case X86::ATOMUMIN16:
12403     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12404   case X86::ATOMUMAX16:
12405     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12406
12407   case X86::ATOMAND8:
12408     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12409                                                X86::AND8ri, X86::MOV8rm,
12410                                                X86::LCMPXCHG8,
12411                                                X86::NOT8r, X86::AL,
12412                                                X86::GR8RegisterClass);
12413   case X86::ATOMOR8:
12414     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12415                                                X86::OR8ri, X86::MOV8rm,
12416                                                X86::LCMPXCHG8,
12417                                                X86::NOT8r, X86::AL,
12418                                                X86::GR8RegisterClass);
12419   case X86::ATOMXOR8:
12420     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12421                                                X86::XOR8ri, X86::MOV8rm,
12422                                                X86::LCMPXCHG8,
12423                                                X86::NOT8r, X86::AL,
12424                                                X86::GR8RegisterClass);
12425   case X86::ATOMNAND8:
12426     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12427                                                X86::AND8ri, X86::MOV8rm,
12428                                                X86::LCMPXCHG8,
12429                                                X86::NOT8r, X86::AL,
12430                                                X86::GR8RegisterClass, true);
12431   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12432   // This group is for 64-bit host.
12433   case X86::ATOMAND64:
12434     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12435                                                X86::AND64ri32, X86::MOV64rm,
12436                                                X86::LCMPXCHG64,
12437                                                X86::NOT64r, X86::RAX,
12438                                                X86::GR64RegisterClass);
12439   case X86::ATOMOR64:
12440     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12441                                                X86::OR64ri32, X86::MOV64rm,
12442                                                X86::LCMPXCHG64,
12443                                                X86::NOT64r, X86::RAX,
12444                                                X86::GR64RegisterClass);
12445   case X86::ATOMXOR64:
12446     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12447                                                X86::XOR64ri32, X86::MOV64rm,
12448                                                X86::LCMPXCHG64,
12449                                                X86::NOT64r, X86::RAX,
12450                                                X86::GR64RegisterClass);
12451   case X86::ATOMNAND64:
12452     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12453                                                X86::AND64ri32, X86::MOV64rm,
12454                                                X86::LCMPXCHG64,
12455                                                X86::NOT64r, X86::RAX,
12456                                                X86::GR64RegisterClass, true);
12457   case X86::ATOMMIN64:
12458     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12459   case X86::ATOMMAX64:
12460     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12461   case X86::ATOMUMIN64:
12462     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12463   case X86::ATOMUMAX64:
12464     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12465
12466   // This group does 64-bit operations on a 32-bit host.
12467   case X86::ATOMAND6432:
12468     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12469                                                X86::AND32rr, X86::AND32rr,
12470                                                X86::AND32ri, X86::AND32ri,
12471                                                false);
12472   case X86::ATOMOR6432:
12473     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12474                                                X86::OR32rr, X86::OR32rr,
12475                                                X86::OR32ri, X86::OR32ri,
12476                                                false);
12477   case X86::ATOMXOR6432:
12478     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12479                                                X86::XOR32rr, X86::XOR32rr,
12480                                                X86::XOR32ri, X86::XOR32ri,
12481                                                false);
12482   case X86::ATOMNAND6432:
12483     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12484                                                X86::AND32rr, X86::AND32rr,
12485                                                X86::AND32ri, X86::AND32ri,
12486                                                true);
12487   case X86::ATOMADD6432:
12488     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12489                                                X86::ADD32rr, X86::ADC32rr,
12490                                                X86::ADD32ri, X86::ADC32ri,
12491                                                false);
12492   case X86::ATOMSUB6432:
12493     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12494                                                X86::SUB32rr, X86::SBB32rr,
12495                                                X86::SUB32ri, X86::SBB32ri,
12496                                                false);
12497   case X86::ATOMSWAP6432:
12498     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12499                                                X86::MOV32rr, X86::MOV32rr,
12500                                                X86::MOV32ri, X86::MOV32ri,
12501                                                false);
12502   case X86::VASTART_SAVE_XMM_REGS:
12503     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12504
12505   case X86::VAARG_64:
12506     return EmitVAARG64WithCustomInserter(MI, BB);
12507   }
12508 }
12509
12510 //===----------------------------------------------------------------------===//
12511 //                           X86 Optimization Hooks
12512 //===----------------------------------------------------------------------===//
12513
12514 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12515                                                        const APInt &Mask,
12516                                                        APInt &KnownZero,
12517                                                        APInt &KnownOne,
12518                                                        const SelectionDAG &DAG,
12519                                                        unsigned Depth) const {
12520   unsigned Opc = Op.getOpcode();
12521   assert((Opc >= ISD::BUILTIN_OP_END ||
12522           Opc == ISD::INTRINSIC_WO_CHAIN ||
12523           Opc == ISD::INTRINSIC_W_CHAIN ||
12524           Opc == ISD::INTRINSIC_VOID) &&
12525          "Should use MaskedValueIsZero if you don't know whether Op"
12526          " is a target node!");
12527
12528   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12529   switch (Opc) {
12530   default: break;
12531   case X86ISD::ADD:
12532   case X86ISD::SUB:
12533   case X86ISD::ADC:
12534   case X86ISD::SBB:
12535   case X86ISD::SMUL:
12536   case X86ISD::UMUL:
12537   case X86ISD::INC:
12538   case X86ISD::DEC:
12539   case X86ISD::OR:
12540   case X86ISD::XOR:
12541   case X86ISD::AND:
12542     // These nodes' second result is a boolean.
12543     if (Op.getResNo() == 0)
12544       break;
12545     // Fallthrough
12546   case X86ISD::SETCC:
12547     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12548                                        Mask.getBitWidth() - 1);
12549     break;
12550   case ISD::INTRINSIC_WO_CHAIN: {
12551     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12552     unsigned NumLoBits = 0;
12553     switch (IntId) {
12554     default: break;
12555     case Intrinsic::x86_sse_movmsk_ps:
12556     case Intrinsic::x86_avx_movmsk_ps_256:
12557     case Intrinsic::x86_sse2_movmsk_pd:
12558     case Intrinsic::x86_avx_movmsk_pd_256:
12559     case Intrinsic::x86_mmx_pmovmskb:
12560     case Intrinsic::x86_sse2_pmovmskb_128:
12561     case Intrinsic::x86_avx2_pmovmskb: {
12562       // High bits of movmskp{s|d}, pmovmskb are known zero.
12563       switch (IntId) {
12564         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12565         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12566         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12567         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12568         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12569         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12570         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12571       }
12572       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12573                                         Mask.getBitWidth() - NumLoBits);
12574       break;
12575     }
12576     }
12577     break;
12578   }
12579   }
12580 }
12581
12582 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12583                                                          unsigned Depth) const {
12584   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12585   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12586     return Op.getValueType().getScalarType().getSizeInBits();
12587
12588   // Fallback case.
12589   return 1;
12590 }
12591
12592 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12593 /// node is a GlobalAddress + offset.
12594 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12595                                        const GlobalValue* &GA,
12596                                        int64_t &Offset) const {
12597   if (N->getOpcode() == X86ISD::Wrapper) {
12598     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12599       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12600       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12601       return true;
12602     }
12603   }
12604   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12605 }
12606
12607 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12608 /// same as extracting the high 128-bit part of 256-bit vector and then
12609 /// inserting the result into the low part of a new 256-bit vector
12610 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12611   EVT VT = SVOp->getValueType(0);
12612   int NumElems = VT.getVectorNumElements();
12613
12614   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12615   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12616     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12617         SVOp->getMaskElt(j) >= 0)
12618       return false;
12619
12620   return true;
12621 }
12622
12623 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12624 /// same as extracting the low 128-bit part of 256-bit vector and then
12625 /// inserting the result into the high part of a new 256-bit vector
12626 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12627   EVT VT = SVOp->getValueType(0);
12628   int NumElems = VT.getVectorNumElements();
12629
12630   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12631   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12632     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12633         SVOp->getMaskElt(j) >= 0)
12634       return false;
12635
12636   return true;
12637 }
12638
12639 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12640 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12641                                         TargetLowering::DAGCombinerInfo &DCI,
12642                                         bool HasAVX2) {
12643   DebugLoc dl = N->getDebugLoc();
12644   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12645   SDValue V1 = SVOp->getOperand(0);
12646   SDValue V2 = SVOp->getOperand(1);
12647   EVT VT = SVOp->getValueType(0);
12648   int NumElems = VT.getVectorNumElements();
12649
12650   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12651       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12652     //
12653     //                   0,0,0,...
12654     //                      |
12655     //    V      UNDEF    BUILD_VECTOR    UNDEF
12656     //     \      /           \           /
12657     //  CONCAT_VECTOR         CONCAT_VECTOR
12658     //         \                  /
12659     //          \                /
12660     //          RESULT: V + zero extended
12661     //
12662     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12663         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12664         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12665       return SDValue();
12666
12667     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12668       return SDValue();
12669
12670     // To match the shuffle mask, the first half of the mask should
12671     // be exactly the first vector, and all the rest a splat with the
12672     // first element of the second one.
12673     for (int i = 0; i < NumElems/2; ++i)
12674       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12675           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12676         return SDValue();
12677
12678     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12679     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12680       SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
12681       SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
12682       SDValue ResNode =
12683         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
12684                                 Ld->getMemoryVT(),
12685                                 Ld->getPointerInfo(),
12686                                 Ld->getAlignment(),
12687                                 false/*isVolatile*/, true/*ReadMem*/,
12688                                 false/*WriteMem*/);
12689       return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
12690     } 
12691
12692     // Emit a zeroed vector and insert the desired subvector on its
12693     // first half.
12694     SDValue Zeros = getZeroVector(VT, true /* HasSSE2 */, HasAVX2, DAG, dl);
12695     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12696                          DAG.getConstant(0, MVT::i32), DAG, dl);
12697     return DCI.CombineTo(N, InsV);
12698   }
12699
12700   //===--------------------------------------------------------------------===//
12701   // Combine some shuffles into subvector extracts and inserts:
12702   //
12703
12704   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12705   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12706     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12707                                     DAG, dl);
12708     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12709                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12710     return DCI.CombineTo(N, InsV);
12711   }
12712
12713   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12714   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12715     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12716     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12717                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12718     return DCI.CombineTo(N, InsV);
12719   }
12720
12721   return SDValue();
12722 }
12723
12724 /// PerformShuffleCombine - Performs several different shuffle combines.
12725 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12726                                      TargetLowering::DAGCombinerInfo &DCI,
12727                                      const X86Subtarget *Subtarget) {
12728   DebugLoc dl = N->getDebugLoc();
12729   EVT VT = N->getValueType(0);
12730
12731   // Don't create instructions with illegal types after legalize types has run.
12732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12733   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12734     return SDValue();
12735
12736   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12737   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12738       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12739     return PerformShuffleCombine256(N, DAG, DCI, Subtarget->hasAVX2());
12740
12741   // Only handle 128 wide vector from here on.
12742   if (VT.getSizeInBits() != 128)
12743     return SDValue();
12744
12745   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12746   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12747   // consecutive, non-overlapping, and in the right order.
12748   SmallVector<SDValue, 16> Elts;
12749   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12750     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12751
12752   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12753 }
12754
12755 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12756 /// generation and convert it from being a bunch of shuffles and extracts
12757 /// to a simple store and scalar loads to extract the elements.
12758 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12759                                                 const TargetLowering &TLI) {
12760   SDValue InputVector = N->getOperand(0);
12761
12762   // Only operate on vectors of 4 elements, where the alternative shuffling
12763   // gets to be more expensive.
12764   if (InputVector.getValueType() != MVT::v4i32)
12765     return SDValue();
12766
12767   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12768   // single use which is a sign-extend or zero-extend, and all elements are
12769   // used.
12770   SmallVector<SDNode *, 4> Uses;
12771   unsigned ExtractedElements = 0;
12772   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12773        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12774     if (UI.getUse().getResNo() != InputVector.getResNo())
12775       return SDValue();
12776
12777     SDNode *Extract = *UI;
12778     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12779       return SDValue();
12780
12781     if (Extract->getValueType(0) != MVT::i32)
12782       return SDValue();
12783     if (!Extract->hasOneUse())
12784       return SDValue();
12785     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12786         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12787       return SDValue();
12788     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12789       return SDValue();
12790
12791     // Record which element was extracted.
12792     ExtractedElements |=
12793       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12794
12795     Uses.push_back(Extract);
12796   }
12797
12798   // If not all the elements were used, this may not be worthwhile.
12799   if (ExtractedElements != 15)
12800     return SDValue();
12801
12802   // Ok, we've now decided to do the transformation.
12803   DebugLoc dl = InputVector.getDebugLoc();
12804
12805   // Store the value to a temporary stack slot.
12806   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12807   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12808                             MachinePointerInfo(), false, false, 0);
12809
12810   // Replace each use (extract) with a load of the appropriate element.
12811   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12812        UE = Uses.end(); UI != UE; ++UI) {
12813     SDNode *Extract = *UI;
12814
12815     // cOMpute the element's address.
12816     SDValue Idx = Extract->getOperand(1);
12817     unsigned EltSize =
12818         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12819     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12820     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12821
12822     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12823                                      StackPtr, OffsetVal);
12824
12825     // Load the scalar.
12826     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12827                                      ScalarAddr, MachinePointerInfo(),
12828                                      false, false, false, 0);
12829
12830     // Replace the exact with the load.
12831     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12832   }
12833
12834   // The replacement was made in place; don't return anything.
12835   return SDValue();
12836 }
12837
12838 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12839 /// nodes.
12840 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12841                                     TargetLowering::DAGCombinerInfo &DCI,
12842                                     const X86Subtarget *Subtarget) {
12843   DebugLoc DL = N->getDebugLoc();
12844   SDValue Cond = N->getOperand(0);
12845   // Get the LHS/RHS of the select.
12846   SDValue LHS = N->getOperand(1);
12847   SDValue RHS = N->getOperand(2);
12848   EVT VT = LHS.getValueType();
12849
12850   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12851   // instructions match the semantics of the common C idiom x<y?x:y but not
12852   // x<=y?x:y, because of how they handle negative zero (which can be
12853   // ignored in unsafe-math mode).
12854   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12855       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12856       (Subtarget->hasSSE2() ||
12857        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12858     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12859
12860     unsigned Opcode = 0;
12861     // Check for x CC y ? x : y.
12862     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12863         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12864       switch (CC) {
12865       default: break;
12866       case ISD::SETULT:
12867         // Converting this to a min would handle NaNs incorrectly, and swapping
12868         // the operands would cause it to handle comparisons between positive
12869         // and negative zero incorrectly.
12870         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12871           if (!DAG.getTarget().Options.UnsafeFPMath &&
12872               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12873             break;
12874           std::swap(LHS, RHS);
12875         }
12876         Opcode = X86ISD::FMIN;
12877         break;
12878       case ISD::SETOLE:
12879         // Converting this to a min would handle comparisons between positive
12880         // and negative zero incorrectly.
12881         if (!DAG.getTarget().Options.UnsafeFPMath &&
12882             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12883           break;
12884         Opcode = X86ISD::FMIN;
12885         break;
12886       case ISD::SETULE:
12887         // Converting this to a min would handle both negative zeros and NaNs
12888         // incorrectly, but we can swap the operands to fix both.
12889         std::swap(LHS, RHS);
12890       case ISD::SETOLT:
12891       case ISD::SETLT:
12892       case ISD::SETLE:
12893         Opcode = X86ISD::FMIN;
12894         break;
12895
12896       case ISD::SETOGE:
12897         // Converting this to a max would handle comparisons between positive
12898         // and negative zero incorrectly.
12899         if (!DAG.getTarget().Options.UnsafeFPMath &&
12900             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12901           break;
12902         Opcode = X86ISD::FMAX;
12903         break;
12904       case ISD::SETUGT:
12905         // Converting this to a max would handle NaNs incorrectly, and swapping
12906         // the operands would cause it to handle comparisons between positive
12907         // and negative zero incorrectly.
12908         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12909           if (!DAG.getTarget().Options.UnsafeFPMath &&
12910               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12911             break;
12912           std::swap(LHS, RHS);
12913         }
12914         Opcode = X86ISD::FMAX;
12915         break;
12916       case ISD::SETUGE:
12917         // Converting this to a max would handle both negative zeros and NaNs
12918         // incorrectly, but we can swap the operands to fix both.
12919         std::swap(LHS, RHS);
12920       case ISD::SETOGT:
12921       case ISD::SETGT:
12922       case ISD::SETGE:
12923         Opcode = X86ISD::FMAX;
12924         break;
12925       }
12926     // Check for x CC y ? y : x -- a min/max with reversed arms.
12927     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12928                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12929       switch (CC) {
12930       default: break;
12931       case ISD::SETOGE:
12932         // Converting this to a min would handle comparisons between positive
12933         // and negative zero incorrectly, and swapping the operands would
12934         // cause it to handle NaNs incorrectly.
12935         if (!DAG.getTarget().Options.UnsafeFPMath &&
12936             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12937           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12938             break;
12939           std::swap(LHS, RHS);
12940         }
12941         Opcode = X86ISD::FMIN;
12942         break;
12943       case ISD::SETUGT:
12944         // Converting this to a min would handle NaNs incorrectly.
12945         if (!DAG.getTarget().Options.UnsafeFPMath &&
12946             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12947           break;
12948         Opcode = X86ISD::FMIN;
12949         break;
12950       case ISD::SETUGE:
12951         // Converting this to a min would handle both negative zeros and NaNs
12952         // incorrectly, but we can swap the operands to fix both.
12953         std::swap(LHS, RHS);
12954       case ISD::SETOGT:
12955       case ISD::SETGT:
12956       case ISD::SETGE:
12957         Opcode = X86ISD::FMIN;
12958         break;
12959
12960       case ISD::SETULT:
12961         // Converting this to a max would handle NaNs incorrectly.
12962         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12963           break;
12964         Opcode = X86ISD::FMAX;
12965         break;
12966       case ISD::SETOLE:
12967         // Converting this to a max would handle comparisons between positive
12968         // and negative zero incorrectly, and swapping the operands would
12969         // cause it to handle NaNs incorrectly.
12970         if (!DAG.getTarget().Options.UnsafeFPMath &&
12971             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12972           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12973             break;
12974           std::swap(LHS, RHS);
12975         }
12976         Opcode = X86ISD::FMAX;
12977         break;
12978       case ISD::SETULE:
12979         // Converting this to a max would handle both negative zeros and NaNs
12980         // incorrectly, but we can swap the operands to fix both.
12981         std::swap(LHS, RHS);
12982       case ISD::SETOLT:
12983       case ISD::SETLT:
12984       case ISD::SETLE:
12985         Opcode = X86ISD::FMAX;
12986         break;
12987       }
12988     }
12989
12990     if (Opcode)
12991       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12992   }
12993
12994   // If this is a select between two integer constants, try to do some
12995   // optimizations.
12996   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12997     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12998       // Don't do this for crazy integer types.
12999       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13000         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13001         // so that TrueC (the true value) is larger than FalseC.
13002         bool NeedsCondInvert = false;
13003
13004         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13005             // Efficiently invertible.
13006             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13007              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13008               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13009           NeedsCondInvert = true;
13010           std::swap(TrueC, FalseC);
13011         }
13012
13013         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13014         if (FalseC->getAPIntValue() == 0 &&
13015             TrueC->getAPIntValue().isPowerOf2()) {
13016           if (NeedsCondInvert) // Invert the condition if needed.
13017             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13018                                DAG.getConstant(1, Cond.getValueType()));
13019
13020           // Zero extend the condition if needed.
13021           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13022
13023           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13024           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13025                              DAG.getConstant(ShAmt, MVT::i8));
13026         }
13027
13028         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13029         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13030           if (NeedsCondInvert) // Invert the condition if needed.
13031             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13032                                DAG.getConstant(1, Cond.getValueType()));
13033
13034           // Zero extend the condition if needed.
13035           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13036                              FalseC->getValueType(0), Cond);
13037           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13038                              SDValue(FalseC, 0));
13039         }
13040
13041         // Optimize cases that will turn into an LEA instruction.  This requires
13042         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13043         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13044           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13045           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13046
13047           bool isFastMultiplier = false;
13048           if (Diff < 10) {
13049             switch ((unsigned char)Diff) {
13050               default: break;
13051               case 1:  // result = add base, cond
13052               case 2:  // result = lea base(    , cond*2)
13053               case 3:  // result = lea base(cond, cond*2)
13054               case 4:  // result = lea base(    , cond*4)
13055               case 5:  // result = lea base(cond, cond*4)
13056               case 8:  // result = lea base(    , cond*8)
13057               case 9:  // result = lea base(cond, cond*8)
13058                 isFastMultiplier = true;
13059                 break;
13060             }
13061           }
13062
13063           if (isFastMultiplier) {
13064             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13065             if (NeedsCondInvert) // Invert the condition if needed.
13066               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13067                                  DAG.getConstant(1, Cond.getValueType()));
13068
13069             // Zero extend the condition if needed.
13070             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13071                                Cond);
13072             // Scale the condition by the difference.
13073             if (Diff != 1)
13074               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13075                                  DAG.getConstant(Diff, Cond.getValueType()));
13076
13077             // Add the base if non-zero.
13078             if (FalseC->getAPIntValue() != 0)
13079               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13080                                  SDValue(FalseC, 0));
13081             return Cond;
13082           }
13083         }
13084       }
13085   }
13086
13087   // Canonicalize max and min:
13088   // (x > y) ? x : y -> (x >= y) ? x : y
13089   // (x < y) ? x : y -> (x <= y) ? x : y
13090   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13091   // the need for an extra compare
13092   // against zero. e.g.
13093   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13094   // subl   %esi, %edi
13095   // testl  %edi, %edi
13096   // movl   $0, %eax
13097   // cmovgl %edi, %eax
13098   // =>
13099   // xorl   %eax, %eax
13100   // subl   %esi, $edi
13101   // cmovsl %eax, %edi
13102   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13103       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13104       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13105     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13106     switch (CC) {
13107     default: break;
13108     case ISD::SETLT:
13109     case ISD::SETGT: {
13110       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13111       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13112                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13113       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13114     }
13115     }
13116   }
13117
13118   // If we know that this node is legal then we know that it is going to be
13119   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13120   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13121   // to simplify previous instructions.
13122   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13123   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13124       !DCI.isBeforeLegalize() &&
13125       TLI.isOperationLegal(ISD::VSELECT, VT)) {
13126     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13127     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13128     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13129
13130     APInt KnownZero, KnownOne;
13131     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13132                                           DCI.isBeforeLegalizeOps());
13133     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13134         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13135       DCI.CommitTargetLoweringOpt(TLO);
13136   }
13137
13138   return SDValue();
13139 }
13140
13141 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13142 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13143                                   TargetLowering::DAGCombinerInfo &DCI) {
13144   DebugLoc DL = N->getDebugLoc();
13145
13146   // If the flag operand isn't dead, don't touch this CMOV.
13147   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13148     return SDValue();
13149
13150   SDValue FalseOp = N->getOperand(0);
13151   SDValue TrueOp = N->getOperand(1);
13152   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13153   SDValue Cond = N->getOperand(3);
13154   if (CC == X86::COND_E || CC == X86::COND_NE) {
13155     switch (Cond.getOpcode()) {
13156     default: break;
13157     case X86ISD::BSR:
13158     case X86ISD::BSF:
13159       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13160       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13161         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13162     }
13163   }
13164
13165   // If this is a select between two integer constants, try to do some
13166   // optimizations.  Note that the operands are ordered the opposite of SELECT
13167   // operands.
13168   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13169     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13170       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13171       // larger than FalseC (the false value).
13172       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13173         CC = X86::GetOppositeBranchCondition(CC);
13174         std::swap(TrueC, FalseC);
13175       }
13176
13177       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13178       // This is efficient for any integer data type (including i8/i16) and
13179       // shift amount.
13180       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13181         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13182                            DAG.getConstant(CC, MVT::i8), Cond);
13183
13184         // Zero extend the condition if needed.
13185         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13186
13187         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13188         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13189                            DAG.getConstant(ShAmt, MVT::i8));
13190         if (N->getNumValues() == 2)  // Dead flag value?
13191           return DCI.CombineTo(N, Cond, SDValue());
13192         return Cond;
13193       }
13194
13195       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13196       // for any integer data type, including i8/i16.
13197       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13198         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13199                            DAG.getConstant(CC, MVT::i8), Cond);
13200
13201         // Zero extend the condition if needed.
13202         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13203                            FalseC->getValueType(0), Cond);
13204         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13205                            SDValue(FalseC, 0));
13206
13207         if (N->getNumValues() == 2)  // Dead flag value?
13208           return DCI.CombineTo(N, Cond, SDValue());
13209         return Cond;
13210       }
13211
13212       // Optimize cases that will turn into an LEA instruction.  This requires
13213       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13214       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13215         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13216         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13217
13218         bool isFastMultiplier = false;
13219         if (Diff < 10) {
13220           switch ((unsigned char)Diff) {
13221           default: break;
13222           case 1:  // result = add base, cond
13223           case 2:  // result = lea base(    , cond*2)
13224           case 3:  // result = lea base(cond, cond*2)
13225           case 4:  // result = lea base(    , cond*4)
13226           case 5:  // result = lea base(cond, cond*4)
13227           case 8:  // result = lea base(    , cond*8)
13228           case 9:  // result = lea base(cond, cond*8)
13229             isFastMultiplier = true;
13230             break;
13231           }
13232         }
13233
13234         if (isFastMultiplier) {
13235           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13236           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13237                              DAG.getConstant(CC, MVT::i8), Cond);
13238           // Zero extend the condition if needed.
13239           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13240                              Cond);
13241           // Scale the condition by the difference.
13242           if (Diff != 1)
13243             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13244                                DAG.getConstant(Diff, Cond.getValueType()));
13245
13246           // Add the base if non-zero.
13247           if (FalseC->getAPIntValue() != 0)
13248             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13249                                SDValue(FalseC, 0));
13250           if (N->getNumValues() == 2)  // Dead flag value?
13251             return DCI.CombineTo(N, Cond, SDValue());
13252           return Cond;
13253         }
13254       }
13255     }
13256   }
13257   return SDValue();
13258 }
13259
13260
13261 /// PerformMulCombine - Optimize a single multiply with constant into two
13262 /// in order to implement it with two cheaper instructions, e.g.
13263 /// LEA + SHL, LEA + LEA.
13264 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13265                                  TargetLowering::DAGCombinerInfo &DCI) {
13266   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13267     return SDValue();
13268
13269   EVT VT = N->getValueType(0);
13270   if (VT != MVT::i64)
13271     return SDValue();
13272
13273   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13274   if (!C)
13275     return SDValue();
13276   uint64_t MulAmt = C->getZExtValue();
13277   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13278     return SDValue();
13279
13280   uint64_t MulAmt1 = 0;
13281   uint64_t MulAmt2 = 0;
13282   if ((MulAmt % 9) == 0) {
13283     MulAmt1 = 9;
13284     MulAmt2 = MulAmt / 9;
13285   } else if ((MulAmt % 5) == 0) {
13286     MulAmt1 = 5;
13287     MulAmt2 = MulAmt / 5;
13288   } else if ((MulAmt % 3) == 0) {
13289     MulAmt1 = 3;
13290     MulAmt2 = MulAmt / 3;
13291   }
13292   if (MulAmt2 &&
13293       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13294     DebugLoc DL = N->getDebugLoc();
13295
13296     if (isPowerOf2_64(MulAmt2) &&
13297         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13298       // If second multiplifer is pow2, issue it first. We want the multiply by
13299       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13300       // is an add.
13301       std::swap(MulAmt1, MulAmt2);
13302
13303     SDValue NewMul;
13304     if (isPowerOf2_64(MulAmt1))
13305       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13306                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13307     else
13308       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13309                            DAG.getConstant(MulAmt1, VT));
13310
13311     if (isPowerOf2_64(MulAmt2))
13312       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13313                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13314     else
13315       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13316                            DAG.getConstant(MulAmt2, VT));
13317
13318     // Do not add new nodes to DAG combiner worklist.
13319     DCI.CombineTo(N, NewMul, false);
13320   }
13321   return SDValue();
13322 }
13323
13324 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13325   SDValue N0 = N->getOperand(0);
13326   SDValue N1 = N->getOperand(1);
13327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13328   EVT VT = N0.getValueType();
13329
13330   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13331   // since the result of setcc_c is all zero's or all ones.
13332   if (VT.isInteger() && !VT.isVector() &&
13333       N1C && N0.getOpcode() == ISD::AND &&
13334       N0.getOperand(1).getOpcode() == ISD::Constant) {
13335     SDValue N00 = N0.getOperand(0);
13336     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13337         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13338           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13339          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13340       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13341       APInt ShAmt = N1C->getAPIntValue();
13342       Mask = Mask.shl(ShAmt);
13343       if (Mask != 0)
13344         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13345                            N00, DAG.getConstant(Mask, VT));
13346     }
13347   }
13348
13349
13350   // Hardware support for vector shifts is sparse which makes us scalarize the
13351   // vector operations in many cases. Also, on sandybridge ADD is faster than
13352   // shl.
13353   // (shl V, 1) -> add V,V
13354   if (isSplatVector(N1.getNode())) {
13355     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13356     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13357     // We shift all of the values by one. In many cases we do not have
13358     // hardware support for this operation. This is better expressed as an ADD
13359     // of two values.
13360     if (N1C && (1 == N1C->getZExtValue())) {
13361       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13362     }
13363   }
13364
13365   return SDValue();
13366 }
13367
13368 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13369 ///                       when possible.
13370 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13371                                    const X86Subtarget *Subtarget) {
13372   EVT VT = N->getValueType(0);
13373   if (N->getOpcode() == ISD::SHL) {
13374     SDValue V = PerformSHLCombine(N, DAG);
13375     if (V.getNode()) return V;
13376   }
13377
13378   // On X86 with SSE2 support, we can transform this to a vector shift if
13379   // all elements are shifted by the same amount.  We can't do this in legalize
13380   // because the a constant vector is typically transformed to a constant pool
13381   // so we have no knowledge of the shift amount.
13382   if (!Subtarget->hasSSE2())
13383     return SDValue();
13384
13385   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13386       (!Subtarget->hasAVX2() ||
13387        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13388     return SDValue();
13389
13390   SDValue ShAmtOp = N->getOperand(1);
13391   EVT EltVT = VT.getVectorElementType();
13392   DebugLoc DL = N->getDebugLoc();
13393   SDValue BaseShAmt = SDValue();
13394   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13395     unsigned NumElts = VT.getVectorNumElements();
13396     unsigned i = 0;
13397     for (; i != NumElts; ++i) {
13398       SDValue Arg = ShAmtOp.getOperand(i);
13399       if (Arg.getOpcode() == ISD::UNDEF) continue;
13400       BaseShAmt = Arg;
13401       break;
13402     }
13403     // Handle the case where the build_vector is all undef
13404     // FIXME: Should DAG allow this?
13405     if (i == NumElts)
13406       return SDValue();
13407
13408     for (; i != NumElts; ++i) {
13409       SDValue Arg = ShAmtOp.getOperand(i);
13410       if (Arg.getOpcode() == ISD::UNDEF) continue;
13411       if (Arg != BaseShAmt) {
13412         return SDValue();
13413       }
13414     }
13415   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13416              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13417     SDValue InVec = ShAmtOp.getOperand(0);
13418     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13419       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13420       unsigned i = 0;
13421       for (; i != NumElts; ++i) {
13422         SDValue Arg = InVec.getOperand(i);
13423         if (Arg.getOpcode() == ISD::UNDEF) continue;
13424         BaseShAmt = Arg;
13425         break;
13426       }
13427     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13428        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13429          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13430          if (C->getZExtValue() == SplatIdx)
13431            BaseShAmt = InVec.getOperand(1);
13432        }
13433     }
13434     if (BaseShAmt.getNode() == 0)
13435       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13436                               DAG.getIntPtrConstant(0));
13437   } else
13438     return SDValue();
13439
13440   // The shift amount is an i32.
13441   if (EltVT.bitsGT(MVT::i32))
13442     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13443   else if (EltVT.bitsLT(MVT::i32))
13444     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13445
13446   // The shift amount is identical so we can do a vector shift.
13447   SDValue  ValOp = N->getOperand(0);
13448   switch (N->getOpcode()) {
13449   default:
13450     llvm_unreachable("Unknown shift opcode!");
13451   case ISD::SHL:
13452     switch (VT.getSimpleVT().SimpleTy) {
13453     default: return SDValue();
13454     case MVT::v2i64:
13455     case MVT::v4i32:
13456     case MVT::v8i16:
13457     case MVT::v4i64:
13458     case MVT::v8i32:
13459     case MVT::v16i16:
13460       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
13461     }
13462   case ISD::SRA:
13463     switch (VT.getSimpleVT().SimpleTy) {
13464     default: return SDValue();
13465     case MVT::v4i32:
13466     case MVT::v8i16:
13467     case MVT::v8i32:
13468     case MVT::v16i16:
13469       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
13470     }
13471   case ISD::SRL:
13472     switch (VT.getSimpleVT().SimpleTy) {
13473     default: return SDValue();
13474     case MVT::v2i64:
13475     case MVT::v4i32:
13476     case MVT::v8i16:
13477     case MVT::v4i64:
13478     case MVT::v8i32:
13479     case MVT::v16i16:
13480       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
13481     }
13482   }
13483 }
13484
13485
13486 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13487 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13488 // and friends.  Likewise for OR -> CMPNEQSS.
13489 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13490                             TargetLowering::DAGCombinerInfo &DCI,
13491                             const X86Subtarget *Subtarget) {
13492   unsigned opcode;
13493
13494   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13495   // we're requiring SSE2 for both.
13496   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13497     SDValue N0 = N->getOperand(0);
13498     SDValue N1 = N->getOperand(1);
13499     SDValue CMP0 = N0->getOperand(1);
13500     SDValue CMP1 = N1->getOperand(1);
13501     DebugLoc DL = N->getDebugLoc();
13502
13503     // The SETCCs should both refer to the same CMP.
13504     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13505       return SDValue();
13506
13507     SDValue CMP00 = CMP0->getOperand(0);
13508     SDValue CMP01 = CMP0->getOperand(1);
13509     EVT     VT    = CMP00.getValueType();
13510
13511     if (VT == MVT::f32 || VT == MVT::f64) {
13512       bool ExpectingFlags = false;
13513       // Check for any users that want flags:
13514       for (SDNode::use_iterator UI = N->use_begin(),
13515              UE = N->use_end();
13516            !ExpectingFlags && UI != UE; ++UI)
13517         switch (UI->getOpcode()) {
13518         default:
13519         case ISD::BR_CC:
13520         case ISD::BRCOND:
13521         case ISD::SELECT:
13522           ExpectingFlags = true;
13523           break;
13524         case ISD::CopyToReg:
13525         case ISD::SIGN_EXTEND:
13526         case ISD::ZERO_EXTEND:
13527         case ISD::ANY_EXTEND:
13528           break;
13529         }
13530
13531       if (!ExpectingFlags) {
13532         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13533         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13534
13535         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13536           X86::CondCode tmp = cc0;
13537           cc0 = cc1;
13538           cc1 = tmp;
13539         }
13540
13541         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13542             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13543           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13544           X86ISD::NodeType NTOperator = is64BitFP ?
13545             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13546           // FIXME: need symbolic constants for these magic numbers.
13547           // See X86ATTInstPrinter.cpp:printSSECC().
13548           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13549           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13550                                               DAG.getConstant(x86cc, MVT::i8));
13551           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13552                                               OnesOrZeroesF);
13553           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13554                                       DAG.getConstant(1, MVT::i32));
13555           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13556           return OneBitOfTruth;
13557         }
13558       }
13559     }
13560   }
13561   return SDValue();
13562 }
13563
13564 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13565 /// so it can be folded inside ANDNP.
13566 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13567   EVT VT = N->getValueType(0);
13568
13569   // Match direct AllOnes for 128 and 256-bit vectors
13570   if (ISD::isBuildVectorAllOnes(N))
13571     return true;
13572
13573   // Look through a bit convert.
13574   if (N->getOpcode() == ISD::BITCAST)
13575     N = N->getOperand(0).getNode();
13576
13577   // Sometimes the operand may come from a insert_subvector building a 256-bit
13578   // allones vector
13579   if (VT.getSizeInBits() == 256 &&
13580       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13581     SDValue V1 = N->getOperand(0);
13582     SDValue V2 = N->getOperand(1);
13583
13584     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13585         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13586         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13587         ISD::isBuildVectorAllOnes(V2.getNode()))
13588       return true;
13589   }
13590
13591   return false;
13592 }
13593
13594 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13595                                  TargetLowering::DAGCombinerInfo &DCI,
13596                                  const X86Subtarget *Subtarget) {
13597   if (DCI.isBeforeLegalizeOps())
13598     return SDValue();
13599
13600   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13601   if (R.getNode())
13602     return R;
13603
13604   EVT VT = N->getValueType(0);
13605
13606   // Create ANDN, BLSI, and BLSR instructions
13607   // BLSI is X & (-X)
13608   // BLSR is X & (X-1)
13609   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13610     SDValue N0 = N->getOperand(0);
13611     SDValue N1 = N->getOperand(1);
13612     DebugLoc DL = N->getDebugLoc();
13613
13614     // Check LHS for not
13615     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13616       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13617     // Check RHS for not
13618     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13619       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13620
13621     // Check LHS for neg
13622     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13623         isZero(N0.getOperand(0)))
13624       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13625
13626     // Check RHS for neg
13627     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13628         isZero(N1.getOperand(0)))
13629       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13630
13631     // Check LHS for X-1
13632     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13633         isAllOnes(N0.getOperand(1)))
13634       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13635
13636     // Check RHS for X-1
13637     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13638         isAllOnes(N1.getOperand(1)))
13639       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13640
13641     return SDValue();
13642   }
13643
13644   // Want to form ANDNP nodes:
13645   // 1) In the hopes of then easily combining them with OR and AND nodes
13646   //    to form PBLEND/PSIGN.
13647   // 2) To match ANDN packed intrinsics
13648   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13649     return SDValue();
13650
13651   SDValue N0 = N->getOperand(0);
13652   SDValue N1 = N->getOperand(1);
13653   DebugLoc DL = N->getDebugLoc();
13654
13655   // Check LHS for vnot
13656   if (N0.getOpcode() == ISD::XOR &&
13657       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13658       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13659     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13660
13661   // Check RHS for vnot
13662   if (N1.getOpcode() == ISD::XOR &&
13663       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13664       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13665     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13666
13667   return SDValue();
13668 }
13669
13670 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13671                                 TargetLowering::DAGCombinerInfo &DCI,
13672                                 const X86Subtarget *Subtarget) {
13673   if (DCI.isBeforeLegalizeOps())
13674     return SDValue();
13675
13676   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13677   if (R.getNode())
13678     return R;
13679
13680   EVT VT = N->getValueType(0);
13681
13682   SDValue N0 = N->getOperand(0);
13683   SDValue N1 = N->getOperand(1);
13684
13685   // look for psign/blend
13686   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13687     if (!Subtarget->hasSSSE3() ||
13688         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13689       return SDValue();
13690
13691     // Canonicalize pandn to RHS
13692     if (N0.getOpcode() == X86ISD::ANDNP)
13693       std::swap(N0, N1);
13694     // or (and (m, y), (pandn m, x))
13695     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13696       SDValue Mask = N1.getOperand(0);
13697       SDValue X    = N1.getOperand(1);
13698       SDValue Y;
13699       if (N0.getOperand(0) == Mask)
13700         Y = N0.getOperand(1);
13701       if (N0.getOperand(1) == Mask)
13702         Y = N0.getOperand(0);
13703
13704       // Check to see if the mask appeared in both the AND and ANDNP and
13705       if (!Y.getNode())
13706         return SDValue();
13707
13708       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13709       if (Mask.getOpcode() != ISD::BITCAST ||
13710           X.getOpcode() != ISD::BITCAST ||
13711           Y.getOpcode() != ISD::BITCAST)
13712         return SDValue();
13713
13714       // Look through mask bitcast.
13715       Mask = Mask.getOperand(0);
13716       EVT MaskVT = Mask.getValueType();
13717
13718       // Validate that the Mask operand is a vector sra node.
13719       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13720       // there is no psrai.b
13721       if (Mask.getOpcode() != X86ISD::VSRAI)
13722         return SDValue();
13723
13724       // Check that the SRA is all signbits.
13725       SDValue SraC = Mask.getOperand(1);
13726       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13727       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13728       if ((SraAmt + 1) != EltBits)
13729         return SDValue();
13730
13731       DebugLoc DL = N->getDebugLoc();
13732
13733       // Now we know we at least have a plendvb with the mask val.  See if
13734       // we can form a psignb/w/d.
13735       // psign = x.type == y.type == mask.type && y = sub(0, x);
13736       X = X.getOperand(0);
13737       Y = Y.getOperand(0);
13738       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13739           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13740           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
13741         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
13742                "Unsupported VT for PSIGN");
13743         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
13744         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13745       }
13746       // PBLENDVB only available on SSE 4.1
13747       if (!Subtarget->hasSSE41())
13748         return SDValue();
13749
13750       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
13751
13752       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
13753       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
13754       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
13755       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
13756       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
13757     }
13758   }
13759
13760   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
13761     return SDValue();
13762
13763   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13764   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13765     std::swap(N0, N1);
13766   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13767     return SDValue();
13768   if (!N0.hasOneUse() || !N1.hasOneUse())
13769     return SDValue();
13770
13771   SDValue ShAmt0 = N0.getOperand(1);
13772   if (ShAmt0.getValueType() != MVT::i8)
13773     return SDValue();
13774   SDValue ShAmt1 = N1.getOperand(1);
13775   if (ShAmt1.getValueType() != MVT::i8)
13776     return SDValue();
13777   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13778     ShAmt0 = ShAmt0.getOperand(0);
13779   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13780     ShAmt1 = ShAmt1.getOperand(0);
13781
13782   DebugLoc DL = N->getDebugLoc();
13783   unsigned Opc = X86ISD::SHLD;
13784   SDValue Op0 = N0.getOperand(0);
13785   SDValue Op1 = N1.getOperand(0);
13786   if (ShAmt0.getOpcode() == ISD::SUB) {
13787     Opc = X86ISD::SHRD;
13788     std::swap(Op0, Op1);
13789     std::swap(ShAmt0, ShAmt1);
13790   }
13791
13792   unsigned Bits = VT.getSizeInBits();
13793   if (ShAmt1.getOpcode() == ISD::SUB) {
13794     SDValue Sum = ShAmt1.getOperand(0);
13795     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13796       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13797       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13798         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13799       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13800         return DAG.getNode(Opc, DL, VT,
13801                            Op0, Op1,
13802                            DAG.getNode(ISD::TRUNCATE, DL,
13803                                        MVT::i8, ShAmt0));
13804     }
13805   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13806     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13807     if (ShAmt0C &&
13808         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13809       return DAG.getNode(Opc, DL, VT,
13810                          N0.getOperand(0), N1.getOperand(0),
13811                          DAG.getNode(ISD::TRUNCATE, DL,
13812                                        MVT::i8, ShAmt0));
13813   }
13814
13815   return SDValue();
13816 }
13817
13818 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
13819 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
13820                                  TargetLowering::DAGCombinerInfo &DCI,
13821                                  const X86Subtarget *Subtarget) {
13822   if (DCI.isBeforeLegalizeOps())
13823     return SDValue();
13824
13825   EVT VT = N->getValueType(0);
13826
13827   if (VT != MVT::i32 && VT != MVT::i64)
13828     return SDValue();
13829
13830   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
13831
13832   // Create BLSMSK instructions by finding X ^ (X-1)
13833   SDValue N0 = N->getOperand(0);
13834   SDValue N1 = N->getOperand(1);
13835   DebugLoc DL = N->getDebugLoc();
13836
13837   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13838       isAllOnes(N0.getOperand(1)))
13839     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
13840
13841   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13842       isAllOnes(N1.getOperand(1)))
13843     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
13844
13845   return SDValue();
13846 }
13847
13848 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13849 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13850                                    const X86Subtarget *Subtarget) {
13851   LoadSDNode *Ld = cast<LoadSDNode>(N);
13852   EVT RegVT = Ld->getValueType(0);
13853   EVT MemVT = Ld->getMemoryVT();
13854   DebugLoc dl = Ld->getDebugLoc();
13855   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13856
13857   ISD::LoadExtType Ext = Ld->getExtensionType();
13858
13859   // If this is a vector EXT Load then attempt to optimize it using a
13860   // shuffle. We need SSE4 for the shuffles.
13861   // TODO: It is possible to support ZExt by zeroing the undef values
13862   // during the shuffle phase or after the shuffle.
13863   if (RegVT.isVector() && RegVT.isInteger() &&
13864       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13865     assert(MemVT != RegVT && "Cannot extend to the same type");
13866     assert(MemVT.isVector() && "Must load a vector from memory");
13867
13868     unsigned NumElems = RegVT.getVectorNumElements();
13869     unsigned RegSz = RegVT.getSizeInBits();
13870     unsigned MemSz = MemVT.getSizeInBits();
13871     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13872     // All sizes must be a power of two
13873     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13874
13875     // Attempt to load the original value using a single load op.
13876     // Find a scalar type which is equal to the loaded word size.
13877     MVT SclrLoadTy = MVT::i8;
13878     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13879          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13880       MVT Tp = (MVT::SimpleValueType)tp;
13881       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13882         SclrLoadTy = Tp;
13883         break;
13884       }
13885     }
13886
13887     // Proceed if a load word is found.
13888     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13889
13890     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13891       RegSz/SclrLoadTy.getSizeInBits());
13892
13893     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13894                                   RegSz/MemVT.getScalarType().getSizeInBits());
13895     // Can't shuffle using an illegal type.
13896     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13897
13898     // Perform a single load.
13899     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13900                                   Ld->getBasePtr(),
13901                                   Ld->getPointerInfo(), Ld->isVolatile(),
13902                                   Ld->isNonTemporal(), Ld->isInvariant(),
13903                                   Ld->getAlignment());
13904
13905     // Insert the word loaded into a vector.
13906     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13907       LoadUnitVecVT, ScalarLoad);
13908
13909     // Bitcast the loaded value to a vector of the original element type, in
13910     // the size of the target vector type.
13911     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
13912                                     ScalarInVector);
13913     unsigned SizeRatio = RegSz/MemSz;
13914
13915     // Redistribute the loaded elements into the different locations.
13916     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13917     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13918
13919     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13920                                 DAG.getUNDEF(SlicedVec.getValueType()),
13921                                 ShuffleVec.data());
13922
13923     // Bitcast to the requested type.
13924     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13925     // Replace the original load with the new sequence
13926     // and return the new chain.
13927     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13928     return SDValue(ScalarLoad.getNode(), 1);
13929   }
13930
13931   return SDValue();
13932 }
13933
13934 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13935 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13936                                    const X86Subtarget *Subtarget) {
13937   StoreSDNode *St = cast<StoreSDNode>(N);
13938   EVT VT = St->getValue().getValueType();
13939   EVT StVT = St->getMemoryVT();
13940   DebugLoc dl = St->getDebugLoc();
13941   SDValue StoredVal = St->getOperand(1);
13942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13943
13944   // If we are saving a concatenation of two XMM registers, perform two stores.
13945   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13946   // 128-bit ones. If in the future the cost becomes only one memory access the
13947   // first version would be better.
13948   if (VT.getSizeInBits() == 256 &&
13949     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13950     StoredVal.getNumOperands() == 2) {
13951
13952     SDValue Value0 = StoredVal.getOperand(0);
13953     SDValue Value1 = StoredVal.getOperand(1);
13954
13955     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13956     SDValue Ptr0 = St->getBasePtr();
13957     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13958
13959     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13960                                 St->getPointerInfo(), St->isVolatile(),
13961                                 St->isNonTemporal(), St->getAlignment());
13962     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13963                                 St->getPointerInfo(), St->isVolatile(),
13964                                 St->isNonTemporal(), St->getAlignment());
13965     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13966   }
13967
13968   // Optimize trunc store (of multiple scalars) to shuffle and store.
13969   // First, pack all of the elements in one place. Next, store to memory
13970   // in fewer chunks.
13971   if (St->isTruncatingStore() && VT.isVector()) {
13972     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13973     unsigned NumElems = VT.getVectorNumElements();
13974     assert(StVT != VT && "Cannot truncate to the same type");
13975     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13976     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13977
13978     // From, To sizes and ElemCount must be pow of two
13979     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13980     // We are going to use the original vector elt for storing.
13981     // Accumulated smaller vector elements must be a multiple of the store size.
13982     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13983
13984     unsigned SizeRatio  = FromSz / ToSz;
13985
13986     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13987
13988     // Create a type on which we perform the shuffle
13989     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13990             StVT.getScalarType(), NumElems*SizeRatio);
13991
13992     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13993
13994     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13995     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13996     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13997
13998     // Can't shuffle using an illegal type
13999     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14000
14001     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14002                                 DAG.getUNDEF(WideVec.getValueType()),
14003                                 ShuffleVec.data());
14004     // At this point all of the data is stored at the bottom of the
14005     // register. We now need to save it to mem.
14006
14007     // Find the largest store unit
14008     MVT StoreType = MVT::i8;
14009     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14010          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14011       MVT Tp = (MVT::SimpleValueType)tp;
14012       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14013         StoreType = Tp;
14014     }
14015
14016     // Bitcast the original vector into a vector of store-size units
14017     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14018             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14019     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14020     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14021     SmallVector<SDValue, 8> Chains;
14022     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14023                                         TLI.getPointerTy());
14024     SDValue Ptr = St->getBasePtr();
14025
14026     // Perform one or more big stores into memory.
14027     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14028       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14029                                    StoreType, ShuffWide,
14030                                    DAG.getIntPtrConstant(i));
14031       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14032                                 St->getPointerInfo(), St->isVolatile(),
14033                                 St->isNonTemporal(), St->getAlignment());
14034       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14035       Chains.push_back(Ch);
14036     }
14037
14038     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14039                                Chains.size());
14040   }
14041
14042
14043   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14044   // the FP state in cases where an emms may be missing.
14045   // A preferable solution to the general problem is to figure out the right
14046   // places to insert EMMS.  This qualifies as a quick hack.
14047
14048   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14049   if (VT.getSizeInBits() != 64)
14050     return SDValue();
14051
14052   const Function *F = DAG.getMachineFunction().getFunction();
14053   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14054   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14055                      && Subtarget->hasSSE2();
14056   if ((VT.isVector() ||
14057        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14058       isa<LoadSDNode>(St->getValue()) &&
14059       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14060       St->getChain().hasOneUse() && !St->isVolatile()) {
14061     SDNode* LdVal = St->getValue().getNode();
14062     LoadSDNode *Ld = 0;
14063     int TokenFactorIndex = -1;
14064     SmallVector<SDValue, 8> Ops;
14065     SDNode* ChainVal = St->getChain().getNode();
14066     // Must be a store of a load.  We currently handle two cases:  the load
14067     // is a direct child, and it's under an intervening TokenFactor.  It is
14068     // possible to dig deeper under nested TokenFactors.
14069     if (ChainVal == LdVal)
14070       Ld = cast<LoadSDNode>(St->getChain());
14071     else if (St->getValue().hasOneUse() &&
14072              ChainVal->getOpcode() == ISD::TokenFactor) {
14073       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14074         if (ChainVal->getOperand(i).getNode() == LdVal) {
14075           TokenFactorIndex = i;
14076           Ld = cast<LoadSDNode>(St->getValue());
14077         } else
14078           Ops.push_back(ChainVal->getOperand(i));
14079       }
14080     }
14081
14082     if (!Ld || !ISD::isNormalLoad(Ld))
14083       return SDValue();
14084
14085     // If this is not the MMX case, i.e. we are just turning i64 load/store
14086     // into f64 load/store, avoid the transformation if there are multiple
14087     // uses of the loaded value.
14088     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14089       return SDValue();
14090
14091     DebugLoc LdDL = Ld->getDebugLoc();
14092     DebugLoc StDL = N->getDebugLoc();
14093     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14094     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14095     // pair instead.
14096     if (Subtarget->is64Bit() || F64IsLegal) {
14097       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14098       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14099                                   Ld->getPointerInfo(), Ld->isVolatile(),
14100                                   Ld->isNonTemporal(), Ld->isInvariant(),
14101                                   Ld->getAlignment());
14102       SDValue NewChain = NewLd.getValue(1);
14103       if (TokenFactorIndex != -1) {
14104         Ops.push_back(NewChain);
14105         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14106                                Ops.size());
14107       }
14108       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14109                           St->getPointerInfo(),
14110                           St->isVolatile(), St->isNonTemporal(),
14111                           St->getAlignment());
14112     }
14113
14114     // Otherwise, lower to two pairs of 32-bit loads / stores.
14115     SDValue LoAddr = Ld->getBasePtr();
14116     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14117                                  DAG.getConstant(4, MVT::i32));
14118
14119     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14120                                Ld->getPointerInfo(),
14121                                Ld->isVolatile(), Ld->isNonTemporal(),
14122                                Ld->isInvariant(), Ld->getAlignment());
14123     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14124                                Ld->getPointerInfo().getWithOffset(4),
14125                                Ld->isVolatile(), Ld->isNonTemporal(),
14126                                Ld->isInvariant(),
14127                                MinAlign(Ld->getAlignment(), 4));
14128
14129     SDValue NewChain = LoLd.getValue(1);
14130     if (TokenFactorIndex != -1) {
14131       Ops.push_back(LoLd);
14132       Ops.push_back(HiLd);
14133       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14134                              Ops.size());
14135     }
14136
14137     LoAddr = St->getBasePtr();
14138     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14139                          DAG.getConstant(4, MVT::i32));
14140
14141     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14142                                 St->getPointerInfo(),
14143                                 St->isVolatile(), St->isNonTemporal(),
14144                                 St->getAlignment());
14145     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14146                                 St->getPointerInfo().getWithOffset(4),
14147                                 St->isVolatile(),
14148                                 St->isNonTemporal(),
14149                                 MinAlign(St->getAlignment(), 4));
14150     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14151   }
14152   return SDValue();
14153 }
14154
14155 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14156 /// and return the operands for the horizontal operation in LHS and RHS.  A
14157 /// horizontal operation performs the binary operation on successive elements
14158 /// of its first operand, then on successive elements of its second operand,
14159 /// returning the resulting values in a vector.  For example, if
14160 ///   A = < float a0, float a1, float a2, float a3 >
14161 /// and
14162 ///   B = < float b0, float b1, float b2, float b3 >
14163 /// then the result of doing a horizontal operation on A and B is
14164 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14165 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14166 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14167 /// set to A, RHS to B, and the routine returns 'true'.
14168 /// Note that the binary operation should have the property that if one of the
14169 /// operands is UNDEF then the result is UNDEF.
14170 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14171   // Look for the following pattern: if
14172   //   A = < float a0, float a1, float a2, float a3 >
14173   //   B = < float b0, float b1, float b2, float b3 >
14174   // and
14175   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14176   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14177   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14178   // which is A horizontal-op B.
14179
14180   // At least one of the operands should be a vector shuffle.
14181   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14182       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14183     return false;
14184
14185   EVT VT = LHS.getValueType();
14186
14187   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14188          "Unsupported vector type for horizontal add/sub");
14189
14190   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14191   // operate independently on 128-bit lanes.
14192   unsigned NumElts = VT.getVectorNumElements();
14193   unsigned NumLanes = VT.getSizeInBits()/128;
14194   unsigned NumLaneElts = NumElts / NumLanes;
14195   assert((NumLaneElts % 2 == 0) &&
14196          "Vector type should have an even number of elements in each lane");
14197   unsigned HalfLaneElts = NumLaneElts/2;
14198
14199   // View LHS in the form
14200   //   LHS = VECTOR_SHUFFLE A, B, LMask
14201   // If LHS is not a shuffle then pretend it is the shuffle
14202   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14203   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14204   // type VT.
14205   SDValue A, B;
14206   SmallVector<int, 16> LMask(NumElts);
14207   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14208     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14209       A = LHS.getOperand(0);
14210     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14211       B = LHS.getOperand(1);
14212     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14213     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14214   } else {
14215     if (LHS.getOpcode() != ISD::UNDEF)
14216       A = LHS;
14217     for (unsigned i = 0; i != NumElts; ++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, 16> RMask(NumElts);
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     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14231     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14232   } else {
14233     if (RHS.getOpcode() != ISD::UNDEF)
14234       C = RHS;
14235     for (unsigned i = 0; i != NumElts; ++i)
14236       RMask[i] = i;
14237   }
14238
14239   // Check that the shuffles are both shuffling the same vectors.
14240   if (!(A == C && B == D) && !(A == D && B == C))
14241     return false;
14242
14243   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14244   if (!A.getNode() && !B.getNode())
14245     return false;
14246
14247   // If A and B occur in reverse order in RHS, then "swap" them (which means
14248   // rewriting the mask).
14249   if (A != C)
14250     CommuteVectorShuffleMask(RMask, NumElts);
14251
14252   // At this point LHS and RHS are equivalent to
14253   //   LHS = VECTOR_SHUFFLE A, B, LMask
14254   //   RHS = VECTOR_SHUFFLE A, B, RMask
14255   // Check that the masks correspond to performing a horizontal operation.
14256   for (unsigned i = 0; i != NumElts; ++i) {
14257     int LIdx = LMask[i], RIdx = RMask[i];
14258
14259     // Ignore any UNDEF components.
14260     if (LIdx < 0 || RIdx < 0 ||
14261         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14262         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14263       continue;
14264
14265     // Check that successive elements are being operated on.  If not, this is
14266     // not a horizontal operation.
14267     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14268     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14269     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14270     if (!(LIdx == Index && RIdx == Index + 1) &&
14271         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14272       return false;
14273   }
14274
14275   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14276   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14277   return true;
14278 }
14279
14280 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14281 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14282                                   const X86Subtarget *Subtarget) {
14283   EVT VT = N->getValueType(0);
14284   SDValue LHS = N->getOperand(0);
14285   SDValue RHS = N->getOperand(1);
14286
14287   // Try to synthesize horizontal adds from adds of shuffles.
14288   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14289        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14290       isHorizontalBinOp(LHS, RHS, true))
14291     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14292   return SDValue();
14293 }
14294
14295 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14296 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14297                                   const X86Subtarget *Subtarget) {
14298   EVT VT = N->getValueType(0);
14299   SDValue LHS = N->getOperand(0);
14300   SDValue RHS = N->getOperand(1);
14301
14302   // Try to synthesize horizontal subs from subs of shuffles.
14303   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14304        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14305       isHorizontalBinOp(LHS, RHS, false))
14306     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14307   return SDValue();
14308 }
14309
14310 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14311 /// X86ISD::FXOR nodes.
14312 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14313   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14314   // F[X]OR(0.0, x) -> x
14315   // F[X]OR(x, 0.0) -> x
14316   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14317     if (C->getValueAPF().isPosZero())
14318       return N->getOperand(1);
14319   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14320     if (C->getValueAPF().isPosZero())
14321       return N->getOperand(0);
14322   return SDValue();
14323 }
14324
14325 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14326 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14327   // FAND(0.0, x) -> 0.0
14328   // FAND(x, 0.0) -> 0.0
14329   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14330     if (C->getValueAPF().isPosZero())
14331       return N->getOperand(0);
14332   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14333     if (C->getValueAPF().isPosZero())
14334       return N->getOperand(1);
14335   return SDValue();
14336 }
14337
14338 static SDValue PerformBTCombine(SDNode *N,
14339                                 SelectionDAG &DAG,
14340                                 TargetLowering::DAGCombinerInfo &DCI) {
14341   // BT ignores high bits in the bit index operand.
14342   SDValue Op1 = N->getOperand(1);
14343   if (Op1.hasOneUse()) {
14344     unsigned BitWidth = Op1.getValueSizeInBits();
14345     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14346     APInt KnownZero, KnownOne;
14347     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14348                                           !DCI.isBeforeLegalizeOps());
14349     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14350     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14351         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14352       DCI.CommitTargetLoweringOpt(TLO);
14353   }
14354   return SDValue();
14355 }
14356
14357 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14358   SDValue Op = N->getOperand(0);
14359   if (Op.getOpcode() == ISD::BITCAST)
14360     Op = Op.getOperand(0);
14361   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14362   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14363       VT.getVectorElementType().getSizeInBits() ==
14364       OpVT.getVectorElementType().getSizeInBits()) {
14365     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14366   }
14367   return SDValue();
14368 }
14369
14370 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
14371                                   const X86Subtarget *Subtarget) {
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   EVT OpVT = N0.getValueType();
14380
14381   if (N0.getOpcode() == ISD::AND &&
14382       N0.hasOneUse() &&
14383       N0.getOperand(0).hasOneUse()) {
14384     SDValue N00 = N0.getOperand(0);
14385     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14386       return SDValue();
14387     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14388     if (!C || C->getZExtValue() != 1)
14389       return SDValue();
14390     return DAG.getNode(ISD::AND, dl, VT,
14391                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14392                                    N00.getOperand(0), N00.getOperand(1)),
14393                        DAG.getConstant(1, VT));
14394   }
14395   // Optimize vectors in AVX mode:
14396   //
14397   //   v8i16 -> v8i32
14398   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14399   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14400   //   Concat upper and lower parts.
14401   //
14402   //   v4i32 -> v4i64
14403   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14404   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14405   //   Concat upper and lower parts.
14406   //
14407   if (Subtarget->hasAVX()) {
14408
14409     if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16))  ||
14410       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
14411
14412       SDValue ZeroVec = getZeroVector(OpVT, Subtarget->hasSSE2(), Subtarget->hasAVX2(), 
14413         DAG, dl);
14414       SDValue OpLo = getTargetShuffleNode(X86ISD::UNPCKL, dl, OpVT, N0, ZeroVec, DAG);
14415       SDValue OpHi = getTargetShuffleNode(X86ISD::UNPCKH, dl, OpVT, N0, ZeroVec, DAG);
14416
14417       EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 
14418         VT.getVectorNumElements()/2);
14419
14420       OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14421       OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14422
14423       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14424     }
14425   }
14426
14427
14428   return SDValue();
14429 }
14430
14431 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14432 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14433   unsigned X86CC = N->getConstantOperandVal(0);
14434   SDValue EFLAG = N->getOperand(1);
14435   DebugLoc DL = N->getDebugLoc();
14436
14437   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14438   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14439   // cases.
14440   if (X86CC == X86::COND_B)
14441     return DAG.getNode(ISD::AND, DL, MVT::i8,
14442                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14443                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14444                        DAG.getConstant(1, MVT::i8));
14445
14446   return SDValue();
14447 }
14448
14449 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14450                                         const X86TargetLowering *XTLI) {
14451   SDValue Op0 = N->getOperand(0);
14452   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14453   // a 32-bit target where SSE doesn't support i64->FP operations.
14454   if (Op0.getOpcode() == ISD::LOAD) {
14455     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14456     EVT VT = Ld->getValueType(0);
14457     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14458         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14459         !XTLI->getSubtarget()->is64Bit() &&
14460         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14461       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14462                                           Ld->getChain(), Op0, DAG);
14463       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14464       return FILDChain;
14465     }
14466   }
14467   return SDValue();
14468 }
14469
14470 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14471 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14472                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14473   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14474   // the result is either zero or one (depending on the input carry bit).
14475   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14476   if (X86::isZeroNode(N->getOperand(0)) &&
14477       X86::isZeroNode(N->getOperand(1)) &&
14478       // We don't have a good way to replace an EFLAGS use, so only do this when
14479       // dead right now.
14480       SDValue(N, 1).use_empty()) {
14481     DebugLoc DL = N->getDebugLoc();
14482     EVT VT = N->getValueType(0);
14483     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14484     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14485                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14486                                            DAG.getConstant(X86::COND_B,MVT::i8),
14487                                            N->getOperand(2)),
14488                                DAG.getConstant(1, VT));
14489     return DCI.CombineTo(N, Res1, CarryOut);
14490   }
14491
14492   return SDValue();
14493 }
14494
14495 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14496 //      (add Y, (setne X, 0)) -> sbb -1, Y
14497 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14498 //      (sub (setne X, 0), Y) -> adc -1, Y
14499 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14500   DebugLoc DL = N->getDebugLoc();
14501
14502   // Look through ZExts.
14503   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14504   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14505     return SDValue();
14506
14507   SDValue SetCC = Ext.getOperand(0);
14508   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14509     return SDValue();
14510
14511   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14512   if (CC != X86::COND_E && CC != X86::COND_NE)
14513     return SDValue();
14514
14515   SDValue Cmp = SetCC.getOperand(1);
14516   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14517       !X86::isZeroNode(Cmp.getOperand(1)) ||
14518       !Cmp.getOperand(0).getValueType().isInteger())
14519     return SDValue();
14520
14521   SDValue CmpOp0 = Cmp.getOperand(0);
14522   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14523                                DAG.getConstant(1, CmpOp0.getValueType()));
14524
14525   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14526   if (CC == X86::COND_NE)
14527     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14528                        DL, OtherVal.getValueType(), OtherVal,
14529                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14530   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14531                      DL, OtherVal.getValueType(), OtherVal,
14532                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14533 }
14534
14535 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14536 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14537                                  const X86Subtarget *Subtarget) {
14538   EVT VT = N->getValueType(0);
14539   SDValue Op0 = N->getOperand(0);
14540   SDValue Op1 = N->getOperand(1);
14541
14542   // Try to synthesize horizontal adds from adds of shuffles.
14543   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14544        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14545       isHorizontalBinOp(Op0, Op1, true))
14546     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14547
14548   return OptimizeConditionalInDecrement(N, DAG);
14549 }
14550
14551 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14552                                  const X86Subtarget *Subtarget) {
14553   SDValue Op0 = N->getOperand(0);
14554   SDValue Op1 = N->getOperand(1);
14555
14556   // X86 can't encode an immediate LHS of a sub. See if we can push the
14557   // negation into a preceding instruction.
14558   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14559     // If the RHS of the sub is a XOR with one use and a constant, invert the
14560     // immediate. Then add one to the LHS of the sub so we can turn
14561     // X-Y -> X+~Y+1, saving one register.
14562     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14563         isa<ConstantSDNode>(Op1.getOperand(1))) {
14564       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14565       EVT VT = Op0.getValueType();
14566       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14567                                    Op1.getOperand(0),
14568                                    DAG.getConstant(~XorC, VT));
14569       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14570                          DAG.getConstant(C->getAPIntValue()+1, VT));
14571     }
14572   }
14573
14574   // Try to synthesize horizontal adds from adds of shuffles.
14575   EVT VT = N->getValueType(0);
14576   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
14577        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
14578       isHorizontalBinOp(Op0, Op1, true))
14579     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14580
14581   return OptimizeConditionalInDecrement(N, DAG);
14582 }
14583
14584 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14585                                              DAGCombinerInfo &DCI) const {
14586   SelectionDAG &DAG = DCI.DAG;
14587   switch (N->getOpcode()) {
14588   default: break;
14589   case ISD::EXTRACT_VECTOR_ELT:
14590     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14591   case ISD::VSELECT:
14592   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
14593   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14594   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14595   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14596   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14597   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14598   case ISD::SHL:
14599   case ISD::SRA:
14600   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14601   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14602   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14603   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14604   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14605   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14606   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14607   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14608   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14609   case X86ISD::FXOR:
14610   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14611   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14612   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14613   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14614   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, Subtarget);
14615   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14616   case X86ISD::SHUFP:       // Handle all target specific shuffles
14617   case X86ISD::PALIGN:
14618   case X86ISD::UNPCKH:
14619   case X86ISD::UNPCKL:
14620   case X86ISD::MOVHLPS:
14621   case X86ISD::MOVLHPS:
14622   case X86ISD::PSHUFD:
14623   case X86ISD::PSHUFHW:
14624   case X86ISD::PSHUFLW:
14625   case X86ISD::MOVSS:
14626   case X86ISD::MOVSD:
14627   case X86ISD::VPERMILP:
14628   case X86ISD::VPERM2X128:
14629   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14630   }
14631
14632   return SDValue();
14633 }
14634
14635 /// isTypeDesirableForOp - Return true if the target has native support for
14636 /// the specified value type and it is 'desirable' to use the type for the
14637 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14638 /// instruction encodings are longer and some i16 instructions are slow.
14639 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14640   if (!isTypeLegal(VT))
14641     return false;
14642   if (VT != MVT::i16)
14643     return true;
14644
14645   switch (Opc) {
14646   default:
14647     return true;
14648   case ISD::LOAD:
14649   case ISD::SIGN_EXTEND:
14650   case ISD::ZERO_EXTEND:
14651   case ISD::ANY_EXTEND:
14652   case ISD::SHL:
14653   case ISD::SRL:
14654   case ISD::SUB:
14655   case ISD::ADD:
14656   case ISD::MUL:
14657   case ISD::AND:
14658   case ISD::OR:
14659   case ISD::XOR:
14660     return false;
14661   }
14662 }
14663
14664 /// IsDesirableToPromoteOp - This method query the target whether it is
14665 /// beneficial for dag combiner to promote the specified node. If true, it
14666 /// should return the desired promotion type by reference.
14667 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14668   EVT VT = Op.getValueType();
14669   if (VT != MVT::i16)
14670     return false;
14671
14672   bool Promote = false;
14673   bool Commute = false;
14674   switch (Op.getOpcode()) {
14675   default: break;
14676   case ISD::LOAD: {
14677     LoadSDNode *LD = cast<LoadSDNode>(Op);
14678     // If the non-extending load has a single use and it's not live out, then it
14679     // might be folded.
14680     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14681                                                      Op.hasOneUse()*/) {
14682       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14683              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14684         // The only case where we'd want to promote LOAD (rather then it being
14685         // promoted as an operand is when it's only use is liveout.
14686         if (UI->getOpcode() != ISD::CopyToReg)
14687           return false;
14688       }
14689     }
14690     Promote = true;
14691     break;
14692   }
14693   case ISD::SIGN_EXTEND:
14694   case ISD::ZERO_EXTEND:
14695   case ISD::ANY_EXTEND:
14696     Promote = true;
14697     break;
14698   case ISD::SHL:
14699   case ISD::SRL: {
14700     SDValue N0 = Op.getOperand(0);
14701     // Look out for (store (shl (load), x)).
14702     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14703       return false;
14704     Promote = true;
14705     break;
14706   }
14707   case ISD::ADD:
14708   case ISD::MUL:
14709   case ISD::AND:
14710   case ISD::OR:
14711   case ISD::XOR:
14712     Commute = true;
14713     // fallthrough
14714   case ISD::SUB: {
14715     SDValue N0 = Op.getOperand(0);
14716     SDValue N1 = Op.getOperand(1);
14717     if (!Commute && MayFoldLoad(N1))
14718       return false;
14719     // Avoid disabling potential load folding opportunities.
14720     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14721       return false;
14722     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14723       return false;
14724     Promote = true;
14725   }
14726   }
14727
14728   PVT = MVT::i32;
14729   return Promote;
14730 }
14731
14732 //===----------------------------------------------------------------------===//
14733 //                           X86 Inline Assembly Support
14734 //===----------------------------------------------------------------------===//
14735
14736 namespace {
14737   // Helper to match a string separated by whitespace.
14738   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
14739     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
14740
14741     for (unsigned i = 0, e = args.size(); i != e; ++i) {
14742       StringRef piece(*args[i]);
14743       if (!s.startswith(piece)) // Check if the piece matches.
14744         return false;
14745
14746       s = s.substr(piece.size());
14747       StringRef::size_type pos = s.find_first_not_of(" \t");
14748       if (pos == 0) // We matched a prefix.
14749         return false;
14750
14751       s = s.substr(pos);
14752     }
14753
14754     return s.empty();
14755   }
14756   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
14757 }
14758
14759 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14760   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14761
14762   std::string AsmStr = IA->getAsmString();
14763
14764   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14765   if (!Ty || Ty->getBitWidth() % 16 != 0)
14766     return false;
14767
14768   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14769   SmallVector<StringRef, 4> AsmPieces;
14770   SplitString(AsmStr, AsmPieces, ";\n");
14771
14772   switch (AsmPieces.size()) {
14773   default: return false;
14774   case 1:
14775     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14776     // we will turn this bswap into something that will be lowered to logical
14777     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
14778     // lower so don't worry about this.
14779     // bswap $0
14780     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
14781         matchAsm(AsmPieces[0], "bswapl", "$0") ||
14782         matchAsm(AsmPieces[0], "bswapq", "$0") ||
14783         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
14784         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
14785         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
14786       // No need to check constraints, nothing other than the equivalent of
14787       // "=r,0" would be valid here.
14788       return IntrinsicLowering::LowerToByteSwap(CI);
14789     }
14790
14791     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14792     if (CI->getType()->isIntegerTy(16) &&
14793         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14794         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
14795          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
14796       AsmPieces.clear();
14797       const std::string &ConstraintsStr = IA->getConstraintString();
14798       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14799       std::sort(AsmPieces.begin(), AsmPieces.end());
14800       if (AsmPieces.size() == 4 &&
14801           AsmPieces[0] == "~{cc}" &&
14802           AsmPieces[1] == "~{dirflag}" &&
14803           AsmPieces[2] == "~{flags}" &&
14804           AsmPieces[3] == "~{fpsr}")
14805       return IntrinsicLowering::LowerToByteSwap(CI);
14806     }
14807     break;
14808   case 3:
14809     if (CI->getType()->isIntegerTy(32) &&
14810         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
14811         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
14812         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
14813         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
14814       AsmPieces.clear();
14815       const std::string &ConstraintsStr = IA->getConstraintString();
14816       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14817       std::sort(AsmPieces.begin(), AsmPieces.end());
14818       if (AsmPieces.size() == 4 &&
14819           AsmPieces[0] == "~{cc}" &&
14820           AsmPieces[1] == "~{dirflag}" &&
14821           AsmPieces[2] == "~{flags}" &&
14822           AsmPieces[3] == "~{fpsr}")
14823         return IntrinsicLowering::LowerToByteSwap(CI);
14824     }
14825
14826     if (CI->getType()->isIntegerTy(64)) {
14827       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14828       if (Constraints.size() >= 2 &&
14829           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14830           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14831         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14832         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
14833             matchAsm(AsmPieces[1], "bswap", "%edx") &&
14834             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
14835           return IntrinsicLowering::LowerToByteSwap(CI);
14836       }
14837     }
14838     break;
14839   }
14840   return false;
14841 }
14842
14843
14844
14845 /// getConstraintType - Given a constraint letter, return the type of
14846 /// constraint it is for this target.
14847 X86TargetLowering::ConstraintType
14848 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14849   if (Constraint.size() == 1) {
14850     switch (Constraint[0]) {
14851     case 'R':
14852     case 'q':
14853     case 'Q':
14854     case 'f':
14855     case 't':
14856     case 'u':
14857     case 'y':
14858     case 'x':
14859     case 'Y':
14860     case 'l':
14861       return C_RegisterClass;
14862     case 'a':
14863     case 'b':
14864     case 'c':
14865     case 'd':
14866     case 'S':
14867     case 'D':
14868     case 'A':
14869       return C_Register;
14870     case 'I':
14871     case 'J':
14872     case 'K':
14873     case 'L':
14874     case 'M':
14875     case 'N':
14876     case 'G':
14877     case 'C':
14878     case 'e':
14879     case 'Z':
14880       return C_Other;
14881     default:
14882       break;
14883     }
14884   }
14885   return TargetLowering::getConstraintType(Constraint);
14886 }
14887
14888 /// Examine constraint type and operand type and determine a weight value.
14889 /// This object must already have been set up with the operand type
14890 /// and the current alternative constraint selected.
14891 TargetLowering::ConstraintWeight
14892   X86TargetLowering::getSingleConstraintMatchWeight(
14893     AsmOperandInfo &info, const char *constraint) const {
14894   ConstraintWeight weight = CW_Invalid;
14895   Value *CallOperandVal = info.CallOperandVal;
14896     // If we don't have a value, we can't do a match,
14897     // but allow it at the lowest weight.
14898   if (CallOperandVal == NULL)
14899     return CW_Default;
14900   Type *type = CallOperandVal->getType();
14901   // Look at the constraint type.
14902   switch (*constraint) {
14903   default:
14904     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14905   case 'R':
14906   case 'q':
14907   case 'Q':
14908   case 'a':
14909   case 'b':
14910   case 'c':
14911   case 'd':
14912   case 'S':
14913   case 'D':
14914   case 'A':
14915     if (CallOperandVal->getType()->isIntegerTy())
14916       weight = CW_SpecificReg;
14917     break;
14918   case 'f':
14919   case 't':
14920   case 'u':
14921       if (type->isFloatingPointTy())
14922         weight = CW_SpecificReg;
14923       break;
14924   case 'y':
14925       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14926         weight = CW_SpecificReg;
14927       break;
14928   case 'x':
14929   case 'Y':
14930     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
14931         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
14932       weight = CW_Register;
14933     break;
14934   case 'I':
14935     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14936       if (C->getZExtValue() <= 31)
14937         weight = CW_Constant;
14938     }
14939     break;
14940   case 'J':
14941     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14942       if (C->getZExtValue() <= 63)
14943         weight = CW_Constant;
14944     }
14945     break;
14946   case 'K':
14947     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14948       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14949         weight = CW_Constant;
14950     }
14951     break;
14952   case 'L':
14953     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14954       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14955         weight = CW_Constant;
14956     }
14957     break;
14958   case 'M':
14959     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14960       if (C->getZExtValue() <= 3)
14961         weight = CW_Constant;
14962     }
14963     break;
14964   case 'N':
14965     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14966       if (C->getZExtValue() <= 0xff)
14967         weight = CW_Constant;
14968     }
14969     break;
14970   case 'G':
14971   case 'C':
14972     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14973       weight = CW_Constant;
14974     }
14975     break;
14976   case 'e':
14977     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14978       if ((C->getSExtValue() >= -0x80000000LL) &&
14979           (C->getSExtValue() <= 0x7fffffffLL))
14980         weight = CW_Constant;
14981     }
14982     break;
14983   case 'Z':
14984     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14985       if (C->getZExtValue() <= 0xffffffff)
14986         weight = CW_Constant;
14987     }
14988     break;
14989   }
14990   return weight;
14991 }
14992
14993 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14994 /// with another that has more specific requirements based on the type of the
14995 /// corresponding operand.
14996 const char *X86TargetLowering::
14997 LowerXConstraint(EVT ConstraintVT) const {
14998   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14999   // 'f' like normal targets.
15000   if (ConstraintVT.isFloatingPoint()) {
15001     if (Subtarget->hasSSE2())
15002       return "Y";
15003     if (Subtarget->hasSSE1())
15004       return "x";
15005   }
15006
15007   return TargetLowering::LowerXConstraint(ConstraintVT);
15008 }
15009
15010 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15011 /// vector.  If it is invalid, don't add anything to Ops.
15012 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15013                                                      std::string &Constraint,
15014                                                      std::vector<SDValue>&Ops,
15015                                                      SelectionDAG &DAG) const {
15016   SDValue Result(0, 0);
15017
15018   // Only support length 1 constraints for now.
15019   if (Constraint.length() > 1) return;
15020
15021   char ConstraintLetter = Constraint[0];
15022   switch (ConstraintLetter) {
15023   default: break;
15024   case 'I':
15025     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15026       if (C->getZExtValue() <= 31) {
15027         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15028         break;
15029       }
15030     }
15031     return;
15032   case 'J':
15033     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15034       if (C->getZExtValue() <= 63) {
15035         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15036         break;
15037       }
15038     }
15039     return;
15040   case 'K':
15041     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15042       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15043         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15044         break;
15045       }
15046     }
15047     return;
15048   case 'N':
15049     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15050       if (C->getZExtValue() <= 255) {
15051         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15052         break;
15053       }
15054     }
15055     return;
15056   case 'e': {
15057     // 32-bit signed value
15058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15059       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15060                                            C->getSExtValue())) {
15061         // Widen to 64 bits here to get it sign extended.
15062         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15063         break;
15064       }
15065     // FIXME gcc accepts some relocatable values here too, but only in certain
15066     // memory models; it's complicated.
15067     }
15068     return;
15069   }
15070   case 'Z': {
15071     // 32-bit unsigned value
15072     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15073       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15074                                            C->getZExtValue())) {
15075         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15076         break;
15077       }
15078     }
15079     // FIXME gcc accepts some relocatable values here too, but only in certain
15080     // memory models; it's complicated.
15081     return;
15082   }
15083   case 'i': {
15084     // Literal immediates are always ok.
15085     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15086       // Widen to 64 bits here to get it sign extended.
15087       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15088       break;
15089     }
15090
15091     // In any sort of PIC mode addresses need to be computed at runtime by
15092     // adding in a register or some sort of table lookup.  These can't
15093     // be used as immediates.
15094     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15095       return;
15096
15097     // If we are in non-pic codegen mode, we allow the address of a global (with
15098     // an optional displacement) to be used with 'i'.
15099     GlobalAddressSDNode *GA = 0;
15100     int64_t Offset = 0;
15101
15102     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15103     while (1) {
15104       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15105         Offset += GA->getOffset();
15106         break;
15107       } else if (Op.getOpcode() == ISD::ADD) {
15108         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15109           Offset += C->getZExtValue();
15110           Op = Op.getOperand(0);
15111           continue;
15112         }
15113       } else if (Op.getOpcode() == ISD::SUB) {
15114         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15115           Offset += -C->getZExtValue();
15116           Op = Op.getOperand(0);
15117           continue;
15118         }
15119       }
15120
15121       // Otherwise, this isn't something we can handle, reject it.
15122       return;
15123     }
15124
15125     const GlobalValue *GV = GA->getGlobal();
15126     // If we require an extra load to get this address, as in PIC mode, we
15127     // can't accept it.
15128     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15129                                                         getTargetMachine())))
15130       return;
15131
15132     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15133                                         GA->getValueType(0), Offset);
15134     break;
15135   }
15136   }
15137
15138   if (Result.getNode()) {
15139     Ops.push_back(Result);
15140     return;
15141   }
15142   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15143 }
15144
15145 std::pair<unsigned, const TargetRegisterClass*>
15146 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15147                                                 EVT VT) const {
15148   // First, see if this is a constraint that directly corresponds to an LLVM
15149   // register class.
15150   if (Constraint.size() == 1) {
15151     // GCC Constraint Letters
15152     switch (Constraint[0]) {
15153     default: break;
15154       // TODO: Slight differences here in allocation order and leaving
15155       // RIP in the class. Do they matter any more here than they do
15156       // in the normal allocation?
15157     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15158       if (Subtarget->is64Bit()) {
15159         if (VT == MVT::i32 || VT == MVT::f32)
15160           return std::make_pair(0U, X86::GR32RegisterClass);
15161         else if (VT == MVT::i16)
15162           return std::make_pair(0U, X86::GR16RegisterClass);
15163         else if (VT == MVT::i8 || VT == MVT::i1)
15164           return std::make_pair(0U, X86::GR8RegisterClass);
15165         else if (VT == MVT::i64 || VT == MVT::f64)
15166           return std::make_pair(0U, X86::GR64RegisterClass);
15167         break;
15168       }
15169       // 32-bit fallthrough
15170     case 'Q':   // Q_REGS
15171       if (VT == MVT::i32 || VT == MVT::f32)
15172         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15173       else if (VT == MVT::i16)
15174         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15175       else if (VT == MVT::i8 || VT == MVT::i1)
15176         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15177       else if (VT == MVT::i64)
15178         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15179       break;
15180     case 'r':   // GENERAL_REGS
15181     case 'l':   // INDEX_REGS
15182       if (VT == MVT::i8 || VT == MVT::i1)
15183         return std::make_pair(0U, X86::GR8RegisterClass);
15184       if (VT == MVT::i16)
15185         return std::make_pair(0U, X86::GR16RegisterClass);
15186       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15187         return std::make_pair(0U, X86::GR32RegisterClass);
15188       return std::make_pair(0U, X86::GR64RegisterClass);
15189     case 'R':   // LEGACY_REGS
15190       if (VT == MVT::i8 || VT == MVT::i1)
15191         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15192       if (VT == MVT::i16)
15193         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15194       if (VT == MVT::i32 || !Subtarget->is64Bit())
15195         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15196       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15197     case 'f':  // FP Stack registers.
15198       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15199       // value to the correct fpstack register class.
15200       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15201         return std::make_pair(0U, X86::RFP32RegisterClass);
15202       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15203         return std::make_pair(0U, X86::RFP64RegisterClass);
15204       return std::make_pair(0U, X86::RFP80RegisterClass);
15205     case 'y':   // MMX_REGS if MMX allowed.
15206       if (!Subtarget->hasMMX()) break;
15207       return std::make_pair(0U, X86::VR64RegisterClass);
15208     case 'Y':   // SSE_REGS if SSE2 allowed
15209       if (!Subtarget->hasSSE2()) break;
15210       // FALL THROUGH.
15211     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15212       if (!Subtarget->hasSSE1()) break;
15213
15214       switch (VT.getSimpleVT().SimpleTy) {
15215       default: break;
15216       // Scalar SSE types.
15217       case MVT::f32:
15218       case MVT::i32:
15219         return std::make_pair(0U, X86::FR32RegisterClass);
15220       case MVT::f64:
15221       case MVT::i64:
15222         return std::make_pair(0U, X86::FR64RegisterClass);
15223       // Vector types.
15224       case MVT::v16i8:
15225       case MVT::v8i16:
15226       case MVT::v4i32:
15227       case MVT::v2i64:
15228       case MVT::v4f32:
15229       case MVT::v2f64:
15230         return std::make_pair(0U, X86::VR128RegisterClass);
15231       // AVX types.
15232       case MVT::v32i8:
15233       case MVT::v16i16:
15234       case MVT::v8i32:
15235       case MVT::v4i64:
15236       case MVT::v8f32:
15237       case MVT::v4f64:
15238         return std::make_pair(0U, X86::VR256RegisterClass);
15239         
15240       }
15241       break;
15242     }
15243   }
15244
15245   // Use the default implementation in TargetLowering to convert the register
15246   // constraint into a member of a register class.
15247   std::pair<unsigned, const TargetRegisterClass*> Res;
15248   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15249
15250   // Not found as a standard register?
15251   if (Res.second == 0) {
15252     // Map st(0) -> st(7) -> ST0
15253     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15254         tolower(Constraint[1]) == 's' &&
15255         tolower(Constraint[2]) == 't' &&
15256         Constraint[3] == '(' &&
15257         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15258         Constraint[5] == ')' &&
15259         Constraint[6] == '}') {
15260
15261       Res.first = X86::ST0+Constraint[4]-'0';
15262       Res.second = X86::RFP80RegisterClass;
15263       return Res;
15264     }
15265
15266     // GCC allows "st(0)" to be called just plain "st".
15267     if (StringRef("{st}").equals_lower(Constraint)) {
15268       Res.first = X86::ST0;
15269       Res.second = X86::RFP80RegisterClass;
15270       return Res;
15271     }
15272
15273     // flags -> EFLAGS
15274     if (StringRef("{flags}").equals_lower(Constraint)) {
15275       Res.first = X86::EFLAGS;
15276       Res.second = X86::CCRRegisterClass;
15277       return Res;
15278     }
15279
15280     // 'A' means EAX + EDX.
15281     if (Constraint == "A") {
15282       Res.first = X86::EAX;
15283       Res.second = X86::GR32_ADRegisterClass;
15284       return Res;
15285     }
15286     return Res;
15287   }
15288
15289   // Otherwise, check to see if this is a register class of the wrong value
15290   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15291   // turn into {ax},{dx}.
15292   if (Res.second->hasType(VT))
15293     return Res;   // Correct type already, nothing to do.
15294
15295   // All of the single-register GCC register classes map their values onto
15296   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15297   // really want an 8-bit or 32-bit register, map to the appropriate register
15298   // class and return the appropriate register.
15299   if (Res.second == X86::GR16RegisterClass) {
15300     if (VT == MVT::i8) {
15301       unsigned DestReg = 0;
15302       switch (Res.first) {
15303       default: break;
15304       case X86::AX: DestReg = X86::AL; break;
15305       case X86::DX: DestReg = X86::DL; break;
15306       case X86::CX: DestReg = X86::CL; break;
15307       case X86::BX: DestReg = X86::BL; break;
15308       }
15309       if (DestReg) {
15310         Res.first = DestReg;
15311         Res.second = X86::GR8RegisterClass;
15312       }
15313     } else if (VT == MVT::i32) {
15314       unsigned DestReg = 0;
15315       switch (Res.first) {
15316       default: break;
15317       case X86::AX: DestReg = X86::EAX; break;
15318       case X86::DX: DestReg = X86::EDX; break;
15319       case X86::CX: DestReg = X86::ECX; break;
15320       case X86::BX: DestReg = X86::EBX; break;
15321       case X86::SI: DestReg = X86::ESI; break;
15322       case X86::DI: DestReg = X86::EDI; break;
15323       case X86::BP: DestReg = X86::EBP; break;
15324       case X86::SP: DestReg = X86::ESP; break;
15325       }
15326       if (DestReg) {
15327         Res.first = DestReg;
15328         Res.second = X86::GR32RegisterClass;
15329       }
15330     } else if (VT == MVT::i64) {
15331       unsigned DestReg = 0;
15332       switch (Res.first) {
15333       default: break;
15334       case X86::AX: DestReg = X86::RAX; break;
15335       case X86::DX: DestReg = X86::RDX; break;
15336       case X86::CX: DestReg = X86::RCX; break;
15337       case X86::BX: DestReg = X86::RBX; break;
15338       case X86::SI: DestReg = X86::RSI; break;
15339       case X86::DI: DestReg = X86::RDI; break;
15340       case X86::BP: DestReg = X86::RBP; break;
15341       case X86::SP: DestReg = X86::RSP; break;
15342       }
15343       if (DestReg) {
15344         Res.first = DestReg;
15345         Res.second = X86::GR64RegisterClass;
15346       }
15347     }
15348   } else if (Res.second == X86::FR32RegisterClass ||
15349              Res.second == X86::FR64RegisterClass ||
15350              Res.second == X86::VR128RegisterClass) {
15351     // Handle references to XMM physical registers that got mapped into the
15352     // wrong class.  This can happen with constraints like {xmm0} where the
15353     // target independent register mapper will just pick the first match it can
15354     // find, ignoring the required type.
15355     if (VT == MVT::f32)
15356       Res.second = X86::FR32RegisterClass;
15357     else if (VT == MVT::f64)
15358       Res.second = X86::FR64RegisterClass;
15359     else if (X86::VR128RegisterClass->hasType(VT))
15360       Res.second = X86::VR128RegisterClass;
15361   }
15362
15363   return Res;
15364 }