Use 256-bit alignment for constant pool value for 256-bit vector FNEG lowering.
[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 "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.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/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getTargetData();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   // Bypass i32 with i8 on Atom when compiling with O2
186   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187     addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
188
189   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190     // Setup Windows compiler runtime calls.
191     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193     setLibcallName(RTLIB::SREM_I64, "_allrem");
194     setLibcallName(RTLIB::UREM_I64, "_aullrem");
195     setLibcallName(RTLIB::MUL_I64, "_allmul");
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
202     // The _ftol2 runtime function has an unusual calling conv, which
203     // is modeled by a special pseudo-instruction.
204     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, &X86::GR8RegClass);
225   addRegisterClass(MVT::i16, &X86::GR16RegClass);
226   addRegisterClass(MVT::i32, &X86::GR32RegClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257   } else if (!TM.Options.UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!TM.Options.UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!TM.Options.UseSoftFloat) {
315     // Since AVX is a superset of SSE3, only check for SSE here.
316     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317       // Expand FP_TO_UINT into a select.
318       // FIXME: We would like to use a Custom expander here eventually to do
319       // the optimal thing for SSE vs. the default expansion in the legalizer.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321     else
322       // With SSE3 we can use fisttpll to convert to a signed i64; without
323       // SSE, we're stuck with a fistpll.
324       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325   }
326
327   if (isTargetFTOL()) {
328     // Use the _ftol2 runtime function, which has a pseudo-instruction
329     // to handle its weird calling convention.
330     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331   }
332
333   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334   if (!X86ScalarSSEf64) {
335     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337     if (Subtarget->is64Bit()) {
338       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339       // Without SSE, i64->f64 goes through memory.
340       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341     }
342   }
343
344   // Scalar integer divide and remainder are lowered to use operations that
345   // produce two results, to match the available instructions. This exposes
346   // the two-result form to trivial CSE, which is able to combine x/y and x%y
347   // into a single instruction.
348   //
349   // Scalar integer multiply-high is also lowered to use two-result
350   // operations, to match the available instructions. However, plain multiply
351   // (low) operations are left as Legal, as there are single-result
352   // instructions for this in x86. Using the two-result multiply instructions
353   // when both high and low results are needed must be arranged by dagcombine.
354   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355     MVT VT = IntVTs[i];
356     setOperationAction(ISD::MULHS, VT, Expand);
357     setOperationAction(ISD::MULHU, VT, Expand);
358     setOperationAction(ISD::SDIV, VT, Expand);
359     setOperationAction(ISD::UDIV, VT, Expand);
360     setOperationAction(ISD::SREM, VT, Expand);
361     setOperationAction(ISD::UREM, VT, Expand);
362
363     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364     setOperationAction(ISD::ADDC, VT, Custom);
365     setOperationAction(ISD::ADDE, VT, Custom);
366     setOperationAction(ISD::SUBC, VT, Custom);
367     setOperationAction(ISD::SUBE, VT, Custom);
368   }
369
370   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374   if (Subtarget->is64Bit())
375     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385   // Promote the i8 variants and force them on up to i32 which has a shorter
386   // encoding.
387   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391   if (Subtarget->hasBMI()) {
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396   } else {
397     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399     if (Subtarget->is64Bit())
400       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401   }
402
403   if (Subtarget->hasLZCNT()) {
404     // When promoting the i8 variants, force them to i32 for a shorter
405     // encoding.
406     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412     if (Subtarget->is64Bit())
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414   } else {
415     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421     if (Subtarget->is64Bit()) {
422       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424     }
425   }
426
427   if (Subtarget->hasPOPCNT()) {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429   } else {
430     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433     if (Subtarget->is64Bit())
434       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435   }
436
437   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440   // These should be promoted to a larger select which is supported.
441   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442   // X86 wants to expand cmov itself.
443   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458   }
459   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460
461   // Darwin ABI issue.
462   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
463   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
464   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
465   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
469   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
470   if (Subtarget->is64Bit()) {
471     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
472     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
473     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
474     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
475     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
476   }
477   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
479   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
480   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
481   if (Subtarget->is64Bit()) {
482     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
483     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
484     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
485   }
486
487   if (Subtarget->hasSSE1())
488     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
489
490   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
491   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
492
493   // On X86 and X86-64, atomic operations are lowered to locked instructions.
494   // Locked instructions, in turn, have implicit fence semantics (all memory
495   // operations are flushed before issuing the locked instruction, and they
496   // are not buffered), so we can fold away the common pattern of
497   // fence-atomic-fence.
498   setShouldFoldAtomicFences(true);
499
500   // Expand certain atomics
501   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
502     MVT VT = IntVTs[i];
503     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506   }
507
508   if (!Subtarget->is64Bit()) {
509     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517   }
518
519   if (Subtarget->hasCmpxchg16b()) {
520     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
521   }
522
523   // FIXME - use subtarget debug flags
524   if (!Subtarget->isTargetDarwin() &&
525       !Subtarget->isTargetELF() &&
526       !Subtarget->isTargetCygMing()) {
527     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528   }
529
530   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
532   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
534   if (Subtarget->is64Bit()) {
535     setExceptionPointerRegister(X86::RAX);
536     setExceptionSelectorRegister(X86::RDX);
537   } else {
538     setExceptionPointerRegister(X86::EAX);
539     setExceptionSelectorRegister(X86::EDX);
540   }
541   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
543
544   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
546
547   setOperationAction(ISD::TRAP, MVT::Other, Legal);
548
549   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
551   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
552   if (Subtarget->is64Bit()) {
553     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
554     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
555   } else {
556     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
557     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
558   }
559
560   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
561   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
562
563   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565                        MVT::i64 : MVT::i32, Custom);
566   else if (TM.Options.EnableSegmentedStacks)
567     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568                        MVT::i64 : MVT::i32, Custom);
569   else
570     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571                        MVT::i64 : MVT::i32, Expand);
572
573   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574     // f32 and f64 use SSE.
575     // Set up the FP register classes.
576     addRegisterClass(MVT::f32, &X86::FR32RegClass);
577     addRegisterClass(MVT::f64, &X86::FR64RegClass);
578
579     // Use ANDPD to simulate FABS.
580     setOperationAction(ISD::FABS , MVT::f64, Custom);
581     setOperationAction(ISD::FABS , MVT::f32, Custom);
582
583     // Use XORP to simulate FNEG.
584     setOperationAction(ISD::FNEG , MVT::f64, Custom);
585     setOperationAction(ISD::FNEG , MVT::f32, Custom);
586
587     // Use ANDPD and ORPD to simulate FCOPYSIGN.
588     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
590
591     // Lower this to FGETSIGNx86 plus an AND.
592     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
594
595     // We don't support sin/cos/fmod
596     setOperationAction(ISD::FSIN , MVT::f64, Expand);
597     setOperationAction(ISD::FCOS , MVT::f64, Expand);
598     setOperationAction(ISD::FSIN , MVT::f32, Expand);
599     setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601     // Expand FP immediates into loads from the stack, except for the special
602     // cases we handle.
603     addLegalFPImmediate(APFloat(+0.0)); // xorpd
604     addLegalFPImmediate(APFloat(+0.0f)); // xorps
605   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606     // Use SSE for f32, x87 for f64.
607     // Set up the FP register classes.
608     addRegisterClass(MVT::f32, &X86::FR32RegClass);
609     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
610
611     // Use ANDPS to simulate FABS.
612     setOperationAction(ISD::FABS , MVT::f32, Custom);
613
614     // Use XORP to simulate FNEG.
615     setOperationAction(ISD::FNEG , MVT::f32, Custom);
616
617     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
618
619     // Use ANDPS and ORPS to simulate FCOPYSIGN.
620     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
622
623     // We don't support sin/cos/fmod
624     setOperationAction(ISD::FSIN , MVT::f32, Expand);
625     setOperationAction(ISD::FCOS , MVT::f32, Expand);
626
627     // Special cases we handle for FP constants.
628     addLegalFPImmediate(APFloat(+0.0f)); // xorps
629     addLegalFPImmediate(APFloat(+0.0)); // FLD0
630     addLegalFPImmediate(APFloat(+1.0)); // FLD1
631     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633
634     if (!TM.Options.UnsafeFPMath) {
635       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
636       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
637     }
638   } else if (!TM.Options.UseSoftFloat) {
639     // f32 and f64 in x87.
640     // Set up the FP register classes.
641     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
643
644     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
645     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
648
649     if (!TM.Options.UnsafeFPMath) {
650       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
651       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
652     }
653     addLegalFPImmediate(APFloat(+0.0)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
661   }
662
663   // We don't support FMA.
664   setOperationAction(ISD::FMA, MVT::f64, Expand);
665   setOperationAction(ISD::FMA, MVT::f32, Expand);
666
667   // Long double always uses X87.
668   if (!TM.Options.UseSoftFloat) {
669     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
672     {
673       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674       addLegalFPImmediate(TmpFlt);  // FLD0
675       TmpFlt.changeSign();
676       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
677
678       bool ignored;
679       APFloat TmpFlt2(+1.0);
680       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
681                       &ignored);
682       addLegalFPImmediate(TmpFlt2);  // FLD1
683       TmpFlt2.changeSign();
684       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
685     }
686
687     if (!TM.Options.UnsafeFPMath) {
688       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
689       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
690     }
691
692     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
694     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
696     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697     setOperationAction(ISD::FMA, MVT::f80, Expand);
698   }
699
700   // Always use a library call for pow.
701   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
702   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
703   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
704
705   setOperationAction(ISD::FLOG, MVT::f80, Expand);
706   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708   setOperationAction(ISD::FEXP, MVT::f80, Expand);
709   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
710
711   // First set operation action for all vector types to either promote
712   // (for widening) or expand (for scalarization). Then we will selectively
713   // turn on ones that can be effectively codegen'd.
714   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
775     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777       setTruncStoreAction((MVT::SimpleValueType)VT,
778                           (MVT::SimpleValueType)InnerVT, Expand);
779     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
782   }
783
784   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785   // with -msoft-float, disable use of MMX as well.
786   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788     // No operations on x86mmx supported, everything uses intrinsics.
789   }
790
791   // MMX-sized vectors (other than x86mmx) are expected to be expanded
792   // into smaller operations.
793   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
794   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
795   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
796   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
797   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
798   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
799   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
800   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
801   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
802   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
803   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
804   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
805   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
806   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
807   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
808   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
809   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
810   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
811   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
812   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
813   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
814   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
815   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
816   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
817   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
818   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
819   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
820   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
821   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
822
823   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
825
826     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
832     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
833     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
834     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
835     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
836     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
838   }
839
840   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
842
843     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844     // registers cannot be used even for integer operations.
845     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
849
850     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
851     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
852     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
853     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
854     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
855     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
856     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
857     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
858     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
859     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
860     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
861     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
862     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
863     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
864     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
865     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
866     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
867
868     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
869     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
870     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
871     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
872
873     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
874     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
877     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
878
879     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881       MVT VT = (MVT::SimpleValueType)i;
882       // Do not attempt to custom lower non-power-of-2 vectors
883       if (!isPowerOf2_32(VT.getVectorNumElements()))
884         continue;
885       // Do not attempt to custom lower non-128-bit vectors
886       if (!VT.is128BitVector())
887         continue;
888       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
889       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891     }
892
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900     if (Subtarget->is64Bit()) {
901       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903     }
904
905     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907       MVT VT = (MVT::SimpleValueType)i;
908
909       // Do not attempt to promote non-128-bit vectors
910       if (!VT.is128BitVector())
911         continue;
912
913       setOperationAction(ISD::AND,    VT, Promote);
914       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915       setOperationAction(ISD::OR,     VT, Promote);
916       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917       setOperationAction(ISD::XOR,    VT, Promote);
918       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919       setOperationAction(ISD::LOAD,   VT, Promote);
920       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921       setOperationAction(ISD::SELECT, VT, Promote);
922       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923     }
924
925     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
926
927     // Custom lower v2i64 and v2f64 selects.
928     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
929     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
930     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
931     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
932
933     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
934     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
935   }
936
937   if (Subtarget->hasSSE41()) {
938     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
939     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
940     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
941     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
942     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
943     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
944     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
945     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
946     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
947     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
948
949     // FIXME: Do we need to handle scalar-to-vector here?
950     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
951
952     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
954     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
956     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
957
958     // i8 and i16 vectors are custom , because the source register and source
959     // source memory operand types are not the same width.  f32 vectors are
960     // custom since the immediate controlling the insert encodes additional
961     // information.
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
968     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
970     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
971
972     // FIXME: these should be Legal but thats only for the case where
973     // the index is constant.  For now custom expand to deal with that.
974     if (Subtarget->is64Bit()) {
975       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
976       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
977     }
978   }
979
980   if (Subtarget->hasSSE2()) {
981     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
982     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
983
984     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
986
987     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
988     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
989
990     if (Subtarget->hasAVX2()) {
991       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
992       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
993
994       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
995       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
996
997       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
998     } else {
999       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1000       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1001
1002       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1003       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1004
1005       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1006     }
1007   }
1008
1009   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1011     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1013     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1015     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1016
1017     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1020
1021     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1027     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1028
1029     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1033     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1034     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1035     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1036
1037     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1038     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1039     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1040
1041     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1042     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1043
1044     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1045     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1046
1047     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1048     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1049
1050     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1051     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1052     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1053     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1054
1055     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1056     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1057     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1058
1059     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1060     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1061     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1062     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1063
1064     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1065       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1066       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1067       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1068       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1069       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1070       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1071     }
1072
1073     if (Subtarget->hasAVX2()) {
1074       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1075       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1076       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1077       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1078
1079       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1080       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1081       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1082       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1083
1084       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1085       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1086       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1087       // Don't lower v32i8 because there is no 128-bit byte mul
1088
1089       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1090
1091       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1092       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1093
1094       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1095       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1096
1097       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1098     } else {
1099       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1100       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1101       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1102       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1103
1104       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1105       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1106       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1107       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1108
1109       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1110       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1111       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1112       // Don't lower v32i8 because there is no 128-bit byte mul
1113
1114       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1116
1117       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1118       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1119
1120       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1121     }
1122
1123     // Custom lower several nodes for 256-bit types.
1124     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1125              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1126       MVT VT = (MVT::SimpleValueType)i;
1127
1128       // Extract subvector is special because the value type
1129       // (result) is 128-bit but the source is 256-bit wide.
1130       if (VT.is128BitVector())
1131         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1132
1133       // Do not attempt to custom lower other non-256-bit vectors
1134       if (!VT.is256BitVector())
1135         continue;
1136
1137       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1138       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1139       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1140       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1141       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1142       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1143       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1144     }
1145
1146     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1147     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1148       MVT VT = (MVT::SimpleValueType)i;
1149
1150       // Do not attempt to promote non-256-bit vectors
1151       if (!VT.is256BitVector())
1152         continue;
1153
1154       setOperationAction(ISD::AND,    VT, Promote);
1155       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1156       setOperationAction(ISD::OR,     VT, Promote);
1157       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1158       setOperationAction(ISD::XOR,    VT, Promote);
1159       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1160       setOperationAction(ISD::LOAD,   VT, Promote);
1161       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1162       setOperationAction(ISD::SELECT, VT, Promote);
1163       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1164     }
1165   }
1166
1167   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1168   // of this type with custom code.
1169   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1170            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1171     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1172                        Custom);
1173   }
1174
1175   // We want to custom lower some of our intrinsics.
1176   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1177   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1178
1179
1180   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1181   // handle type legalization for these operations here.
1182   //
1183   // FIXME: We really should do custom legalization for addition and
1184   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1185   // than generic legalization for 64-bit multiplication-with-overflow, though.
1186   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1187     // Add/Sub/Mul with overflow operations are custom lowered.
1188     MVT VT = IntVTs[i];
1189     setOperationAction(ISD::SADDO, VT, Custom);
1190     setOperationAction(ISD::UADDO, VT, Custom);
1191     setOperationAction(ISD::SSUBO, VT, Custom);
1192     setOperationAction(ISD::USUBO, VT, Custom);
1193     setOperationAction(ISD::SMULO, VT, Custom);
1194     setOperationAction(ISD::UMULO, VT, Custom);
1195   }
1196
1197   // There are no 8-bit 3-address imul/mul instructions
1198   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1199   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1200
1201   if (!Subtarget->is64Bit()) {
1202     // These libcalls are not available in 32-bit.
1203     setLibcallName(RTLIB::SHL_I128, 0);
1204     setLibcallName(RTLIB::SRL_I128, 0);
1205     setLibcallName(RTLIB::SRA_I128, 0);
1206   }
1207
1208   // We have target-specific dag combine patterns for the following nodes:
1209   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1210   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1211   setTargetDAGCombine(ISD::VSELECT);
1212   setTargetDAGCombine(ISD::SELECT);
1213   setTargetDAGCombine(ISD::SHL);
1214   setTargetDAGCombine(ISD::SRA);
1215   setTargetDAGCombine(ISD::SRL);
1216   setTargetDAGCombine(ISD::OR);
1217   setTargetDAGCombine(ISD::AND);
1218   setTargetDAGCombine(ISD::ADD);
1219   setTargetDAGCombine(ISD::FADD);
1220   setTargetDAGCombine(ISD::FSUB);
1221   setTargetDAGCombine(ISD::FMA);
1222   setTargetDAGCombine(ISD::SUB);
1223   setTargetDAGCombine(ISD::LOAD);
1224   setTargetDAGCombine(ISD::STORE);
1225   setTargetDAGCombine(ISD::ZERO_EXTEND);
1226   setTargetDAGCombine(ISD::ANY_EXTEND);
1227   setTargetDAGCombine(ISD::SIGN_EXTEND);
1228   setTargetDAGCombine(ISD::TRUNCATE);
1229   setTargetDAGCombine(ISD::UINT_TO_FP);
1230   setTargetDAGCombine(ISD::SINT_TO_FP);
1231   setTargetDAGCombine(ISD::SETCC);
1232   setTargetDAGCombine(ISD::FP_TO_SINT);
1233   if (Subtarget->is64Bit())
1234     setTargetDAGCombine(ISD::MUL);
1235   setTargetDAGCombine(ISD::XOR);
1236
1237   computeRegisterProperties();
1238
1239   // On Darwin, -Os means optimize for size without hurting performance,
1240   // do not reduce the limit.
1241   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1242   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1243   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1244   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1245   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1246   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1247   setPrefLoopAlignment(4); // 2^4 bytes.
1248   benefitFromCodePlacementOpt = true;
1249
1250   // Predictable cmov don't hurt on atom because it's in-order.
1251   predictableSelectIsExpensive = !Subtarget->isAtom();
1252
1253   setPrefFunctionAlignment(4); // 2^4 bytes.
1254 }
1255
1256
1257 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1258   if (!VT.isVector()) return MVT::i8;
1259   return VT.changeVectorElementTypeToInteger();
1260 }
1261
1262
1263 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1264 /// the desired ByVal argument alignment.
1265 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1266   if (MaxAlign == 16)
1267     return;
1268   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1269     if (VTy->getBitWidth() == 128)
1270       MaxAlign = 16;
1271   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1272     unsigned EltAlign = 0;
1273     getMaxByValAlign(ATy->getElementType(), EltAlign);
1274     if (EltAlign > MaxAlign)
1275       MaxAlign = EltAlign;
1276   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1277     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278       unsigned EltAlign = 0;
1279       getMaxByValAlign(STy->getElementType(i), EltAlign);
1280       if (EltAlign > MaxAlign)
1281         MaxAlign = EltAlign;
1282       if (MaxAlign == 16)
1283         break;
1284     }
1285   }
1286 }
1287
1288 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1289 /// function arguments in the caller parameter area. For X86, aggregates
1290 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1291 /// are at 4-byte boundaries.
1292 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1293   if (Subtarget->is64Bit()) {
1294     // Max of 8 and alignment of type.
1295     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1296     if (TyAlign > 8)
1297       return TyAlign;
1298     return 8;
1299   }
1300
1301   unsigned Align = 4;
1302   if (Subtarget->hasSSE1())
1303     getMaxByValAlign(Ty, Align);
1304   return Align;
1305 }
1306
1307 /// getOptimalMemOpType - Returns the target specific optimal type for load
1308 /// and store operations as a result of memset, memcpy, and memmove
1309 /// lowering. If DstAlign is zero that means it's safe to destination
1310 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1311 /// means there isn't a need to check it against alignment requirement,
1312 /// probably because the source does not need to be loaded. If
1313 /// 'IsZeroVal' is true, that means it's safe to return a
1314 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1315 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1316 /// constant so it does not need to be loaded.
1317 /// It returns EVT::Other if the type should be determined using generic
1318 /// target-independent logic.
1319 EVT
1320 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1321                                        unsigned DstAlign, unsigned SrcAlign,
1322                                        bool IsZeroVal,
1323                                        bool MemcpyStrSrc,
1324                                        MachineFunction &MF) const {
1325   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1326   // linux.  This is because the stack realignment code can't handle certain
1327   // cases like PR2962.  This should be removed when PR2962 is fixed.
1328   const Function *F = MF.getFunction();
1329   if (IsZeroVal &&
1330       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1331     if (Size >= 16 &&
1332         (Subtarget->isUnalignedMemAccessFast() ||
1333          ((DstAlign == 0 || DstAlign >= 16) &&
1334           (SrcAlign == 0 || SrcAlign >= 16))) &&
1335         Subtarget->getStackAlignment() >= 16) {
1336       if (Subtarget->getStackAlignment() >= 32) {
1337         if (Subtarget->hasAVX2())
1338           return MVT::v8i32;
1339         if (Subtarget->hasAVX())
1340           return MVT::v8f32;
1341       }
1342       if (Subtarget->hasSSE2())
1343         return MVT::v4i32;
1344       if (Subtarget->hasSSE1())
1345         return MVT::v4f32;
1346     } else if (!MemcpyStrSrc && Size >= 8 &&
1347                !Subtarget->is64Bit() &&
1348                Subtarget->getStackAlignment() >= 8 &&
1349                Subtarget->hasSSE2()) {
1350       // Do not use f64 to lower memcpy if source is string constant. It's
1351       // better to use i32 to avoid the loads.
1352       return MVT::f64;
1353     }
1354   }
1355   if (Subtarget->is64Bit() && Size >= 8)
1356     return MVT::i64;
1357   return MVT::i32;
1358 }
1359
1360 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1361 /// current function.  The returned value is a member of the
1362 /// MachineJumpTableInfo::JTEntryKind enum.
1363 unsigned X86TargetLowering::getJumpTableEncoding() const {
1364   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1365   // symbol.
1366   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1367       Subtarget->isPICStyleGOT())
1368     return MachineJumpTableInfo::EK_Custom32;
1369
1370   // Otherwise, use the normal jump table encoding heuristics.
1371   return TargetLowering::getJumpTableEncoding();
1372 }
1373
1374 const MCExpr *
1375 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1376                                              const MachineBasicBlock *MBB,
1377                                              unsigned uid,MCContext &Ctx) const{
1378   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1379          Subtarget->isPICStyleGOT());
1380   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1381   // entries.
1382   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1383                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1384 }
1385
1386 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1387 /// jumptable.
1388 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1389                                                     SelectionDAG &DAG) const {
1390   if (!Subtarget->is64Bit())
1391     // This doesn't have DebugLoc associated with it, but is not really the
1392     // same as a Register.
1393     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1394   return Table;
1395 }
1396
1397 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1398 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1399 /// MCExpr.
1400 const MCExpr *X86TargetLowering::
1401 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1402                              MCContext &Ctx) const {
1403   // X86-64 uses RIP relative addressing based on the jump table label.
1404   if (Subtarget->isPICStyleRIPRel())
1405     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1406
1407   // Otherwise, the reference is relative to the PIC base.
1408   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1409 }
1410
1411 // FIXME: Why this routine is here? Move to RegInfo!
1412 std::pair<const TargetRegisterClass*, uint8_t>
1413 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1414   const TargetRegisterClass *RRC = 0;
1415   uint8_t Cost = 1;
1416   switch (VT.getSimpleVT().SimpleTy) {
1417   default:
1418     return TargetLowering::findRepresentativeClass(VT);
1419   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1420     RRC = Subtarget->is64Bit() ?
1421       (const TargetRegisterClass*)&X86::GR64RegClass :
1422       (const TargetRegisterClass*)&X86::GR32RegClass;
1423     break;
1424   case MVT::x86mmx:
1425     RRC = &X86::VR64RegClass;
1426     break;
1427   case MVT::f32: case MVT::f64:
1428   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1429   case MVT::v4f32: case MVT::v2f64:
1430   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1431   case MVT::v4f64:
1432     RRC = &X86::VR128RegClass;
1433     break;
1434   }
1435   return std::make_pair(RRC, Cost);
1436 }
1437
1438 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1439                                                unsigned &Offset) const {
1440   if (!Subtarget->isTargetLinux())
1441     return false;
1442
1443   if (Subtarget->is64Bit()) {
1444     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1445     Offset = 0x28;
1446     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1447       AddressSpace = 256;
1448     else
1449       AddressSpace = 257;
1450   } else {
1451     // %gs:0x14 on i386
1452     Offset = 0x14;
1453     AddressSpace = 256;
1454   }
1455   return true;
1456 }
1457
1458
1459 //===----------------------------------------------------------------------===//
1460 //               Return Value Calling Convention Implementation
1461 //===----------------------------------------------------------------------===//
1462
1463 #include "X86GenCallingConv.inc"
1464
1465 bool
1466 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1467                                   MachineFunction &MF, bool isVarArg,
1468                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1469                         LLVMContext &Context) const {
1470   SmallVector<CCValAssign, 16> RVLocs;
1471   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1472                  RVLocs, Context);
1473   return CCInfo.CheckReturn(Outs, RetCC_X86);
1474 }
1475
1476 SDValue
1477 X86TargetLowering::LowerReturn(SDValue Chain,
1478                                CallingConv::ID CallConv, bool isVarArg,
1479                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1480                                const SmallVectorImpl<SDValue> &OutVals,
1481                                DebugLoc dl, SelectionDAG &DAG) const {
1482   MachineFunction &MF = DAG.getMachineFunction();
1483   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1484
1485   SmallVector<CCValAssign, 16> RVLocs;
1486   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487                  RVLocs, *DAG.getContext());
1488   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1489
1490   // Add the regs to the liveout set for the function.
1491   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1492   for (unsigned i = 0; i != RVLocs.size(); ++i)
1493     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1494       MRI.addLiveOut(RVLocs[i].getLocReg());
1495
1496   SDValue Flag;
1497
1498   SmallVector<SDValue, 6> RetOps;
1499   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1500   // Operand #1 = Bytes To Pop
1501   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1502                    MVT::i16));
1503
1504   // Copy the result values into the output registers.
1505   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1506     CCValAssign &VA = RVLocs[i];
1507     assert(VA.isRegLoc() && "Can only return in registers!");
1508     SDValue ValToCopy = OutVals[i];
1509     EVT ValVT = ValToCopy.getValueType();
1510
1511     // Promote values to the appropriate types
1512     if (VA.getLocInfo() == CCValAssign::SExt)
1513       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514     else if (VA.getLocInfo() == CCValAssign::ZExt)
1515       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1516     else if (VA.getLocInfo() == CCValAssign::AExt)
1517       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1518     else if (VA.getLocInfo() == CCValAssign::BCvt)
1519       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1520
1521     // If this is x86-64, and we disabled SSE, we can't return FP values,
1522     // or SSE or MMX vectors.
1523     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1524          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1525           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1526       report_fatal_error("SSE register return with SSE disabled");
1527     }
1528     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1529     // llvm-gcc has never done it right and no one has noticed, so this
1530     // should be OK for now.
1531     if (ValVT == MVT::f64 &&
1532         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1533       report_fatal_error("SSE2 register return with SSE2 disabled");
1534
1535     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1536     // the RET instruction and handled by the FP Stackifier.
1537     if (VA.getLocReg() == X86::ST0 ||
1538         VA.getLocReg() == X86::ST1) {
1539       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1540       // change the value to the FP stack register class.
1541       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1542         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1543       RetOps.push_back(ValToCopy);
1544       // Don't emit a copytoreg.
1545       continue;
1546     }
1547
1548     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1549     // which is returned in RAX / RDX.
1550     if (Subtarget->is64Bit()) {
1551       if (ValVT == MVT::x86mmx) {
1552         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1553           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1554           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1555                                   ValToCopy);
1556           // If we don't have SSE2 available, convert to v4f32 so the generated
1557           // register is legal.
1558           if (!Subtarget->hasSSE2())
1559             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1560         }
1561       }
1562     }
1563
1564     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1565     Flag = Chain.getValue(1);
1566   }
1567
1568   // The x86-64 ABI for returning structs by value requires that we copy
1569   // the sret argument into %rax for the return. We saved the argument into
1570   // a virtual register in the entry block, so now we copy the value out
1571   // and into %rax.
1572   if (Subtarget->is64Bit() &&
1573       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1574     MachineFunction &MF = DAG.getMachineFunction();
1575     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1576     unsigned Reg = FuncInfo->getSRetReturnReg();
1577     assert(Reg &&
1578            "SRetReturnReg should have been set in LowerFormalArguments().");
1579     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1580
1581     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1582     Flag = Chain.getValue(1);
1583
1584     // RAX now acts like a return value.
1585     MRI.addLiveOut(X86::RAX);
1586   }
1587
1588   RetOps[0] = Chain;  // Update chain.
1589
1590   // Add the flag if we have it.
1591   if (Flag.getNode())
1592     RetOps.push_back(Flag);
1593
1594   return DAG.getNode(X86ISD::RET_FLAG, dl,
1595                      MVT::Other, &RetOps[0], RetOps.size());
1596 }
1597
1598 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1599   if (N->getNumValues() != 1)
1600     return false;
1601   if (!N->hasNUsesOfValue(1, 0))
1602     return false;
1603
1604   SDValue TCChain = Chain;
1605   SDNode *Copy = *N->use_begin();
1606   if (Copy->getOpcode() == ISD::CopyToReg) {
1607     // If the copy has a glue operand, we conservatively assume it isn't safe to
1608     // perform a tail call.
1609     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1610       return false;
1611     TCChain = Copy->getOperand(0);
1612   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1613     return false;
1614
1615   bool HasRet = false;
1616   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1617        UI != UE; ++UI) {
1618     if (UI->getOpcode() != X86ISD::RET_FLAG)
1619       return false;
1620     HasRet = true;
1621   }
1622
1623   if (!HasRet)
1624     return false;
1625
1626   Chain = TCChain;
1627   return true;
1628 }
1629
1630 EVT
1631 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1632                                             ISD::NodeType ExtendKind) const {
1633   MVT ReturnMVT;
1634   // TODO: Is this also valid on 32-bit?
1635   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1636     ReturnMVT = MVT::i8;
1637   else
1638     ReturnMVT = MVT::i32;
1639
1640   EVT MinVT = getRegisterType(Context, ReturnMVT);
1641   return VT.bitsLT(MinVT) ? MinVT : VT;
1642 }
1643
1644 /// LowerCallResult - Lower the result values of a call into the
1645 /// appropriate copies out of appropriate physical registers.
1646 ///
1647 SDValue
1648 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1649                                    CallingConv::ID CallConv, bool isVarArg,
1650                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1651                                    DebugLoc dl, SelectionDAG &DAG,
1652                                    SmallVectorImpl<SDValue> &InVals) const {
1653
1654   // Assign locations to each value returned by this call.
1655   SmallVector<CCValAssign, 16> RVLocs;
1656   bool Is64Bit = Subtarget->is64Bit();
1657   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1658                  getTargetMachine(), RVLocs, *DAG.getContext());
1659   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1660
1661   // Copy all of the result registers out of their specified physreg.
1662   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1663     CCValAssign &VA = RVLocs[i];
1664     EVT CopyVT = VA.getValVT();
1665
1666     // If this is x86-64, and we disabled SSE, we can't return FP values
1667     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1668         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1669       report_fatal_error("SSE register return with SSE disabled");
1670     }
1671
1672     SDValue Val;
1673
1674     // If this is a call to a function that returns an fp value on the floating
1675     // point stack, we must guarantee the value is popped from the stack, so
1676     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1677     // if the return value is not used. We use the FpPOP_RETVAL instruction
1678     // instead.
1679     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1680       // If we prefer to use the value in xmm registers, copy it out as f80 and
1681       // use a truncate to move it from fp stack reg to xmm reg.
1682       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1683       SDValue Ops[] = { Chain, InFlag };
1684       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1685                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1686       Val = Chain.getValue(0);
1687
1688       // Round the f80 to the right size, which also moves it to the appropriate
1689       // xmm register.
1690       if (CopyVT != VA.getValVT())
1691         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1692                           // This truncation won't change the value.
1693                           DAG.getIntPtrConstant(1));
1694     } else {
1695       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1696                                  CopyVT, InFlag).getValue(1);
1697       Val = Chain.getValue(0);
1698     }
1699     InFlag = Chain.getValue(2);
1700     InVals.push_back(Val);
1701   }
1702
1703   return Chain;
1704 }
1705
1706
1707 //===----------------------------------------------------------------------===//
1708 //                C & StdCall & Fast Calling Convention implementation
1709 //===----------------------------------------------------------------------===//
1710 //  StdCall calling convention seems to be standard for many Windows' API
1711 //  routines and around. It differs from C calling convention just a little:
1712 //  callee should clean up the stack, not caller. Symbols should be also
1713 //  decorated in some fancy way :) It doesn't support any vector arguments.
1714 //  For info on fast calling convention see Fast Calling Convention (tail call)
1715 //  implementation LowerX86_32FastCCCallTo.
1716
1717 /// CallIsStructReturn - Determines whether a call uses struct return
1718 /// semantics.
1719 enum StructReturnType {
1720   NotStructReturn,
1721   RegStructReturn,
1722   StackStructReturn
1723 };
1724 static StructReturnType
1725 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1726   if (Outs.empty())
1727     return NotStructReturn;
1728
1729   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1730   if (!Flags.isSRet())
1731     return NotStructReturn;
1732   if (Flags.isInReg())
1733     return RegStructReturn;
1734   return StackStructReturn;
1735 }
1736
1737 /// ArgsAreStructReturn - Determines whether a function uses struct
1738 /// return semantics.
1739 static StructReturnType
1740 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1741   if (Ins.empty())
1742     return NotStructReturn;
1743
1744   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1745   if (!Flags.isSRet())
1746     return NotStructReturn;
1747   if (Flags.isInReg())
1748     return RegStructReturn;
1749   return StackStructReturn;
1750 }
1751
1752 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1753 /// by "Src" to address "Dst" with size and alignment information specified by
1754 /// the specific parameter attribute. The copy will be passed as a byval
1755 /// function parameter.
1756 static SDValue
1757 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1758                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1759                           DebugLoc dl) {
1760   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1761
1762   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1763                        /*isVolatile*/false, /*AlwaysInline=*/true,
1764                        MachinePointerInfo(), MachinePointerInfo());
1765 }
1766
1767 /// IsTailCallConvention - Return true if the calling convention is one that
1768 /// supports tail call optimization.
1769 static bool IsTailCallConvention(CallingConv::ID CC) {
1770   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1771 }
1772
1773 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1774   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1775     return false;
1776
1777   CallSite CS(CI);
1778   CallingConv::ID CalleeCC = CS.getCallingConv();
1779   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1780     return false;
1781
1782   return true;
1783 }
1784
1785 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1786 /// a tailcall target by changing its ABI.
1787 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1788                                    bool GuaranteedTailCallOpt) {
1789   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1790 }
1791
1792 SDValue
1793 X86TargetLowering::LowerMemArgument(SDValue Chain,
1794                                     CallingConv::ID CallConv,
1795                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1796                                     DebugLoc dl, SelectionDAG &DAG,
1797                                     const CCValAssign &VA,
1798                                     MachineFrameInfo *MFI,
1799                                     unsigned i) const {
1800   // Create the nodes corresponding to a load from this parameter slot.
1801   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1802   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1803                               getTargetMachine().Options.GuaranteedTailCallOpt);
1804   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1805   EVT ValVT;
1806
1807   // If value is passed by pointer we have address passed instead of the value
1808   // itself.
1809   if (VA.getLocInfo() == CCValAssign::Indirect)
1810     ValVT = VA.getLocVT();
1811   else
1812     ValVT = VA.getValVT();
1813
1814   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1815   // changed with more analysis.
1816   // In case of tail call optimization mark all arguments mutable. Since they
1817   // could be overwritten by lowering of arguments in case of a tail call.
1818   if (Flags.isByVal()) {
1819     unsigned Bytes = Flags.getByValSize();
1820     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1821     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1822     return DAG.getFrameIndex(FI, getPointerTy());
1823   } else {
1824     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1825                                     VA.getLocMemOffset(), isImmutable);
1826     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1827     return DAG.getLoad(ValVT, dl, Chain, FIN,
1828                        MachinePointerInfo::getFixedStack(FI),
1829                        false, false, false, 0);
1830   }
1831 }
1832
1833 SDValue
1834 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1835                                         CallingConv::ID CallConv,
1836                                         bool isVarArg,
1837                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1838                                         DebugLoc dl,
1839                                         SelectionDAG &DAG,
1840                                         SmallVectorImpl<SDValue> &InVals)
1841                                           const {
1842   MachineFunction &MF = DAG.getMachineFunction();
1843   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1844
1845   const Function* Fn = MF.getFunction();
1846   if (Fn->hasExternalLinkage() &&
1847       Subtarget->isTargetCygMing() &&
1848       Fn->getName() == "main")
1849     FuncInfo->setForceFramePointer(true);
1850
1851   MachineFrameInfo *MFI = MF.getFrameInfo();
1852   bool Is64Bit = Subtarget->is64Bit();
1853   bool IsWindows = Subtarget->isTargetWindows();
1854   bool IsWin64 = Subtarget->isTargetWin64();
1855
1856   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1857          "Var args not supported with calling convention fastcc or ghc");
1858
1859   // Assign locations to all of the incoming arguments.
1860   SmallVector<CCValAssign, 16> ArgLocs;
1861   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1862                  ArgLocs, *DAG.getContext());
1863
1864   // Allocate shadow area for Win64
1865   if (IsWin64) {
1866     CCInfo.AllocateStack(32, 8);
1867   }
1868
1869   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1870
1871   unsigned LastVal = ~0U;
1872   SDValue ArgValue;
1873   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1874     CCValAssign &VA = ArgLocs[i];
1875     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1876     // places.
1877     assert(VA.getValNo() != LastVal &&
1878            "Don't support value assigned to multiple locs yet");
1879     (void)LastVal;
1880     LastVal = VA.getValNo();
1881
1882     if (VA.isRegLoc()) {
1883       EVT RegVT = VA.getLocVT();
1884       const TargetRegisterClass *RC;
1885       if (RegVT == MVT::i32)
1886         RC = &X86::GR32RegClass;
1887       else if (Is64Bit && RegVT == MVT::i64)
1888         RC = &X86::GR64RegClass;
1889       else if (RegVT == MVT::f32)
1890         RC = &X86::FR32RegClass;
1891       else if (RegVT == MVT::f64)
1892         RC = &X86::FR64RegClass;
1893       else if (RegVT.is256BitVector())
1894         RC = &X86::VR256RegClass;
1895       else if (RegVT.is128BitVector())
1896         RC = &X86::VR128RegClass;
1897       else if (RegVT == MVT::x86mmx)
1898         RC = &X86::VR64RegClass;
1899       else
1900         llvm_unreachable("Unknown argument type!");
1901
1902       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1903       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1904
1905       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1906       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1907       // right size.
1908       if (VA.getLocInfo() == CCValAssign::SExt)
1909         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1910                                DAG.getValueType(VA.getValVT()));
1911       else if (VA.getLocInfo() == CCValAssign::ZExt)
1912         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1913                                DAG.getValueType(VA.getValVT()));
1914       else if (VA.getLocInfo() == CCValAssign::BCvt)
1915         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1916
1917       if (VA.isExtInLoc()) {
1918         // Handle MMX values passed in XMM regs.
1919         if (RegVT.isVector()) {
1920           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1921                                  ArgValue);
1922         } else
1923           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1924       }
1925     } else {
1926       assert(VA.isMemLoc());
1927       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1928     }
1929
1930     // If value is passed via pointer - do a load.
1931     if (VA.getLocInfo() == CCValAssign::Indirect)
1932       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1933                              MachinePointerInfo(), false, false, false, 0);
1934
1935     InVals.push_back(ArgValue);
1936   }
1937
1938   // The x86-64 ABI for returning structs by value requires that we copy
1939   // the sret argument into %rax for the return. Save the argument into
1940   // a virtual register so that we can access it from the return points.
1941   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1942     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1943     unsigned Reg = FuncInfo->getSRetReturnReg();
1944     if (!Reg) {
1945       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1946       FuncInfo->setSRetReturnReg(Reg);
1947     }
1948     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1949     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1950   }
1951
1952   unsigned StackSize = CCInfo.getNextStackOffset();
1953   // Align stack specially for tail calls.
1954   if (FuncIsMadeTailCallSafe(CallConv,
1955                              MF.getTarget().Options.GuaranteedTailCallOpt))
1956     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1957
1958   // If the function takes variable number of arguments, make a frame index for
1959   // the start of the first vararg value... for expansion of llvm.va_start.
1960   if (isVarArg) {
1961     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1962                     CallConv != CallingConv::X86_ThisCall)) {
1963       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1964     }
1965     if (Is64Bit) {
1966       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1967
1968       // FIXME: We should really autogenerate these arrays
1969       static const uint16_t GPR64ArgRegsWin64[] = {
1970         X86::RCX, X86::RDX, X86::R8,  X86::R9
1971       };
1972       static const uint16_t GPR64ArgRegs64Bit[] = {
1973         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1974       };
1975       static const uint16_t XMMArgRegs64Bit[] = {
1976         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1977         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1978       };
1979       const uint16_t *GPR64ArgRegs;
1980       unsigned NumXMMRegs = 0;
1981
1982       if (IsWin64) {
1983         // The XMM registers which might contain var arg parameters are shadowed
1984         // in their paired GPR.  So we only need to save the GPR to their home
1985         // slots.
1986         TotalNumIntRegs = 4;
1987         GPR64ArgRegs = GPR64ArgRegsWin64;
1988       } else {
1989         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1990         GPR64ArgRegs = GPR64ArgRegs64Bit;
1991
1992         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1993                                                 TotalNumXMMRegs);
1994       }
1995       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1996                                                        TotalNumIntRegs);
1997
1998       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1999       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2000              "SSE register cannot be used when SSE is disabled!");
2001       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2002                NoImplicitFloatOps) &&
2003              "SSE register cannot be used when SSE is disabled!");
2004       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2005           !Subtarget->hasSSE1())
2006         // Kernel mode asks for SSE to be disabled, so don't push them
2007         // on the stack.
2008         TotalNumXMMRegs = 0;
2009
2010       if (IsWin64) {
2011         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2012         // Get to the caller-allocated home save location.  Add 8 to account
2013         // for the return address.
2014         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2015         FuncInfo->setRegSaveFrameIndex(
2016           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2017         // Fixup to set vararg frame on shadow area (4 x i64).
2018         if (NumIntRegs < 4)
2019           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2020       } else {
2021         // For X86-64, if there are vararg parameters that are passed via
2022         // registers, then we must store them to their spots on the stack so
2023         // they may be loaded by deferencing the result of va_next.
2024         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2025         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2026         FuncInfo->setRegSaveFrameIndex(
2027           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2028                                false));
2029       }
2030
2031       // Store the integer parameter registers.
2032       SmallVector<SDValue, 8> MemOps;
2033       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2034                                         getPointerTy());
2035       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2036       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2037         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2038                                   DAG.getIntPtrConstant(Offset));
2039         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2040                                      &X86::GR64RegClass);
2041         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2042         SDValue Store =
2043           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2044                        MachinePointerInfo::getFixedStack(
2045                          FuncInfo->getRegSaveFrameIndex(), Offset),
2046                        false, false, 0);
2047         MemOps.push_back(Store);
2048         Offset += 8;
2049       }
2050
2051       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2052         // Now store the XMM (fp + vector) parameter registers.
2053         SmallVector<SDValue, 11> SaveXMMOps;
2054         SaveXMMOps.push_back(Chain);
2055
2056         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2057         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2058         SaveXMMOps.push_back(ALVal);
2059
2060         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2061                                FuncInfo->getRegSaveFrameIndex()));
2062         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2063                                FuncInfo->getVarArgsFPOffset()));
2064
2065         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2066           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2067                                        &X86::VR128RegClass);
2068           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2069           SaveXMMOps.push_back(Val);
2070         }
2071         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2072                                      MVT::Other,
2073                                      &SaveXMMOps[0], SaveXMMOps.size()));
2074       }
2075
2076       if (!MemOps.empty())
2077         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2078                             &MemOps[0], MemOps.size());
2079     }
2080   }
2081
2082   // Some CCs need callee pop.
2083   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2084                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2085     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2086   } else {
2087     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2088     // If this is an sret function, the return should pop the hidden pointer.
2089     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2090         argsAreStructReturn(Ins) == StackStructReturn)
2091       FuncInfo->setBytesToPopOnReturn(4);
2092   }
2093
2094   if (!Is64Bit) {
2095     // RegSaveFrameIndex is X86-64 only.
2096     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2097     if (CallConv == CallingConv::X86_FastCall ||
2098         CallConv == CallingConv::X86_ThisCall)
2099       // fastcc functions can't have varargs.
2100       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2101   }
2102
2103   FuncInfo->setArgumentStackSize(StackSize);
2104
2105   return Chain;
2106 }
2107
2108 SDValue
2109 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2110                                     SDValue StackPtr, SDValue Arg,
2111                                     DebugLoc dl, SelectionDAG &DAG,
2112                                     const CCValAssign &VA,
2113                                     ISD::ArgFlagsTy Flags) const {
2114   unsigned LocMemOffset = VA.getLocMemOffset();
2115   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2116   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2117   if (Flags.isByVal())
2118     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2119
2120   return DAG.getStore(Chain, dl, Arg, PtrOff,
2121                       MachinePointerInfo::getStack(LocMemOffset),
2122                       false, false, 0);
2123 }
2124
2125 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2126 /// optimization is performed and it is required.
2127 SDValue
2128 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2129                                            SDValue &OutRetAddr, SDValue Chain,
2130                                            bool IsTailCall, bool Is64Bit,
2131                                            int FPDiff, DebugLoc dl) const {
2132   // Adjust the Return address stack slot.
2133   EVT VT = getPointerTy();
2134   OutRetAddr = getReturnAddressFrameIndex(DAG);
2135
2136   // Load the "old" Return address.
2137   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2138                            false, false, false, 0);
2139   return SDValue(OutRetAddr.getNode(), 1);
2140 }
2141
2142 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2143 /// optimization is performed and it is required (FPDiff!=0).
2144 static SDValue
2145 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2146                          SDValue Chain, SDValue RetAddrFrIdx,
2147                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2148   // Store the return address to the appropriate stack slot.
2149   if (!FPDiff) return Chain;
2150   // Calculate the new stack slot for the return address.
2151   int SlotSize = Is64Bit ? 8 : 4;
2152   int NewReturnAddrFI =
2153     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2154   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2155   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2156   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2157                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2158                        false, false, 0);
2159   return Chain;
2160 }
2161
2162 SDValue
2163 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2164                              SmallVectorImpl<SDValue> &InVals) const {
2165   SelectionDAG &DAG                     = CLI.DAG;
2166   DebugLoc &dl                          = CLI.DL;
2167   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2168   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2169   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2170   SDValue Chain                         = CLI.Chain;
2171   SDValue Callee                        = CLI.Callee;
2172   CallingConv::ID CallConv              = CLI.CallConv;
2173   bool &isTailCall                      = CLI.IsTailCall;
2174   bool isVarArg                         = CLI.IsVarArg;
2175
2176   MachineFunction &MF = DAG.getMachineFunction();
2177   bool Is64Bit        = Subtarget->is64Bit();
2178   bool IsWin64        = Subtarget->isTargetWin64();
2179   bool IsWindows      = Subtarget->isTargetWindows();
2180   StructReturnType SR = callIsStructReturn(Outs);
2181   bool IsSibcall      = false;
2182
2183   if (MF.getTarget().Options.DisableTailCalls)
2184     isTailCall = false;
2185
2186   if (isTailCall) {
2187     // Check if it's really possible to do a tail call.
2188     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2189                     isVarArg, SR != NotStructReturn,
2190                     MF.getFunction()->hasStructRetAttr(),
2191                     Outs, OutVals, Ins, DAG);
2192
2193     // Sibcalls are automatically detected tailcalls which do not require
2194     // ABI changes.
2195     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2196       IsSibcall = true;
2197
2198     if (isTailCall)
2199       ++NumTailCalls;
2200   }
2201
2202   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2203          "Var args not supported with calling convention fastcc or ghc");
2204
2205   // Analyze operands of the call, assigning locations to each operand.
2206   SmallVector<CCValAssign, 16> ArgLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2208                  ArgLocs, *DAG.getContext());
2209
2210   // Allocate shadow area for Win64
2211   if (IsWin64) {
2212     CCInfo.AllocateStack(32, 8);
2213   }
2214
2215   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2216
2217   // Get a count of how many bytes are to be pushed on the stack.
2218   unsigned NumBytes = CCInfo.getNextStackOffset();
2219   if (IsSibcall)
2220     // This is a sibcall. The memory operands are available in caller's
2221     // own caller's stack.
2222     NumBytes = 0;
2223   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2224            IsTailCallConvention(CallConv))
2225     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2226
2227   int FPDiff = 0;
2228   if (isTailCall && !IsSibcall) {
2229     // Lower arguments at fp - stackoffset + fpdiff.
2230     unsigned NumBytesCallerPushed =
2231       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2232     FPDiff = NumBytesCallerPushed - NumBytes;
2233
2234     // Set the delta of movement of the returnaddr stackslot.
2235     // But only set if delta is greater than previous delta.
2236     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2237       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2238   }
2239
2240   if (!IsSibcall)
2241     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2242
2243   SDValue RetAddrFrIdx;
2244   // Load return address for tail calls.
2245   if (isTailCall && FPDiff)
2246     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2247                                     Is64Bit, FPDiff, dl);
2248
2249   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2250   SmallVector<SDValue, 8> MemOpChains;
2251   SDValue StackPtr;
2252
2253   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2254   // of tail call optimization arguments are handle later.
2255   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2256     CCValAssign &VA = ArgLocs[i];
2257     EVT RegVT = VA.getLocVT();
2258     SDValue Arg = OutVals[i];
2259     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2260     bool isByVal = Flags.isByVal();
2261
2262     // Promote the value if needed.
2263     switch (VA.getLocInfo()) {
2264     default: llvm_unreachable("Unknown loc info!");
2265     case CCValAssign::Full: break;
2266     case CCValAssign::SExt:
2267       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2268       break;
2269     case CCValAssign::ZExt:
2270       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2271       break;
2272     case CCValAssign::AExt:
2273       if (RegVT.is128BitVector()) {
2274         // Special case: passing MMX values in XMM registers.
2275         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2276         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2277         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2278       } else
2279         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2280       break;
2281     case CCValAssign::BCvt:
2282       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2283       break;
2284     case CCValAssign::Indirect: {
2285       // Store the argument.
2286       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2287       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2288       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2289                            MachinePointerInfo::getFixedStack(FI),
2290                            false, false, 0);
2291       Arg = SpillSlot;
2292       break;
2293     }
2294     }
2295
2296     if (VA.isRegLoc()) {
2297       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2298       if (isVarArg && IsWin64) {
2299         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2300         // shadow reg if callee is a varargs function.
2301         unsigned ShadowReg = 0;
2302         switch (VA.getLocReg()) {
2303         case X86::XMM0: ShadowReg = X86::RCX; break;
2304         case X86::XMM1: ShadowReg = X86::RDX; break;
2305         case X86::XMM2: ShadowReg = X86::R8; break;
2306         case X86::XMM3: ShadowReg = X86::R9; break;
2307         }
2308         if (ShadowReg)
2309           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2310       }
2311     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2312       assert(VA.isMemLoc());
2313       if (StackPtr.getNode() == 0)
2314         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2315       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2316                                              dl, DAG, VA, Flags));
2317     }
2318   }
2319
2320   if (!MemOpChains.empty())
2321     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2322                         &MemOpChains[0], MemOpChains.size());
2323
2324   if (Subtarget->isPICStyleGOT()) {
2325     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2326     // GOT pointer.
2327     if (!isTailCall) {
2328       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2329                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2330     } else {
2331       // If we are tail calling and generating PIC/GOT style code load the
2332       // address of the callee into ECX. The value in ecx is used as target of
2333       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2334       // for tail calls on PIC/GOT architectures. Normally we would just put the
2335       // address of GOT into ebx and then call target@PLT. But for tail calls
2336       // ebx would be restored (since ebx is callee saved) before jumping to the
2337       // target@PLT.
2338
2339       // Note: The actual moving to ECX is done further down.
2340       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2341       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2342           !G->getGlobal()->hasProtectedVisibility())
2343         Callee = LowerGlobalAddress(Callee, DAG);
2344       else if (isa<ExternalSymbolSDNode>(Callee))
2345         Callee = LowerExternalSymbol(Callee, DAG);
2346     }
2347   }
2348
2349   if (Is64Bit && isVarArg && !IsWin64) {
2350     // From AMD64 ABI document:
2351     // For calls that may call functions that use varargs or stdargs
2352     // (prototype-less calls or calls to functions containing ellipsis (...) in
2353     // the declaration) %al is used as hidden argument to specify the number
2354     // of SSE registers used. The contents of %al do not need to match exactly
2355     // the number of registers, but must be an ubound on the number of SSE
2356     // registers used and is in the range 0 - 8 inclusive.
2357
2358     // Count the number of XMM registers allocated.
2359     static const uint16_t XMMArgRegs[] = {
2360       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2361       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2362     };
2363     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2364     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2365            && "SSE registers cannot be used when SSE is disabled");
2366
2367     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2368                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2369   }
2370
2371   // For tail calls lower the arguments to the 'real' stack slot.
2372   if (isTailCall) {
2373     // Force all the incoming stack arguments to be loaded from the stack
2374     // before any new outgoing arguments are stored to the stack, because the
2375     // outgoing stack slots may alias the incoming argument stack slots, and
2376     // the alias isn't otherwise explicit. This is slightly more conservative
2377     // than necessary, because it means that each store effectively depends
2378     // on every argument instead of just those arguments it would clobber.
2379     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2380
2381     SmallVector<SDValue, 8> MemOpChains2;
2382     SDValue FIN;
2383     int FI = 0;
2384     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2385       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2386         CCValAssign &VA = ArgLocs[i];
2387         if (VA.isRegLoc())
2388           continue;
2389         assert(VA.isMemLoc());
2390         SDValue Arg = OutVals[i];
2391         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2392         // Create frame index.
2393         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2394         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2395         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2396         FIN = DAG.getFrameIndex(FI, getPointerTy());
2397
2398         if (Flags.isByVal()) {
2399           // Copy relative to framepointer.
2400           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2401           if (StackPtr.getNode() == 0)
2402             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2403                                           getPointerTy());
2404           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2405
2406           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2407                                                            ArgChain,
2408                                                            Flags, DAG, dl));
2409         } else {
2410           // Store relative to framepointer.
2411           MemOpChains2.push_back(
2412             DAG.getStore(ArgChain, dl, Arg, FIN,
2413                          MachinePointerInfo::getFixedStack(FI),
2414                          false, false, 0));
2415         }
2416       }
2417     }
2418
2419     if (!MemOpChains2.empty())
2420       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2421                           &MemOpChains2[0], MemOpChains2.size());
2422
2423     // Store the return address to the appropriate stack slot.
2424     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2425                                      FPDiff, dl);
2426   }
2427
2428   // Build a sequence of copy-to-reg nodes chained together with token chain
2429   // and flag operands which copy the outgoing args into registers.
2430   SDValue InFlag;
2431   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2432     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2433                              RegsToPass[i].second, InFlag);
2434     InFlag = Chain.getValue(1);
2435   }
2436
2437   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2438     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2439     // In the 64-bit large code model, we have to make all calls
2440     // through a register, since the call instruction's 32-bit
2441     // pc-relative offset may not be large enough to hold the whole
2442     // address.
2443   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2444     // If the callee is a GlobalAddress node (quite common, every direct call
2445     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2446     // it.
2447
2448     // We should use extra load for direct calls to dllimported functions in
2449     // non-JIT mode.
2450     const GlobalValue *GV = G->getGlobal();
2451     if (!GV->hasDLLImportLinkage()) {
2452       unsigned char OpFlags = 0;
2453       bool ExtraLoad = false;
2454       unsigned WrapperKind = ISD::DELETED_NODE;
2455
2456       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2457       // external symbols most go through the PLT in PIC mode.  If the symbol
2458       // has hidden or protected visibility, or if it is static or local, then
2459       // we don't need to use the PLT - we can directly call it.
2460       if (Subtarget->isTargetELF() &&
2461           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2462           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2463         OpFlags = X86II::MO_PLT;
2464       } else if (Subtarget->isPICStyleStubAny() &&
2465                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
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       } else if (Subtarget->isPICStyleRIPRel() &&
2473                  isa<Function>(GV) &&
2474                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2475         // If the function is marked as non-lazy, generate an indirect call
2476         // which loads from the GOT directly. This avoids runtime overhead
2477         // at the cost of eager binding (and one extra byte of encoding).
2478         OpFlags = X86II::MO_GOTPCREL;
2479         WrapperKind = X86ISD::WrapperRIP;
2480         ExtraLoad = true;
2481       }
2482
2483       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2484                                           G->getOffset(), OpFlags);
2485
2486       // Add a wrapper if needed.
2487       if (WrapperKind != ISD::DELETED_NODE)
2488         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2489       // Add extra indirection if needed.
2490       if (ExtraLoad)
2491         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2492                              MachinePointerInfo::getGOT(),
2493                              false, false, false, 0);
2494     }
2495   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2496     unsigned char OpFlags = 0;
2497
2498     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2499     // external symbols should go through the PLT.
2500     if (Subtarget->isTargetELF() &&
2501         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2502       OpFlags = X86II::MO_PLT;
2503     } else if (Subtarget->isPICStyleStubAny() &&
2504                (!Subtarget->getTargetTriple().isMacOSX() ||
2505                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2506       // PC-relative references to external symbols should go through $stub,
2507       // unless we're building with the leopard linker or later, which
2508       // automatically synthesizes these stubs.
2509       OpFlags = X86II::MO_DARWIN_STUB;
2510     }
2511
2512     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2513                                          OpFlags);
2514   }
2515
2516   // Returns a chain & a flag for retval copy to use.
2517   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2518   SmallVector<SDValue, 8> Ops;
2519
2520   if (!IsSibcall && isTailCall) {
2521     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2522                            DAG.getIntPtrConstant(0, true), InFlag);
2523     InFlag = Chain.getValue(1);
2524   }
2525
2526   Ops.push_back(Chain);
2527   Ops.push_back(Callee);
2528
2529   if (isTailCall)
2530     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2531
2532   // Add argument registers to the end of the list so that they are known live
2533   // into the call.
2534   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2535     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2536                                   RegsToPass[i].second.getValueType()));
2537
2538   // Add a register mask operand representing the call-preserved registers.
2539   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2540   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2541   assert(Mask && "Missing call preserved mask for calling convention");
2542   Ops.push_back(DAG.getRegisterMask(Mask));
2543
2544   if (InFlag.getNode())
2545     Ops.push_back(InFlag);
2546
2547   if (isTailCall) {
2548     // We used to do:
2549     //// If this is the first return lowered for this function, add the regs
2550     //// to the liveout set for the function.
2551     // This isn't right, although it's probably harmless on x86; liveouts
2552     // should be computed from returns not tail calls.  Consider a void
2553     // function making a tail call to a function returning int.
2554     return DAG.getNode(X86ISD::TC_RETURN, dl,
2555                        NodeTys, &Ops[0], Ops.size());
2556   }
2557
2558   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2559   InFlag = Chain.getValue(1);
2560
2561   // Create the CALLSEQ_END node.
2562   unsigned NumBytesForCalleeToPush;
2563   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2564                        getTargetMachine().Options.GuaranteedTailCallOpt))
2565     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2566   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2567            SR == StackStructReturn)
2568     // If this is a call to a struct-return function, the callee
2569     // pops the hidden struct pointer, so we have to push it back.
2570     // This is common for Darwin/X86, Linux & Mingw32 targets.
2571     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2572     NumBytesForCalleeToPush = 4;
2573   else
2574     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2575
2576   // Returns a flag for retval copy to use.
2577   if (!IsSibcall) {
2578     Chain = DAG.getCALLSEQ_END(Chain,
2579                                DAG.getIntPtrConstant(NumBytes, true),
2580                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2581                                                      true),
2582                                InFlag);
2583     InFlag = Chain.getValue(1);
2584   }
2585
2586   // Handle result values, copying them out of physregs into vregs that we
2587   // return.
2588   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2589                          Ins, dl, DAG, InVals);
2590 }
2591
2592
2593 //===----------------------------------------------------------------------===//
2594 //                Fast Calling Convention (tail call) implementation
2595 //===----------------------------------------------------------------------===//
2596
2597 //  Like std call, callee cleans arguments, convention except that ECX is
2598 //  reserved for storing the tail called function address. Only 2 registers are
2599 //  free for argument passing (inreg). Tail call optimization is performed
2600 //  provided:
2601 //                * tailcallopt is enabled
2602 //                * caller/callee are fastcc
2603 //  On X86_64 architecture with GOT-style position independent code only local
2604 //  (within module) calls are supported at the moment.
2605 //  To keep the stack aligned according to platform abi the function
2606 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2607 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2608 //  If a tail called function callee has more arguments than the caller the
2609 //  caller needs to make sure that there is room to move the RETADDR to. This is
2610 //  achieved by reserving an area the size of the argument delta right after the
2611 //  original REtADDR, but before the saved framepointer or the spilled registers
2612 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2613 //  stack layout:
2614 //    arg1
2615 //    arg2
2616 //    RETADDR
2617 //    [ new RETADDR
2618 //      move area ]
2619 //    (possible EBP)
2620 //    ESI
2621 //    EDI
2622 //    local1 ..
2623
2624 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2625 /// for a 16 byte align requirement.
2626 unsigned
2627 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2628                                                SelectionDAG& DAG) const {
2629   MachineFunction &MF = DAG.getMachineFunction();
2630   const TargetMachine &TM = MF.getTarget();
2631   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2632   unsigned StackAlignment = TFI.getStackAlignment();
2633   uint64_t AlignMask = StackAlignment - 1;
2634   int64_t Offset = StackSize;
2635   uint64_t SlotSize = TD->getPointerSize();
2636   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2637     // Number smaller than 12 so just add the difference.
2638     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2639   } else {
2640     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2641     Offset = ((~AlignMask) & Offset) + StackAlignment +
2642       (StackAlignment-SlotSize);
2643   }
2644   return Offset;
2645 }
2646
2647 /// MatchingStackOffset - Return true if the given stack call argument is
2648 /// already available in the same position (relatively) of the caller's
2649 /// incoming argument stack.
2650 static
2651 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2652                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2653                          const X86InstrInfo *TII) {
2654   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2655   int FI = INT_MAX;
2656   if (Arg.getOpcode() == ISD::CopyFromReg) {
2657     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2658     if (!TargetRegisterInfo::isVirtualRegister(VR))
2659       return false;
2660     MachineInstr *Def = MRI->getVRegDef(VR);
2661     if (!Def)
2662       return false;
2663     if (!Flags.isByVal()) {
2664       if (!TII->isLoadFromStackSlot(Def, FI))
2665         return false;
2666     } else {
2667       unsigned Opcode = Def->getOpcode();
2668       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2669           Def->getOperand(1).isFI()) {
2670         FI = Def->getOperand(1).getIndex();
2671         Bytes = Flags.getByValSize();
2672       } else
2673         return false;
2674     }
2675   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2676     if (Flags.isByVal())
2677       // ByVal argument is passed in as a pointer but it's now being
2678       // dereferenced. e.g.
2679       // define @foo(%struct.X* %A) {
2680       //   tail call @bar(%struct.X* byval %A)
2681       // }
2682       return false;
2683     SDValue Ptr = Ld->getBasePtr();
2684     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2685     if (!FINode)
2686       return false;
2687     FI = FINode->getIndex();
2688   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2689     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2690     FI = FINode->getIndex();
2691     Bytes = Flags.getByValSize();
2692   } else
2693     return false;
2694
2695   assert(FI != INT_MAX);
2696   if (!MFI->isFixedObjectIndex(FI))
2697     return false;
2698   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2699 }
2700
2701 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2702 /// for tail call optimization. Targets which want to do tail call
2703 /// optimization should implement this function.
2704 bool
2705 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2706                                                      CallingConv::ID CalleeCC,
2707                                                      bool isVarArg,
2708                                                      bool isCalleeStructRet,
2709                                                      bool isCallerStructRet,
2710                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2711                                     const SmallVectorImpl<SDValue> &OutVals,
2712                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2713                                                      SelectionDAG& DAG) const {
2714   if (!IsTailCallConvention(CalleeCC) &&
2715       CalleeCC != CallingConv::C)
2716     return false;
2717
2718   // If -tailcallopt is specified, make fastcc functions tail-callable.
2719   const MachineFunction &MF = DAG.getMachineFunction();
2720   const Function *CallerF = DAG.getMachineFunction().getFunction();
2721   CallingConv::ID CallerCC = CallerF->getCallingConv();
2722   bool CCMatch = CallerCC == CalleeCC;
2723
2724   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2725     if (IsTailCallConvention(CalleeCC) && CCMatch)
2726       return true;
2727     return false;
2728   }
2729
2730   // Look for obvious safe cases to perform tail call optimization that do not
2731   // require ABI changes. This is what gcc calls sibcall.
2732
2733   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2734   // emit a special epilogue.
2735   if (RegInfo->needsStackRealignment(MF))
2736     return false;
2737
2738   // Also avoid sibcall optimization if either caller or callee uses struct
2739   // return semantics.
2740   if (isCalleeStructRet || isCallerStructRet)
2741     return false;
2742
2743   // An stdcall caller is expected to clean up its arguments; the callee
2744   // isn't going to do that.
2745   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2746     return false;
2747
2748   // Do not sibcall optimize vararg calls unless all arguments are passed via
2749   // registers.
2750   if (isVarArg && !Outs.empty()) {
2751
2752     // Optimizing for varargs on Win64 is unlikely to be safe without
2753     // additional testing.
2754     if (Subtarget->isTargetWin64())
2755       return false;
2756
2757     SmallVector<CCValAssign, 16> ArgLocs;
2758     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2759                    getTargetMachine(), ArgLocs, *DAG.getContext());
2760
2761     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2762     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2763       if (!ArgLocs[i].isRegLoc())
2764         return false;
2765   }
2766
2767   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2768   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2769   // this into a sibcall.
2770   bool Unused = false;
2771   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2772     if (!Ins[i].Used) {
2773       Unused = true;
2774       break;
2775     }
2776   }
2777   if (Unused) {
2778     SmallVector<CCValAssign, 16> RVLocs;
2779     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2780                    getTargetMachine(), RVLocs, *DAG.getContext());
2781     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2782     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2783       CCValAssign &VA = RVLocs[i];
2784       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2785         return false;
2786     }
2787   }
2788
2789   // If the calling conventions do not match, then we'd better make sure the
2790   // results are returned in the same way as what the caller expects.
2791   if (!CCMatch) {
2792     SmallVector<CCValAssign, 16> RVLocs1;
2793     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2794                     getTargetMachine(), RVLocs1, *DAG.getContext());
2795     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2796
2797     SmallVector<CCValAssign, 16> RVLocs2;
2798     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2799                     getTargetMachine(), RVLocs2, *DAG.getContext());
2800     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2801
2802     if (RVLocs1.size() != RVLocs2.size())
2803       return false;
2804     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2805       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2806         return false;
2807       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2808         return false;
2809       if (RVLocs1[i].isRegLoc()) {
2810         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2811           return false;
2812       } else {
2813         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2814           return false;
2815       }
2816     }
2817   }
2818
2819   // If the callee takes no arguments then go on to check the results of the
2820   // call.
2821   if (!Outs.empty()) {
2822     // Check if stack adjustment is needed. For now, do not do this if any
2823     // argument is passed on the stack.
2824     SmallVector<CCValAssign, 16> ArgLocs;
2825     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2826                    getTargetMachine(), ArgLocs, *DAG.getContext());
2827
2828     // Allocate shadow area for Win64
2829     if (Subtarget->isTargetWin64()) {
2830       CCInfo.AllocateStack(32, 8);
2831     }
2832
2833     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2834     if (CCInfo.getNextStackOffset()) {
2835       MachineFunction &MF = DAG.getMachineFunction();
2836       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2837         return false;
2838
2839       // Check if the arguments are already laid out in the right way as
2840       // the caller's fixed stack objects.
2841       MachineFrameInfo *MFI = MF.getFrameInfo();
2842       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2843       const X86InstrInfo *TII =
2844         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2845       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846         CCValAssign &VA = ArgLocs[i];
2847         SDValue Arg = OutVals[i];
2848         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849         if (VA.getLocInfo() == CCValAssign::Indirect)
2850           return false;
2851         if (!VA.isRegLoc()) {
2852           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2853                                    MFI, MRI, TII))
2854             return false;
2855         }
2856       }
2857     }
2858
2859     // If the tailcall address may be in a register, then make sure it's
2860     // possible to register allocate for it. In 32-bit, the call address can
2861     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2862     // callee-saved registers are restored. These happen to be the same
2863     // registers used to pass 'inreg' arguments so watch out for those.
2864     if (!Subtarget->is64Bit() &&
2865         !isa<GlobalAddressSDNode>(Callee) &&
2866         !isa<ExternalSymbolSDNode>(Callee)) {
2867       unsigned NumInRegs = 0;
2868       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2869         CCValAssign &VA = ArgLocs[i];
2870         if (!VA.isRegLoc())
2871           continue;
2872         unsigned Reg = VA.getLocReg();
2873         switch (Reg) {
2874         default: break;
2875         case X86::EAX: case X86::EDX: case X86::ECX:
2876           if (++NumInRegs == 3)
2877             return false;
2878           break;
2879         }
2880       }
2881     }
2882   }
2883
2884   return true;
2885 }
2886
2887 FastISel *
2888 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2889                                   const TargetLibraryInfo *libInfo) const {
2890   return X86::createFastISel(funcInfo, libInfo);
2891 }
2892
2893
2894 //===----------------------------------------------------------------------===//
2895 //                           Other Lowering Hooks
2896 //===----------------------------------------------------------------------===//
2897
2898 static bool MayFoldLoad(SDValue Op) {
2899   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2900 }
2901
2902 static bool MayFoldIntoStore(SDValue Op) {
2903   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2904 }
2905
2906 static bool isTargetShuffle(unsigned Opcode) {
2907   switch(Opcode) {
2908   default: return false;
2909   case X86ISD::PSHUFD:
2910   case X86ISD::PSHUFHW:
2911   case X86ISD::PSHUFLW:
2912   case X86ISD::SHUFP:
2913   case X86ISD::PALIGN:
2914   case X86ISD::MOVLHPS:
2915   case X86ISD::MOVLHPD:
2916   case X86ISD::MOVHLPS:
2917   case X86ISD::MOVLPS:
2918   case X86ISD::MOVLPD:
2919   case X86ISD::MOVSHDUP:
2920   case X86ISD::MOVSLDUP:
2921   case X86ISD::MOVDDUP:
2922   case X86ISD::MOVSS:
2923   case X86ISD::MOVSD:
2924   case X86ISD::UNPCKL:
2925   case X86ISD::UNPCKH:
2926   case X86ISD::VPERMILP:
2927   case X86ISD::VPERM2X128:
2928   case X86ISD::VPERMI:
2929     return true;
2930   }
2931 }
2932
2933 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2934                                     SDValue V1, SelectionDAG &DAG) {
2935   switch(Opc) {
2936   default: llvm_unreachable("Unknown x86 shuffle node");
2937   case X86ISD::MOVSHDUP:
2938   case X86ISD::MOVSLDUP:
2939   case X86ISD::MOVDDUP:
2940     return DAG.getNode(Opc, dl, VT, V1);
2941   }
2942 }
2943
2944 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2945                                     SDValue V1, unsigned TargetMask,
2946                                     SelectionDAG &DAG) {
2947   switch(Opc) {
2948   default: llvm_unreachable("Unknown x86 shuffle node");
2949   case X86ISD::PSHUFD:
2950   case X86ISD::PSHUFHW:
2951   case X86ISD::PSHUFLW:
2952   case X86ISD::VPERMILP:
2953   case X86ISD::VPERMI:
2954     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2955   }
2956 }
2957
2958 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2959                                     SDValue V1, SDValue V2, unsigned TargetMask,
2960                                     SelectionDAG &DAG) {
2961   switch(Opc) {
2962   default: llvm_unreachable("Unknown x86 shuffle node");
2963   case X86ISD::PALIGN:
2964   case X86ISD::SHUFP:
2965   case X86ISD::VPERM2X128:
2966     return DAG.getNode(Opc, dl, VT, V1, V2,
2967                        DAG.getConstant(TargetMask, MVT::i8));
2968   }
2969 }
2970
2971 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2972                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2973   switch(Opc) {
2974   default: llvm_unreachable("Unknown x86 shuffle node");
2975   case X86ISD::MOVLHPS:
2976   case X86ISD::MOVLHPD:
2977   case X86ISD::MOVHLPS:
2978   case X86ISD::MOVLPS:
2979   case X86ISD::MOVLPD:
2980   case X86ISD::MOVSS:
2981   case X86ISD::MOVSD:
2982   case X86ISD::UNPCKL:
2983   case X86ISD::UNPCKH:
2984     return DAG.getNode(Opc, dl, VT, V1, V2);
2985   }
2986 }
2987
2988 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2989   MachineFunction &MF = DAG.getMachineFunction();
2990   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2991   int ReturnAddrIndex = FuncInfo->getRAIndex();
2992
2993   if (ReturnAddrIndex == 0) {
2994     // Set up a frame object for the return address.
2995     uint64_t SlotSize = TD->getPointerSize();
2996     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2997                                                            false);
2998     FuncInfo->setRAIndex(ReturnAddrIndex);
2999   }
3000
3001   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3002 }
3003
3004
3005 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3006                                        bool hasSymbolicDisplacement) {
3007   // Offset should fit into 32 bit immediate field.
3008   if (!isInt<32>(Offset))
3009     return false;
3010
3011   // If we don't have a symbolic displacement - we don't have any extra
3012   // restrictions.
3013   if (!hasSymbolicDisplacement)
3014     return true;
3015
3016   // FIXME: Some tweaks might be needed for medium code model.
3017   if (M != CodeModel::Small && M != CodeModel::Kernel)
3018     return false;
3019
3020   // For small code model we assume that latest object is 16MB before end of 31
3021   // bits boundary. We may also accept pretty large negative constants knowing
3022   // that all objects are in the positive half of address space.
3023   if (M == CodeModel::Small && Offset < 16*1024*1024)
3024     return true;
3025
3026   // For kernel code model we know that all object resist in the negative half
3027   // of 32bits address space. We may not accept negative offsets, since they may
3028   // be just off and we may accept pretty large positive ones.
3029   if (M == CodeModel::Kernel && Offset > 0)
3030     return true;
3031
3032   return false;
3033 }
3034
3035 /// isCalleePop - Determines whether the callee is required to pop its
3036 /// own arguments. Callee pop is necessary to support tail calls.
3037 bool X86::isCalleePop(CallingConv::ID CallingConv,
3038                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3039   if (IsVarArg)
3040     return false;
3041
3042   switch (CallingConv) {
3043   default:
3044     return false;
3045   case CallingConv::X86_StdCall:
3046     return !is64Bit;
3047   case CallingConv::X86_FastCall:
3048     return !is64Bit;
3049   case CallingConv::X86_ThisCall:
3050     return !is64Bit;
3051   case CallingConv::Fast:
3052     return TailCallOpt;
3053   case CallingConv::GHC:
3054     return TailCallOpt;
3055   }
3056 }
3057
3058 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3059 /// specific condition code, returning the condition code and the LHS/RHS of the
3060 /// comparison to make.
3061 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3062                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3063   if (!isFP) {
3064     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3065       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3066         // X > -1   -> X == 0, jump !sign.
3067         RHS = DAG.getConstant(0, RHS.getValueType());
3068         return X86::COND_NS;
3069       }
3070       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3071         // X < 0   -> X == 0, jump on sign.
3072         return X86::COND_S;
3073       }
3074       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3075         // X < 1   -> X <= 0
3076         RHS = DAG.getConstant(0, RHS.getValueType());
3077         return X86::COND_LE;
3078       }
3079     }
3080
3081     switch (SetCCOpcode) {
3082     default: llvm_unreachable("Invalid integer condition!");
3083     case ISD::SETEQ:  return X86::COND_E;
3084     case ISD::SETGT:  return X86::COND_G;
3085     case ISD::SETGE:  return X86::COND_GE;
3086     case ISD::SETLT:  return X86::COND_L;
3087     case ISD::SETLE:  return X86::COND_LE;
3088     case ISD::SETNE:  return X86::COND_NE;
3089     case ISD::SETULT: return X86::COND_B;
3090     case ISD::SETUGT: return X86::COND_A;
3091     case ISD::SETULE: return X86::COND_BE;
3092     case ISD::SETUGE: return X86::COND_AE;
3093     }
3094   }
3095
3096   // First determine if it is required or is profitable to flip the operands.
3097
3098   // If LHS is a foldable load, but RHS is not, flip the condition.
3099   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3100       !ISD::isNON_EXTLoad(RHS.getNode())) {
3101     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3102     std::swap(LHS, RHS);
3103   }
3104
3105   switch (SetCCOpcode) {
3106   default: break;
3107   case ISD::SETOLT:
3108   case ISD::SETOLE:
3109   case ISD::SETUGT:
3110   case ISD::SETUGE:
3111     std::swap(LHS, RHS);
3112     break;
3113   }
3114
3115   // On a floating point condition, the flags are set as follows:
3116   // ZF  PF  CF   op
3117   //  0 | 0 | 0 | X > Y
3118   //  0 | 0 | 1 | X < Y
3119   //  1 | 0 | 0 | X == Y
3120   //  1 | 1 | 1 | unordered
3121   switch (SetCCOpcode) {
3122   default: llvm_unreachable("Condcode should be pre-legalized away");
3123   case ISD::SETUEQ:
3124   case ISD::SETEQ:   return X86::COND_E;
3125   case ISD::SETOLT:              // flipped
3126   case ISD::SETOGT:
3127   case ISD::SETGT:   return X86::COND_A;
3128   case ISD::SETOLE:              // flipped
3129   case ISD::SETOGE:
3130   case ISD::SETGE:   return X86::COND_AE;
3131   case ISD::SETUGT:              // flipped
3132   case ISD::SETULT:
3133   case ISD::SETLT:   return X86::COND_B;
3134   case ISD::SETUGE:              // flipped
3135   case ISD::SETULE:
3136   case ISD::SETLE:   return X86::COND_BE;
3137   case ISD::SETONE:
3138   case ISD::SETNE:   return X86::COND_NE;
3139   case ISD::SETUO:   return X86::COND_P;
3140   case ISD::SETO:    return X86::COND_NP;
3141   case ISD::SETOEQ:
3142   case ISD::SETUNE:  return X86::COND_INVALID;
3143   }
3144 }
3145
3146 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3147 /// code. Current x86 isa includes the following FP cmov instructions:
3148 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3149 static bool hasFPCMov(unsigned X86CC) {
3150   switch (X86CC) {
3151   default:
3152     return false;
3153   case X86::COND_B:
3154   case X86::COND_BE:
3155   case X86::COND_E:
3156   case X86::COND_P:
3157   case X86::COND_A:
3158   case X86::COND_AE:
3159   case X86::COND_NE:
3160   case X86::COND_NP:
3161     return true;
3162   }
3163 }
3164
3165 /// isFPImmLegal - Returns true if the target can instruction select the
3166 /// specified FP immediate natively. If false, the legalizer will
3167 /// materialize the FP immediate as a load from a constant pool.
3168 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3169   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3170     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3171       return true;
3172   }
3173   return false;
3174 }
3175
3176 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3177 /// the specified range (L, H].
3178 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3179   return (Val < 0) || (Val >= Low && Val < Hi);
3180 }
3181
3182 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3183 /// specified value.
3184 static bool isUndefOrEqual(int Val, int CmpVal) {
3185   if (Val < 0 || Val == CmpVal)
3186     return true;
3187   return false;
3188 }
3189
3190 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3191 /// from position Pos and ending in Pos+Size, falls within the specified
3192 /// sequential range (L, L+Pos]. or is undef.
3193 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3194                                        unsigned Pos, unsigned Size, int Low) {
3195   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3196     if (!isUndefOrEqual(Mask[i], Low))
3197       return false;
3198   return true;
3199 }
3200
3201 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3202 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3203 /// the second operand.
3204 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3205   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3206     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3207   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3208     return (Mask[0] < 2 && Mask[1] < 2);
3209   return false;
3210 }
3211
3212 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3213 /// is suitable for input to PSHUFHW.
3214 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3215   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3216     return false;
3217
3218   // Lower quadword copied in order or undef.
3219   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3220     return false;
3221
3222   // Upper quadword shuffled.
3223   for (unsigned i = 4; i != 8; ++i)
3224     if (!isUndefOrInRange(Mask[i], 4, 8))
3225       return false;
3226
3227   if (VT == MVT::v16i16) {
3228     // Lower quadword copied in order or undef.
3229     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3230       return false;
3231
3232     // Upper quadword shuffled.
3233     for (unsigned i = 12; i != 16; ++i)
3234       if (!isUndefOrInRange(Mask[i], 12, 16))
3235         return false;
3236   }
3237
3238   return true;
3239 }
3240
3241 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3242 /// is suitable for input to PSHUFLW.
3243 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3244   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3245     return false;
3246
3247   // Upper quadword copied in order.
3248   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3249     return false;
3250
3251   // Lower quadword shuffled.
3252   for (unsigned i = 0; i != 4; ++i)
3253     if (!isUndefOrInRange(Mask[i], 0, 4))
3254       return false;
3255
3256   if (VT == MVT::v16i16) {
3257     // Upper quadword copied in order.
3258     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3259       return false;
3260
3261     // Lower quadword shuffled.
3262     for (unsigned i = 8; i != 12; ++i)
3263       if (!isUndefOrInRange(Mask[i], 8, 12))
3264         return false;
3265   }
3266
3267   return true;
3268 }
3269
3270 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3271 /// is suitable for input to PALIGNR.
3272 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3273                           const X86Subtarget *Subtarget) {
3274   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3275       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3276     return false;
3277
3278   unsigned NumElts = VT.getVectorNumElements();
3279   unsigned NumLanes = VT.getSizeInBits()/128;
3280   unsigned NumLaneElts = NumElts/NumLanes;
3281
3282   // Do not handle 64-bit element shuffles with palignr.
3283   if (NumLaneElts == 2)
3284     return false;
3285
3286   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3287     unsigned i;
3288     for (i = 0; i != NumLaneElts; ++i) {
3289       if (Mask[i+l] >= 0)
3290         break;
3291     }
3292
3293     // Lane is all undef, go to next lane
3294     if (i == NumLaneElts)
3295       continue;
3296
3297     int Start = Mask[i+l];
3298
3299     // Make sure its in this lane in one of the sources
3300     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3301         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3302       return false;
3303
3304     // If not lane 0, then we must match lane 0
3305     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3306       return false;
3307
3308     // Correct second source to be contiguous with first source
3309     if (Start >= (int)NumElts)
3310       Start -= NumElts - NumLaneElts;
3311
3312     // Make sure we're shifting in the right direction.
3313     if (Start <= (int)(i+l))
3314       return false;
3315
3316     Start -= i;
3317
3318     // Check the rest of the elements to see if they are consecutive.
3319     for (++i; i != NumLaneElts; ++i) {
3320       int Idx = Mask[i+l];
3321
3322       // Make sure its in this lane
3323       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3324           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3325         return false;
3326
3327       // If not lane 0, then we must match lane 0
3328       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3329         return false;
3330
3331       if (Idx >= (int)NumElts)
3332         Idx -= NumElts - NumLaneElts;
3333
3334       if (!isUndefOrEqual(Idx, Start+i))
3335         return false;
3336
3337     }
3338   }
3339
3340   return true;
3341 }
3342
3343 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3344 /// the two vector operands have swapped position.
3345 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3346                                      unsigned NumElems) {
3347   for (unsigned i = 0; i != NumElems; ++i) {
3348     int idx = Mask[i];
3349     if (idx < 0)
3350       continue;
3351     else if (idx < (int)NumElems)
3352       Mask[i] = idx + NumElems;
3353     else
3354       Mask[i] = idx - NumElems;
3355   }
3356 }
3357
3358 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3359 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3360 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3361 /// reverse of what x86 shuffles want.
3362 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3363                         bool Commuted = false) {
3364   if (!HasAVX && VT.getSizeInBits() == 256)
3365     return false;
3366
3367   unsigned NumElems = VT.getVectorNumElements();
3368   unsigned NumLanes = VT.getSizeInBits()/128;
3369   unsigned NumLaneElems = NumElems/NumLanes;
3370
3371   if (NumLaneElems != 2 && NumLaneElems != 4)
3372     return false;
3373
3374   // VSHUFPSY divides the resulting vector into 4 chunks.
3375   // The sources are also splitted into 4 chunks, and each destination
3376   // chunk must come from a different source chunk.
3377   //
3378   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3379   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3380   //
3381   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3382   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3383   //
3384   // VSHUFPDY divides the resulting vector into 4 chunks.
3385   // The sources are also splitted into 4 chunks, and each destination
3386   // chunk must come from a different source chunk.
3387   //
3388   //  SRC1 =>      X3       X2       X1       X0
3389   //  SRC2 =>      Y3       Y2       Y1       Y0
3390   //
3391   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3392   //
3393   unsigned HalfLaneElems = NumLaneElems/2;
3394   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3395     for (unsigned i = 0; i != NumLaneElems; ++i) {
3396       int Idx = Mask[i+l];
3397       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3398       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3399         return false;
3400       // For VSHUFPSY, the mask of the second half must be the same as the
3401       // first but with the appropriate offsets. This works in the same way as
3402       // VPERMILPS works with masks.
3403       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3404         continue;
3405       if (!isUndefOrEqual(Idx, Mask[i]+l))
3406         return false;
3407     }
3408   }
3409
3410   return true;
3411 }
3412
3413 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3414 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3415 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3416   if (!VT.is128BitVector())
3417     return false;
3418
3419   unsigned NumElems = VT.getVectorNumElements();
3420
3421   if (NumElems != 4)
3422     return false;
3423
3424   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3425   return isUndefOrEqual(Mask[0], 6) &&
3426          isUndefOrEqual(Mask[1], 7) &&
3427          isUndefOrEqual(Mask[2], 2) &&
3428          isUndefOrEqual(Mask[3], 3);
3429 }
3430
3431 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3432 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3433 /// <2, 3, 2, 3>
3434 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3435   if (!VT.is128BitVector())
3436     return false;
3437
3438   unsigned NumElems = VT.getVectorNumElements();
3439
3440   if (NumElems != 4)
3441     return false;
3442
3443   return isUndefOrEqual(Mask[0], 2) &&
3444          isUndefOrEqual(Mask[1], 3) &&
3445          isUndefOrEqual(Mask[2], 2) &&
3446          isUndefOrEqual(Mask[3], 3);
3447 }
3448
3449 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3450 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3451 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3452   if (!VT.is128BitVector())
3453     return false;
3454
3455   unsigned NumElems = VT.getVectorNumElements();
3456
3457   if (NumElems != 2 && NumElems != 4)
3458     return false;
3459
3460   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3461     if (!isUndefOrEqual(Mask[i], i + NumElems))
3462       return false;
3463
3464   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3465     if (!isUndefOrEqual(Mask[i], i))
3466       return false;
3467
3468   return true;
3469 }
3470
3471 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3472 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3473 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3474   if (!VT.is128BitVector())
3475     return false;
3476
3477   unsigned NumElems = VT.getVectorNumElements();
3478
3479   if (NumElems != 2 && NumElems != 4)
3480     return false;
3481
3482   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3483     if (!isUndefOrEqual(Mask[i], i))
3484       return false;
3485
3486   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3487     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3488       return false;
3489
3490   return true;
3491 }
3492
3493 //
3494 // Some special combinations that can be optimized.
3495 //
3496 static
3497 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3498                                SelectionDAG &DAG) {
3499   EVT VT = SVOp->getValueType(0);
3500   DebugLoc dl = SVOp->getDebugLoc();
3501
3502   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3503     return SDValue();
3504
3505   ArrayRef<int> Mask = SVOp->getMask();
3506
3507   // These are the special masks that may be optimized.
3508   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3509   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3510   bool MatchEvenMask = true;
3511   bool MatchOddMask  = true;
3512   for (int i=0; i<8; ++i) {
3513     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3514       MatchEvenMask = false;
3515     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3516       MatchOddMask = false;
3517   }
3518
3519   if (!MatchEvenMask && !MatchOddMask)
3520     return SDValue();
3521   
3522   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3523
3524   SDValue Op0 = SVOp->getOperand(0);
3525   SDValue Op1 = SVOp->getOperand(1);
3526
3527   if (MatchEvenMask) {
3528     // Shift the second operand right to 32 bits.
3529     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3530     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3531   } else {
3532     // Shift the first operand left to 32 bits.
3533     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3534     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3535   }
3536   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3537   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3538 }
3539
3540 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3541 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3542 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3543                          bool HasAVX2, bool V2IsSplat = false) {
3544   unsigned NumElts = VT.getVectorNumElements();
3545
3546   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3547          "Unsupported vector type for unpckh");
3548
3549   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3550       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3551     return false;
3552
3553   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3554   // independently on 128-bit lanes.
3555   unsigned NumLanes = VT.getSizeInBits()/128;
3556   unsigned NumLaneElts = NumElts/NumLanes;
3557
3558   for (unsigned l = 0; l != NumLanes; ++l) {
3559     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3560          i != (l+1)*NumLaneElts;
3561          i += 2, ++j) {
3562       int BitI  = Mask[i];
3563       int BitI1 = Mask[i+1];
3564       if (!isUndefOrEqual(BitI, j))
3565         return false;
3566       if (V2IsSplat) {
3567         if (!isUndefOrEqual(BitI1, NumElts))
3568           return false;
3569       } else {
3570         if (!isUndefOrEqual(BitI1, j + NumElts))
3571           return false;
3572       }
3573     }
3574   }
3575
3576   return true;
3577 }
3578
3579 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3580 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3581 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3582                          bool HasAVX2, bool V2IsSplat = false) {
3583   unsigned NumElts = VT.getVectorNumElements();
3584
3585   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3586          "Unsupported vector type for unpckh");
3587
3588   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3589       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3590     return false;
3591
3592   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593   // independently on 128-bit lanes.
3594   unsigned NumLanes = VT.getSizeInBits()/128;
3595   unsigned NumLaneElts = NumElts/NumLanes;
3596
3597   for (unsigned l = 0; l != NumLanes; ++l) {
3598     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3599          i != (l+1)*NumLaneElts; i += 2, ++j) {
3600       int BitI  = Mask[i];
3601       int BitI1 = Mask[i+1];
3602       if (!isUndefOrEqual(BitI, j))
3603         return false;
3604       if (V2IsSplat) {
3605         if (isUndefOrEqual(BitI1, NumElts))
3606           return false;
3607       } else {
3608         if (!isUndefOrEqual(BitI1, j+NumElts))
3609           return false;
3610       }
3611     }
3612   }
3613   return true;
3614 }
3615
3616 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3617 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3618 /// <0, 0, 1, 1>
3619 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3620                                   bool HasAVX2) {
3621   unsigned NumElts = VT.getVectorNumElements();
3622
3623   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3624          "Unsupported vector type for unpckh");
3625
3626   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3627       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3628     return false;
3629
3630   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3631   // FIXME: Need a better way to get rid of this, there's no latency difference
3632   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3633   // the former later. We should also remove the "_undef" special mask.
3634   if (NumElts == 4 && VT.getSizeInBits() == 256)
3635     return false;
3636
3637   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3638   // independently on 128-bit lanes.
3639   unsigned NumLanes = VT.getSizeInBits()/128;
3640   unsigned NumLaneElts = NumElts/NumLanes;
3641
3642   for (unsigned l = 0; l != NumLanes; ++l) {
3643     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3644          i != (l+1)*NumLaneElts;
3645          i += 2, ++j) {
3646       int BitI  = Mask[i];
3647       int BitI1 = Mask[i+1];
3648
3649       if (!isUndefOrEqual(BitI, j))
3650         return false;
3651       if (!isUndefOrEqual(BitI1, j))
3652         return false;
3653     }
3654   }
3655
3656   return true;
3657 }
3658
3659 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3660 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3661 /// <2, 2, 3, 3>
3662 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3663   unsigned NumElts = VT.getVectorNumElements();
3664
3665   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3666          "Unsupported vector type for unpckh");
3667
3668   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3669       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3670     return false;
3671
3672   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3673   // independently on 128-bit lanes.
3674   unsigned NumLanes = VT.getSizeInBits()/128;
3675   unsigned NumLaneElts = NumElts/NumLanes;
3676
3677   for (unsigned l = 0; l != NumLanes; ++l) {
3678     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3679          i != (l+1)*NumLaneElts; i += 2, ++j) {
3680       int BitI  = Mask[i];
3681       int BitI1 = Mask[i+1];
3682       if (!isUndefOrEqual(BitI, j))
3683         return false;
3684       if (!isUndefOrEqual(BitI1, j))
3685         return false;
3686     }
3687   }
3688   return true;
3689 }
3690
3691 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3692 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3693 /// MOVSD, and MOVD, i.e. setting the lowest element.
3694 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3695   if (VT.getVectorElementType().getSizeInBits() < 32)
3696     return false;
3697   if (!VT.is128BitVector())
3698     return false;
3699
3700   unsigned NumElts = VT.getVectorNumElements();
3701
3702   if (!isUndefOrEqual(Mask[0], NumElts))
3703     return false;
3704
3705   for (unsigned i = 1; i != NumElts; ++i)
3706     if (!isUndefOrEqual(Mask[i], i))
3707       return false;
3708
3709   return true;
3710 }
3711
3712 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3713 /// as permutations between 128-bit chunks or halves. As an example: this
3714 /// shuffle bellow:
3715 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3716 /// The first half comes from the second half of V1 and the second half from the
3717 /// the second half of V2.
3718 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3719   if (!HasAVX || !VT.is256BitVector())
3720     return false;
3721
3722   // The shuffle result is divided into half A and half B. In total the two
3723   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3724   // B must come from C, D, E or F.
3725   unsigned HalfSize = VT.getVectorNumElements()/2;
3726   bool MatchA = false, MatchB = false;
3727
3728   // Check if A comes from one of C, D, E, F.
3729   for (unsigned Half = 0; Half != 4; ++Half) {
3730     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3731       MatchA = true;
3732       break;
3733     }
3734   }
3735
3736   // Check if B comes from one of C, D, E, F.
3737   for (unsigned Half = 0; Half != 4; ++Half) {
3738     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3739       MatchB = true;
3740       break;
3741     }
3742   }
3743
3744   return MatchA && MatchB;
3745 }
3746
3747 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3748 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3749 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3750   EVT VT = SVOp->getValueType(0);
3751
3752   unsigned HalfSize = VT.getVectorNumElements()/2;
3753
3754   unsigned FstHalf = 0, SndHalf = 0;
3755   for (unsigned i = 0; i < HalfSize; ++i) {
3756     if (SVOp->getMaskElt(i) > 0) {
3757       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3758       break;
3759     }
3760   }
3761   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3762     if (SVOp->getMaskElt(i) > 0) {
3763       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3764       break;
3765     }
3766   }
3767
3768   return (FstHalf | (SndHalf << 4));
3769 }
3770
3771 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3772 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3773 /// Note that VPERMIL mask matching is different depending whether theunderlying
3774 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3775 /// to the same elements of the low, but to the higher half of the source.
3776 /// In VPERMILPD the two lanes could be shuffled independently of each other
3777 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3778 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3779   if (!HasAVX)
3780     return false;
3781
3782   unsigned NumElts = VT.getVectorNumElements();
3783   // Only match 256-bit with 32/64-bit types
3784   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3785     return false;
3786
3787   unsigned NumLanes = VT.getSizeInBits()/128;
3788   unsigned LaneSize = NumElts/NumLanes;
3789   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3790     for (unsigned i = 0; i != LaneSize; ++i) {
3791       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3792         return false;
3793       if (NumElts != 8 || l == 0)
3794         continue;
3795       // VPERMILPS handling
3796       if (Mask[i] < 0)
3797         continue;
3798       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3799         return false;
3800     }
3801   }
3802
3803   return true;
3804 }
3805
3806 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3807 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3808 /// element of vector 2 and the other elements to come from vector 1 in order.
3809 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3810                                bool V2IsSplat = false, bool V2IsUndef = false) {
3811   if (!VT.is128BitVector())
3812     return false;
3813
3814   unsigned NumOps = VT.getVectorNumElements();
3815   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3816     return false;
3817
3818   if (!isUndefOrEqual(Mask[0], 0))
3819     return false;
3820
3821   for (unsigned i = 1; i != NumOps; ++i)
3822     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3823           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3824           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3825       return false;
3826
3827   return true;
3828 }
3829
3830 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3832 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3833 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3834                            const X86Subtarget *Subtarget) {
3835   if (!Subtarget->hasSSE3())
3836     return false;
3837
3838   unsigned NumElems = VT.getVectorNumElements();
3839
3840   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3841       (VT.getSizeInBits() == 256 && NumElems != 8))
3842     return false;
3843
3844   // "i+1" is the value the indexed mask element must have
3845   for (unsigned i = 0; i != NumElems; i += 2)
3846     if (!isUndefOrEqual(Mask[i], i+1) ||
3847         !isUndefOrEqual(Mask[i+1], i+1))
3848       return false;
3849
3850   return true;
3851 }
3852
3853 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3854 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3855 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3856 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3857                            const X86Subtarget *Subtarget) {
3858   if (!Subtarget->hasSSE3())
3859     return false;
3860
3861   unsigned NumElems = VT.getVectorNumElements();
3862
3863   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3864       (VT.getSizeInBits() == 256 && NumElems != 8))
3865     return false;
3866
3867   // "i" is the value the indexed mask element must have
3868   for (unsigned i = 0; i != NumElems; i += 2)
3869     if (!isUndefOrEqual(Mask[i], i) ||
3870         !isUndefOrEqual(Mask[i+1], i))
3871       return false;
3872
3873   return true;
3874 }
3875
3876 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3877 /// specifies a shuffle of elements that is suitable for input to 256-bit
3878 /// version of MOVDDUP.
3879 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3880   if (!HasAVX || !VT.is256BitVector())
3881     return false;
3882
3883   unsigned NumElts = VT.getVectorNumElements();
3884   if (NumElts != 4)
3885     return false;
3886
3887   for (unsigned i = 0; i != NumElts/2; ++i)
3888     if (!isUndefOrEqual(Mask[i], 0))
3889       return false;
3890   for (unsigned i = NumElts/2; i != NumElts; ++i)
3891     if (!isUndefOrEqual(Mask[i], NumElts/2))
3892       return false;
3893   return true;
3894 }
3895
3896 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3897 /// specifies a shuffle of elements that is suitable for input to 128-bit
3898 /// version of MOVDDUP.
3899 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3900   if (!VT.is128BitVector())
3901     return false;
3902
3903   unsigned e = VT.getVectorNumElements() / 2;
3904   for (unsigned i = 0; i != e; ++i)
3905     if (!isUndefOrEqual(Mask[i], i))
3906       return false;
3907   for (unsigned i = 0; i != e; ++i)
3908     if (!isUndefOrEqual(Mask[e+i], i))
3909       return false;
3910   return true;
3911 }
3912
3913 /// isVEXTRACTF128Index - Return true if the specified
3914 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3915 /// suitable for input to VEXTRACTF128.
3916 bool X86::isVEXTRACTF128Index(SDNode *N) {
3917   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3918     return false;
3919
3920   // The index should be aligned on a 128-bit boundary.
3921   uint64_t Index =
3922     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3923
3924   unsigned VL = N->getValueType(0).getVectorNumElements();
3925   unsigned VBits = N->getValueType(0).getSizeInBits();
3926   unsigned ElSize = VBits / VL;
3927   bool Result = (Index * ElSize) % 128 == 0;
3928
3929   return Result;
3930 }
3931
3932 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3933 /// operand specifies a subvector insert that is suitable for input to
3934 /// VINSERTF128.
3935 bool X86::isVINSERTF128Index(SDNode *N) {
3936   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3937     return false;
3938
3939   // The index should be aligned on a 128-bit boundary.
3940   uint64_t Index =
3941     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3942
3943   unsigned VL = N->getValueType(0).getVectorNumElements();
3944   unsigned VBits = N->getValueType(0).getSizeInBits();
3945   unsigned ElSize = VBits / VL;
3946   bool Result = (Index * ElSize) % 128 == 0;
3947
3948   return Result;
3949 }
3950
3951 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3952 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3953 /// Handles 128-bit and 256-bit.
3954 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3955   EVT VT = N->getValueType(0);
3956
3957   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3958          "Unsupported vector type for PSHUF/SHUFP");
3959
3960   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3961   // independently on 128-bit lanes.
3962   unsigned NumElts = VT.getVectorNumElements();
3963   unsigned NumLanes = VT.getSizeInBits()/128;
3964   unsigned NumLaneElts = NumElts/NumLanes;
3965
3966   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3967          "Only supports 2 or 4 elements per lane");
3968
3969   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3970   unsigned Mask = 0;
3971   for (unsigned i = 0; i != NumElts; ++i) {
3972     int Elt = N->getMaskElt(i);
3973     if (Elt < 0) continue;
3974     Elt &= NumLaneElts - 1;
3975     unsigned ShAmt = (i << Shift) % 8;
3976     Mask |= Elt << ShAmt;
3977   }
3978
3979   return Mask;
3980 }
3981
3982 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3983 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3984 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3985   EVT VT = N->getValueType(0);
3986
3987   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3988          "Unsupported vector type for PSHUFHW");
3989
3990   unsigned NumElts = VT.getVectorNumElements();
3991
3992   unsigned Mask = 0;
3993   for (unsigned l = 0; l != NumElts; l += 8) {
3994     // 8 nodes per lane, but we only care about the last 4.
3995     for (unsigned i = 0; i < 4; ++i) {
3996       int Elt = N->getMaskElt(l+i+4);
3997       if (Elt < 0) continue;
3998       Elt &= 0x3; // only 2-bits.
3999       Mask |= Elt << (i * 2);
4000     }
4001   }
4002
4003   return Mask;
4004 }
4005
4006 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4007 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4008 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4009   EVT VT = N->getValueType(0);
4010
4011   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4012          "Unsupported vector type for PSHUFHW");
4013
4014   unsigned NumElts = VT.getVectorNumElements();
4015
4016   unsigned Mask = 0;
4017   for (unsigned l = 0; l != NumElts; l += 8) {
4018     // 8 nodes per lane, but we only care about the first 4.
4019     for (unsigned i = 0; i < 4; ++i) {
4020       int Elt = N->getMaskElt(l+i);
4021       if (Elt < 0) continue;
4022       Elt &= 0x3; // only 2-bits
4023       Mask |= Elt << (i * 2);
4024     }
4025   }
4026
4027   return Mask;
4028 }
4029
4030 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4031 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4032 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4033   EVT VT = SVOp->getValueType(0);
4034   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4035
4036   unsigned NumElts = VT.getVectorNumElements();
4037   unsigned NumLanes = VT.getSizeInBits()/128;
4038   unsigned NumLaneElts = NumElts/NumLanes;
4039
4040   int Val = 0;
4041   unsigned i;
4042   for (i = 0; i != NumElts; ++i) {
4043     Val = SVOp->getMaskElt(i);
4044     if (Val >= 0)
4045       break;
4046   }
4047   if (Val >= (int)NumElts)
4048     Val -= NumElts - NumLaneElts;
4049
4050   assert(Val - i > 0 && "PALIGNR imm should be positive");
4051   return (Val - i) * EltSize;
4052 }
4053
4054 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4055 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4056 /// instructions.
4057 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4058   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4059     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4060
4061   uint64_t Index =
4062     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4063
4064   EVT VecVT = N->getOperand(0).getValueType();
4065   EVT ElVT = VecVT.getVectorElementType();
4066
4067   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4068   return Index / NumElemsPerChunk;
4069 }
4070
4071 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4072 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4073 /// instructions.
4074 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4075   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4077
4078   uint64_t Index =
4079     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080
4081   EVT VecVT = N->getValueType(0);
4082   EVT ElVT = VecVT.getVectorElementType();
4083
4084   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4085   return Index / NumElemsPerChunk;
4086 }
4087
4088 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4089 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4090 /// Handles 256-bit.
4091 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4092   EVT VT = N->getValueType(0);
4093
4094   unsigned NumElts = VT.getVectorNumElements();
4095
4096   assert((VT.is256BitVector() && NumElts == 4) &&
4097          "Unsupported vector type for VPERMQ/VPERMPD");
4098
4099   unsigned Mask = 0;
4100   for (unsigned i = 0; i != NumElts; ++i) {
4101     int Elt = N->getMaskElt(i);
4102     if (Elt < 0)
4103       continue;
4104     Mask |= Elt << (i*2);
4105   }
4106
4107   return Mask;
4108 }
4109 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4110 /// constant +0.0.
4111 bool X86::isZeroNode(SDValue Elt) {
4112   return ((isa<ConstantSDNode>(Elt) &&
4113            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4114           (isa<ConstantFPSDNode>(Elt) &&
4115            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4116 }
4117
4118 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4119 /// their permute mask.
4120 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4121                                     SelectionDAG &DAG) {
4122   EVT VT = SVOp->getValueType(0);
4123   unsigned NumElems = VT.getVectorNumElements();
4124   SmallVector<int, 8> MaskVec;
4125
4126   for (unsigned i = 0; i != NumElems; ++i) {
4127     int Idx = SVOp->getMaskElt(i);
4128     if (Idx >= 0) {
4129       if (Idx < (int)NumElems)
4130         Idx += NumElems;
4131       else
4132         Idx -= NumElems;
4133     }
4134     MaskVec.push_back(Idx);
4135   }
4136   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4137                               SVOp->getOperand(0), &MaskVec[0]);
4138 }
4139
4140 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4141 /// match movhlps. The lower half elements should come from upper half of
4142 /// V1 (and in order), and the upper half elements should come from the upper
4143 /// half of V2 (and in order).
4144 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4145   if (!VT.is128BitVector())
4146     return false;
4147   if (VT.getVectorNumElements() != 4)
4148     return false;
4149   for (unsigned i = 0, e = 2; i != e; ++i)
4150     if (!isUndefOrEqual(Mask[i], i+2))
4151       return false;
4152   for (unsigned i = 2; i != 4; ++i)
4153     if (!isUndefOrEqual(Mask[i], i+4))
4154       return false;
4155   return true;
4156 }
4157
4158 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4159 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4160 /// required.
4161 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4162   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4163     return false;
4164   N = N->getOperand(0).getNode();
4165   if (!ISD::isNON_EXTLoad(N))
4166     return false;
4167   if (LD)
4168     *LD = cast<LoadSDNode>(N);
4169   return true;
4170 }
4171
4172 // Test whether the given value is a vector value which will be legalized
4173 // into a load.
4174 static bool WillBeConstantPoolLoad(SDNode *N) {
4175   if (N->getOpcode() != ISD::BUILD_VECTOR)
4176     return false;
4177
4178   // Check for any non-constant elements.
4179   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4180     switch (N->getOperand(i).getNode()->getOpcode()) {
4181     case ISD::UNDEF:
4182     case ISD::ConstantFP:
4183     case ISD::Constant:
4184       break;
4185     default:
4186       return false;
4187     }
4188
4189   // Vectors of all-zeros and all-ones are materialized with special
4190   // instructions rather than being loaded.
4191   return !ISD::isBuildVectorAllZeros(N) &&
4192          !ISD::isBuildVectorAllOnes(N);
4193 }
4194
4195 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4196 /// match movlp{s|d}. The lower half elements should come from lower half of
4197 /// V1 (and in order), and the upper half elements should come from the upper
4198 /// half of V2 (and in order). And since V1 will become the source of the
4199 /// MOVLP, it must be either a vector load or a scalar load to vector.
4200 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4201                                ArrayRef<int> Mask, EVT VT) {
4202   if (!VT.is128BitVector())
4203     return false;
4204
4205   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4206     return false;
4207   // Is V2 is a vector load, don't do this transformation. We will try to use
4208   // load folding shufps op.
4209   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4210     return false;
4211
4212   unsigned NumElems = VT.getVectorNumElements();
4213
4214   if (NumElems != 2 && NumElems != 4)
4215     return false;
4216   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4217     if (!isUndefOrEqual(Mask[i], i))
4218       return false;
4219   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4220     if (!isUndefOrEqual(Mask[i], i+NumElems))
4221       return false;
4222   return true;
4223 }
4224
4225 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4226 /// all the same.
4227 static bool isSplatVector(SDNode *N) {
4228   if (N->getOpcode() != ISD::BUILD_VECTOR)
4229     return false;
4230
4231   SDValue SplatValue = N->getOperand(0);
4232   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4233     if (N->getOperand(i) != SplatValue)
4234       return false;
4235   return true;
4236 }
4237
4238 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4239 /// to an zero vector.
4240 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4241 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4242   SDValue V1 = N->getOperand(0);
4243   SDValue V2 = N->getOperand(1);
4244   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4245   for (unsigned i = 0; i != NumElems; ++i) {
4246     int Idx = N->getMaskElt(i);
4247     if (Idx >= (int)NumElems) {
4248       unsigned Opc = V2.getOpcode();
4249       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4250         continue;
4251       if (Opc != ISD::BUILD_VECTOR ||
4252           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4253         return false;
4254     } else if (Idx >= 0) {
4255       unsigned Opc = V1.getOpcode();
4256       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4257         continue;
4258       if (Opc != ISD::BUILD_VECTOR ||
4259           !X86::isZeroNode(V1.getOperand(Idx)))
4260         return false;
4261     }
4262   }
4263   return true;
4264 }
4265
4266 /// getZeroVector - Returns a vector of specified type with all zero elements.
4267 ///
4268 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4269                              SelectionDAG &DAG, DebugLoc dl) {
4270   assert(VT.isVector() && "Expected a vector type");
4271   unsigned Size = VT.getSizeInBits();
4272
4273   // Always build SSE zero vectors as <4 x i32> bitcasted
4274   // to their dest type. This ensures they get CSE'd.
4275   SDValue Vec;
4276   if (Size == 128) {  // SSE
4277     if (Subtarget->hasSSE2()) {  // SSE2
4278       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4279       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4280     } else { // SSE1
4281       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4282       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4283     }
4284   } else if (Size == 256) { // AVX
4285     if (Subtarget->hasAVX2()) { // AVX2
4286       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4287       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4288       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4289     } else {
4290       // 256-bit logic and arithmetic instructions in AVX are all
4291       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4292       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4293       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4294       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4295     }
4296   } else
4297     llvm_unreachable("Unexpected vector type");
4298
4299   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4300 }
4301
4302 /// getOnesVector - Returns a vector of specified type with all bits set.
4303 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4304 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4305 /// Then bitcast to their original type, ensuring they get CSE'd.
4306 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4307                              DebugLoc dl) {
4308   assert(VT.isVector() && "Expected a vector type");
4309   unsigned Size = VT.getSizeInBits();
4310
4311   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4312   SDValue Vec;
4313   if (Size == 256) {
4314     if (HasAVX2) { // AVX2
4315       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4316       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4317     } else { // AVX
4318       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4319       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4320     }
4321   } else if (Size == 128) {
4322     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4323   } else
4324     llvm_unreachable("Unexpected vector type");
4325
4326   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4327 }
4328
4329 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4330 /// that point to V2 points to its first element.
4331 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4332   for (unsigned i = 0; i != NumElems; ++i) {
4333     if (Mask[i] > (int)NumElems) {
4334       Mask[i] = NumElems;
4335     }
4336   }
4337 }
4338
4339 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4340 /// operation of specified width.
4341 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4342                        SDValue V2) {
4343   unsigned NumElems = VT.getVectorNumElements();
4344   SmallVector<int, 8> Mask;
4345   Mask.push_back(NumElems);
4346   for (unsigned i = 1; i != NumElems; ++i)
4347     Mask.push_back(i);
4348   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4349 }
4350
4351 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4352 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4353                           SDValue V2) {
4354   unsigned NumElems = VT.getVectorNumElements();
4355   SmallVector<int, 8> Mask;
4356   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4357     Mask.push_back(i);
4358     Mask.push_back(i + NumElems);
4359   }
4360   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4361 }
4362
4363 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4364 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4365                           SDValue V2) {
4366   unsigned NumElems = VT.getVectorNumElements();
4367   SmallVector<int, 8> Mask;
4368   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4369     Mask.push_back(i + Half);
4370     Mask.push_back(i + NumElems + Half);
4371   }
4372   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4373 }
4374
4375 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4376 // a generic shuffle instruction because the target has no such instructions.
4377 // Generate shuffles which repeat i16 and i8 several times until they can be
4378 // represented by v4f32 and then be manipulated by target suported shuffles.
4379 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4380   EVT VT = V.getValueType();
4381   int NumElems = VT.getVectorNumElements();
4382   DebugLoc dl = V.getDebugLoc();
4383
4384   while (NumElems > 4) {
4385     if (EltNo < NumElems/2) {
4386       V = getUnpackl(DAG, dl, VT, V, V);
4387     } else {
4388       V = getUnpackh(DAG, dl, VT, V, V);
4389       EltNo -= NumElems/2;
4390     }
4391     NumElems >>= 1;
4392   }
4393   return V;
4394 }
4395
4396 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4397 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4398   EVT VT = V.getValueType();
4399   DebugLoc dl = V.getDebugLoc();
4400   unsigned Size = VT.getSizeInBits();
4401
4402   if (Size == 128) {
4403     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4404     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4405     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4406                              &SplatMask[0]);
4407   } else if (Size == 256) {
4408     // To use VPERMILPS to splat scalars, the second half of indicies must
4409     // refer to the higher part, which is a duplication of the lower one,
4410     // because VPERMILPS can only handle in-lane permutations.
4411     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4412                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4413
4414     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4415     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4416                              &SplatMask[0]);
4417   } else
4418     llvm_unreachable("Vector size not supported");
4419
4420   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4421 }
4422
4423 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4424 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4425   EVT SrcVT = SV->getValueType(0);
4426   SDValue V1 = SV->getOperand(0);
4427   DebugLoc dl = SV->getDebugLoc();
4428
4429   int EltNo = SV->getSplatIndex();
4430   int NumElems = SrcVT.getVectorNumElements();
4431   unsigned Size = SrcVT.getSizeInBits();
4432
4433   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4434           "Unknown how to promote splat for type");
4435
4436   // Extract the 128-bit part containing the splat element and update
4437   // the splat element index when it refers to the higher register.
4438   if (Size == 256) {
4439     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4440     if (EltNo >= NumElems/2)
4441       EltNo -= NumElems/2;
4442   }
4443
4444   // All i16 and i8 vector types can't be used directly by a generic shuffle
4445   // instruction because the target has no such instruction. Generate shuffles
4446   // which repeat i16 and i8 several times until they fit in i32, and then can
4447   // be manipulated by target suported shuffles.
4448   EVT EltVT = SrcVT.getVectorElementType();
4449   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4450     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4451
4452   // Recreate the 256-bit vector and place the same 128-bit vector
4453   // into the low and high part. This is necessary because we want
4454   // to use VPERM* to shuffle the vectors
4455   if (Size == 256) {
4456     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4457   }
4458
4459   return getLegalSplat(DAG, V1, EltNo);
4460 }
4461
4462 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4463 /// vector of zero or undef vector.  This produces a shuffle where the low
4464 /// element of V2 is swizzled into the zero/undef vector, landing at element
4465 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4466 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4467                                            bool IsZero,
4468                                            const X86Subtarget *Subtarget,
4469                                            SelectionDAG &DAG) {
4470   EVT VT = V2.getValueType();
4471   SDValue V1 = IsZero
4472     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4473   unsigned NumElems = VT.getVectorNumElements();
4474   SmallVector<int, 16> MaskVec;
4475   for (unsigned i = 0; i != NumElems; ++i)
4476     // If this is the insertion idx, put the low elt of V2 here.
4477     MaskVec.push_back(i == Idx ? NumElems : i);
4478   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4479 }
4480
4481 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4482 /// target specific opcode. Returns true if the Mask could be calculated.
4483 /// Sets IsUnary to true if only uses one source.
4484 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4485                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4486   unsigned NumElems = VT.getVectorNumElements();
4487   SDValue ImmN;
4488
4489   IsUnary = false;
4490   switch(N->getOpcode()) {
4491   case X86ISD::SHUFP:
4492     ImmN = N->getOperand(N->getNumOperands()-1);
4493     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494     break;
4495   case X86ISD::UNPCKH:
4496     DecodeUNPCKHMask(VT, Mask);
4497     break;
4498   case X86ISD::UNPCKL:
4499     DecodeUNPCKLMask(VT, Mask);
4500     break;
4501   case X86ISD::MOVHLPS:
4502     DecodeMOVHLPSMask(NumElems, Mask);
4503     break;
4504   case X86ISD::MOVLHPS:
4505     DecodeMOVLHPSMask(NumElems, Mask);
4506     break;
4507   case X86ISD::PSHUFD:
4508   case X86ISD::VPERMILP:
4509     ImmN = N->getOperand(N->getNumOperands()-1);
4510     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511     IsUnary = true;
4512     break;
4513   case X86ISD::PSHUFHW:
4514     ImmN = N->getOperand(N->getNumOperands()-1);
4515     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516     IsUnary = true;
4517     break;
4518   case X86ISD::PSHUFLW:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     IsUnary = true;
4522     break;
4523   case X86ISD::VPERMI:
4524     ImmN = N->getOperand(N->getNumOperands()-1);
4525     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526     IsUnary = true;
4527     break;
4528   case X86ISD::MOVSS:
4529   case X86ISD::MOVSD: {
4530     // The index 0 always comes from the first element of the second source,
4531     // this is why MOVSS and MOVSD are used in the first place. The other
4532     // elements come from the other positions of the first source vector
4533     Mask.push_back(NumElems);
4534     for (unsigned i = 1; i != NumElems; ++i) {
4535       Mask.push_back(i);
4536     }
4537     break;
4538   }
4539   case X86ISD::VPERM2X128:
4540     ImmN = N->getOperand(N->getNumOperands()-1);
4541     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4542     if (Mask.empty()) return false;
4543     break;
4544   case X86ISD::MOVDDUP:
4545   case X86ISD::MOVLHPD:
4546   case X86ISD::MOVLPD:
4547   case X86ISD::MOVLPS:
4548   case X86ISD::MOVSHDUP:
4549   case X86ISD::MOVSLDUP:
4550   case X86ISD::PALIGN:
4551     // Not yet implemented
4552     return false;
4553   default: llvm_unreachable("unknown target shuffle node");
4554   }
4555
4556   return true;
4557 }
4558
4559 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4560 /// element of the result of the vector shuffle.
4561 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4562                                    unsigned Depth) {
4563   if (Depth == 6)
4564     return SDValue();  // Limit search depth.
4565
4566   SDValue V = SDValue(N, 0);
4567   EVT VT = V.getValueType();
4568   unsigned Opcode = V.getOpcode();
4569
4570   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4571   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4572     int Elt = SV->getMaskElt(Index);
4573
4574     if (Elt < 0)
4575       return DAG.getUNDEF(VT.getVectorElementType());
4576
4577     unsigned NumElems = VT.getVectorNumElements();
4578     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4579                                          : SV->getOperand(1);
4580     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4581   }
4582
4583   // Recurse into target specific vector shuffles to find scalars.
4584   if (isTargetShuffle(Opcode)) {
4585     MVT ShufVT = V.getValueType().getSimpleVT();
4586     unsigned NumElems = ShufVT.getVectorNumElements();
4587     SmallVector<int, 16> ShuffleMask;
4588     SDValue ImmN;
4589     bool IsUnary;
4590
4591     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4592       return SDValue();
4593
4594     int Elt = ShuffleMask[Index];
4595     if (Elt < 0)
4596       return DAG.getUNDEF(ShufVT.getVectorElementType());
4597
4598     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4599                                          : N->getOperand(1);
4600     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4601                                Depth+1);
4602   }
4603
4604   // Actual nodes that may contain scalar elements
4605   if (Opcode == ISD::BITCAST) {
4606     V = V.getOperand(0);
4607     EVT SrcVT = V.getValueType();
4608     unsigned NumElems = VT.getVectorNumElements();
4609
4610     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4611       return SDValue();
4612   }
4613
4614   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4615     return (Index == 0) ? V.getOperand(0)
4616                         : DAG.getUNDEF(VT.getVectorElementType());
4617
4618   if (V.getOpcode() == ISD::BUILD_VECTOR)
4619     return V.getOperand(Index);
4620
4621   return SDValue();
4622 }
4623
4624 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4625 /// shuffle operation which come from a consecutively from a zero. The
4626 /// search can start in two different directions, from left or right.
4627 static
4628 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4629                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4630   unsigned i;
4631   for (i = 0; i != NumElems; ++i) {
4632     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4633     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4634     if (!(Elt.getNode() &&
4635          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4636       break;
4637   }
4638
4639   return i;
4640 }
4641
4642 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4643 /// correspond consecutively to elements from one of the vector operands,
4644 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4645 static
4646 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4647                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4648                               unsigned NumElems, unsigned &OpNum) {
4649   bool SeenV1 = false;
4650   bool SeenV2 = false;
4651
4652   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4653     int Idx = SVOp->getMaskElt(i);
4654     // Ignore undef indicies
4655     if (Idx < 0)
4656       continue;
4657
4658     if (Idx < (int)NumElems)
4659       SeenV1 = true;
4660     else
4661       SeenV2 = true;
4662
4663     // Only accept consecutive elements from the same vector
4664     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4665       return false;
4666   }
4667
4668   OpNum = SeenV1 ? 0 : 1;
4669   return true;
4670 }
4671
4672 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4673 /// logical left shift of a vector.
4674 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4675                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4676   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4677   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4678               false /* check zeros from right */, DAG);
4679   unsigned OpSrc;
4680
4681   if (!NumZeros)
4682     return false;
4683
4684   // Considering the elements in the mask that are not consecutive zeros,
4685   // check if they consecutively come from only one of the source vectors.
4686   //
4687   //               V1 = {X, A, B, C}     0
4688   //                         \  \  \    /
4689   //   vector_shuffle V1, V2 <1, 2, 3, X>
4690   //
4691   if (!isShuffleMaskConsecutive(SVOp,
4692             0,                   // Mask Start Index
4693             NumElems-NumZeros,   // Mask End Index(exclusive)
4694             NumZeros,            // Where to start looking in the src vector
4695             NumElems,            // Number of elements in vector
4696             OpSrc))              // Which source operand ?
4697     return false;
4698
4699   isLeft = false;
4700   ShAmt = NumZeros;
4701   ShVal = SVOp->getOperand(OpSrc);
4702   return true;
4703 }
4704
4705 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4706 /// logical left shift of a vector.
4707 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4708                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4709   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4710   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4711               true /* check zeros from left */, DAG);
4712   unsigned OpSrc;
4713
4714   if (!NumZeros)
4715     return false;
4716
4717   // Considering the elements in the mask that are not consecutive zeros,
4718   // check if they consecutively come from only one of the source vectors.
4719   //
4720   //                           0    { A, B, X, X } = V2
4721   //                          / \    /  /
4722   //   vector_shuffle V1, V2 <X, X, 4, 5>
4723   //
4724   if (!isShuffleMaskConsecutive(SVOp,
4725             NumZeros,     // Mask Start Index
4726             NumElems,     // Mask End Index(exclusive)
4727             0,            // Where to start looking in the src vector
4728             NumElems,     // Number of elements in vector
4729             OpSrc))       // Which source operand ?
4730     return false;
4731
4732   isLeft = true;
4733   ShAmt = NumZeros;
4734   ShVal = SVOp->getOperand(OpSrc);
4735   return true;
4736 }
4737
4738 /// isVectorShift - Returns true if the shuffle can be implemented as a
4739 /// logical left or right shift of a vector.
4740 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4741                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4742   // Although the logic below support any bitwidth size, there are no
4743   // shift instructions which handle more than 128-bit vectors.
4744   if (!SVOp->getValueType(0).is128BitVector())
4745     return false;
4746
4747   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4748       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4749     return true;
4750
4751   return false;
4752 }
4753
4754 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4755 ///
4756 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4757                                        unsigned NumNonZero, unsigned NumZero,
4758                                        SelectionDAG &DAG,
4759                                        const X86Subtarget* Subtarget,
4760                                        const TargetLowering &TLI) {
4761   if (NumNonZero > 8)
4762     return SDValue();
4763
4764   DebugLoc dl = Op.getDebugLoc();
4765   SDValue V(0, 0);
4766   bool First = true;
4767   for (unsigned i = 0; i < 16; ++i) {
4768     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4769     if (ThisIsNonZero && First) {
4770       if (NumZero)
4771         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4772       else
4773         V = DAG.getUNDEF(MVT::v8i16);
4774       First = false;
4775     }
4776
4777     if ((i & 1) != 0) {
4778       SDValue ThisElt(0, 0), LastElt(0, 0);
4779       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4780       if (LastIsNonZero) {
4781         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4782                               MVT::i16, Op.getOperand(i-1));
4783       }
4784       if (ThisIsNonZero) {
4785         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4786         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4787                               ThisElt, DAG.getConstant(8, MVT::i8));
4788         if (LastIsNonZero)
4789           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4790       } else
4791         ThisElt = LastElt;
4792
4793       if (ThisElt.getNode())
4794         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4795                         DAG.getIntPtrConstant(i/2));
4796     }
4797   }
4798
4799   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4800 }
4801
4802 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4803 ///
4804 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4805                                      unsigned NumNonZero, unsigned NumZero,
4806                                      SelectionDAG &DAG,
4807                                      const X86Subtarget* Subtarget,
4808                                      const TargetLowering &TLI) {
4809   if (NumNonZero > 4)
4810     return SDValue();
4811
4812   DebugLoc dl = Op.getDebugLoc();
4813   SDValue V(0, 0);
4814   bool First = true;
4815   for (unsigned i = 0; i < 8; ++i) {
4816     bool isNonZero = (NonZeros & (1 << i)) != 0;
4817     if (isNonZero) {
4818       if (First) {
4819         if (NumZero)
4820           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4821         else
4822           V = DAG.getUNDEF(MVT::v8i16);
4823         First = false;
4824       }
4825       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4826                       MVT::v8i16, V, Op.getOperand(i),
4827                       DAG.getIntPtrConstant(i));
4828     }
4829   }
4830
4831   return V;
4832 }
4833
4834 /// getVShift - Return a vector logical shift node.
4835 ///
4836 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4837                          unsigned NumBits, SelectionDAG &DAG,
4838                          const TargetLowering &TLI, DebugLoc dl) {
4839   assert(VT.is128BitVector() && "Unknown type for VShift");
4840   EVT ShVT = MVT::v2i64;
4841   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4842   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4843   return DAG.getNode(ISD::BITCAST, dl, VT,
4844                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4845                              DAG.getConstant(NumBits,
4846                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4847 }
4848
4849 SDValue
4850 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4851                                           SelectionDAG &DAG) const {
4852
4853   // Check if the scalar load can be widened into a vector load. And if
4854   // the address is "base + cst" see if the cst can be "absorbed" into
4855   // the shuffle mask.
4856   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4857     SDValue Ptr = LD->getBasePtr();
4858     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4859       return SDValue();
4860     EVT PVT = LD->getValueType(0);
4861     if (PVT != MVT::i32 && PVT != MVT::f32)
4862       return SDValue();
4863
4864     int FI = -1;
4865     int64_t Offset = 0;
4866     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4867       FI = FINode->getIndex();
4868       Offset = 0;
4869     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4870                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4871       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4872       Offset = Ptr.getConstantOperandVal(1);
4873       Ptr = Ptr.getOperand(0);
4874     } else {
4875       return SDValue();
4876     }
4877
4878     // FIXME: 256-bit vector instructions don't require a strict alignment,
4879     // improve this code to support it better.
4880     unsigned RequiredAlign = VT.getSizeInBits()/8;
4881     SDValue Chain = LD->getChain();
4882     // Make sure the stack object alignment is at least 16 or 32.
4883     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4884     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4885       if (MFI->isFixedObjectIndex(FI)) {
4886         // Can't change the alignment. FIXME: It's possible to compute
4887         // the exact stack offset and reference FI + adjust offset instead.
4888         // If someone *really* cares about this. That's the way to implement it.
4889         return SDValue();
4890       } else {
4891         MFI->setObjectAlignment(FI, RequiredAlign);
4892       }
4893     }
4894
4895     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4896     // Ptr + (Offset & ~15).
4897     if (Offset < 0)
4898       return SDValue();
4899     if ((Offset % RequiredAlign) & 3)
4900       return SDValue();
4901     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4902     if (StartOffset)
4903       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4904                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4905
4906     int EltNo = (Offset - StartOffset) >> 2;
4907     unsigned NumElems = VT.getVectorNumElements();
4908
4909     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4910     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4911                              LD->getPointerInfo().getWithOffset(StartOffset),
4912                              false, false, false, 0);
4913
4914     SmallVector<int, 8> Mask;
4915     for (unsigned i = 0; i != NumElems; ++i)
4916       Mask.push_back(EltNo);
4917
4918     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4919   }
4920
4921   return SDValue();
4922 }
4923
4924 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4925 /// vector of type 'VT', see if the elements can be replaced by a single large
4926 /// load which has the same value as a build_vector whose operands are 'elts'.
4927 ///
4928 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4929 ///
4930 /// FIXME: we'd also like to handle the case where the last elements are zero
4931 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4932 /// There's even a handy isZeroNode for that purpose.
4933 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4934                                         DebugLoc &DL, SelectionDAG &DAG) {
4935   EVT EltVT = VT.getVectorElementType();
4936   unsigned NumElems = Elts.size();
4937
4938   LoadSDNode *LDBase = NULL;
4939   unsigned LastLoadedElt = -1U;
4940
4941   // For each element in the initializer, see if we've found a load or an undef.
4942   // If we don't find an initial load element, or later load elements are
4943   // non-consecutive, bail out.
4944   for (unsigned i = 0; i < NumElems; ++i) {
4945     SDValue Elt = Elts[i];
4946
4947     if (!Elt.getNode() ||
4948         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4949       return SDValue();
4950     if (!LDBase) {
4951       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4952         return SDValue();
4953       LDBase = cast<LoadSDNode>(Elt.getNode());
4954       LastLoadedElt = i;
4955       continue;
4956     }
4957     if (Elt.getOpcode() == ISD::UNDEF)
4958       continue;
4959
4960     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4961     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4962       return SDValue();
4963     LastLoadedElt = i;
4964   }
4965
4966   // If we have found an entire vector of loads and undefs, then return a large
4967   // load of the entire vector width starting at the base pointer.  If we found
4968   // consecutive loads for the low half, generate a vzext_load node.
4969   if (LastLoadedElt == NumElems - 1) {
4970     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4971       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4972                          LDBase->getPointerInfo(),
4973                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4974                          LDBase->isInvariant(), 0);
4975     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4976                        LDBase->getPointerInfo(),
4977                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4978                        LDBase->isInvariant(), LDBase->getAlignment());
4979   }
4980   if (NumElems == 4 && LastLoadedElt == 1 &&
4981       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4982     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4983     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4984     SDValue ResNode =
4985         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4986                                 LDBase->getPointerInfo(),
4987                                 LDBase->getAlignment(),
4988                                 false/*isVolatile*/, true/*ReadMem*/,
4989                                 false/*WriteMem*/);
4990
4991     // Make sure the newly-created LOAD is in the same position as LDBase in
4992     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4993     // update uses of LDBase's output chain to use the TokenFactor.
4994     if (LDBase->hasAnyUseOfValue(1)) {
4995       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4996                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4997       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4998       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4999                              SDValue(ResNode.getNode(), 1));
5000     }
5001
5002     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5003   }
5004   return SDValue();
5005 }
5006
5007 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5008 /// to generate a splat value for the following cases:
5009 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5010 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5011 /// a scalar load, or a constant.
5012 /// The VBROADCAST node is returned when a pattern is found,
5013 /// or SDValue() otherwise.
5014 SDValue
5015 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5016   if (!Subtarget->hasAVX())
5017     return SDValue();
5018
5019   EVT VT = Op.getValueType();
5020   DebugLoc dl = Op.getDebugLoc();
5021
5022   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5023          "Unsupported vector type for broadcast.");
5024
5025   SDValue Ld;
5026   bool ConstSplatVal;
5027
5028   switch (Op.getOpcode()) {
5029     default:
5030       // Unknown pattern found.
5031       return SDValue();
5032
5033     case ISD::BUILD_VECTOR: {
5034       // The BUILD_VECTOR node must be a splat.
5035       if (!isSplatVector(Op.getNode()))
5036         return SDValue();
5037
5038       Ld = Op.getOperand(0);
5039       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5040                      Ld.getOpcode() == ISD::ConstantFP);
5041
5042       // The suspected load node has several users. Make sure that all
5043       // of its users are from the BUILD_VECTOR node.
5044       // Constants may have multiple users.
5045       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5046         return SDValue();
5047       break;
5048     }
5049
5050     case ISD::VECTOR_SHUFFLE: {
5051       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5052
5053       // Shuffles must have a splat mask where the first element is
5054       // broadcasted.
5055       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5056         return SDValue();
5057
5058       SDValue Sc = Op.getOperand(0);
5059       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5060           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5061
5062         if (!Subtarget->hasAVX2())
5063           return SDValue();
5064
5065         // Use the register form of the broadcast instruction available on AVX2.
5066         if (VT.is256BitVector())
5067           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5068         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5069       }
5070
5071       Ld = Sc.getOperand(0);
5072       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5073                        Ld.getOpcode() == ISD::ConstantFP);
5074
5075       // The scalar_to_vector node and the suspected
5076       // load node must have exactly one user.
5077       // Constants may have multiple users.
5078       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5079         return SDValue();
5080       break;
5081     }
5082   }
5083
5084   bool Is256 = VT.is256BitVector();
5085
5086   // Handle the broadcasting a single constant scalar from the constant pool
5087   // into a vector. On Sandybridge it is still better to load a constant vector
5088   // from the constant pool and not to broadcast it from a scalar.
5089   if (ConstSplatVal && Subtarget->hasAVX2()) {
5090     EVT CVT = Ld.getValueType();
5091     assert(!CVT.isVector() && "Must not broadcast a vector type");
5092     unsigned ScalarSize = CVT.getSizeInBits();
5093
5094     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5095       const Constant *C = 0;
5096       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5097         C = CI->getConstantIntValue();
5098       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5099         C = CF->getConstantFPValue();
5100
5101       assert(C && "Invalid constant type");
5102
5103       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5104       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5105       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5106                        MachinePointerInfo::getConstantPool(),
5107                        false, false, false, Alignment);
5108
5109       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5110     }
5111   }
5112
5113   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5114   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5115
5116   // Handle AVX2 in-register broadcasts.
5117   if (!IsLoad && Subtarget->hasAVX2() &&
5118       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5119     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5120
5121   // The scalar source must be a normal load.
5122   if (!IsLoad)
5123     return SDValue();
5124
5125   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5126     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5127
5128   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5129   // double since there is no vbroadcastsd xmm
5130   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5131     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5132       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5133   }
5134
5135   // Unsupported broadcast.
5136   return SDValue();
5137 }
5138
5139 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5140 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5141 // constraint of matching input/output vector elements.
5142 SDValue
5143 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5144   DebugLoc DL = Op.getDebugLoc();
5145   SDNode *N = Op.getNode();
5146   EVT VT = Op.getValueType();
5147   unsigned NumElts = Op.getNumOperands();
5148
5149   // Check supported types and sub-targets.
5150   //
5151   // Only v2f32 -> v2f64 needs special handling.
5152   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5153     return SDValue();
5154
5155   SDValue VecIn;
5156   EVT VecInVT;
5157   SmallVector<int, 8> Mask;
5158   EVT SrcVT = MVT::Other;
5159
5160   // Check the patterns could be translated into X86vfpext.
5161   for (unsigned i = 0; i < NumElts; ++i) {
5162     SDValue In = N->getOperand(i);
5163     unsigned Opcode = In.getOpcode();
5164
5165     // Skip if the element is undefined.
5166     if (Opcode == ISD::UNDEF) {
5167       Mask.push_back(-1);
5168       continue;
5169     }
5170
5171     // Quit if one of the elements is not defined from 'fpext'.
5172     if (Opcode != ISD::FP_EXTEND)
5173       return SDValue();
5174
5175     // Check how the source of 'fpext' is defined.
5176     SDValue L2In = In.getOperand(0);
5177     EVT L2InVT = L2In.getValueType();
5178
5179     // Check the original type
5180     if (SrcVT == MVT::Other)
5181       SrcVT = L2InVT;
5182     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5183       return SDValue();
5184
5185     // Check whether the value being 'fpext'ed is extracted from the same
5186     // source.
5187     Opcode = L2In.getOpcode();
5188
5189     // Quit if it's not extracted with a constant index.
5190     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5191         !isa<ConstantSDNode>(L2In.getOperand(1)))
5192       return SDValue();
5193
5194     SDValue ExtractedFromVec = L2In.getOperand(0);
5195
5196     if (VecIn.getNode() == 0) {
5197       VecIn = ExtractedFromVec;
5198       VecInVT = ExtractedFromVec.getValueType();
5199     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5200       return SDValue();
5201
5202     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5203   }
5204
5205   // Quit if all operands of BUILD_VECTOR are undefined.
5206   if (!VecIn.getNode())
5207     return SDValue();
5208
5209   // Fill the remaining mask as undef.
5210   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5211     Mask.push_back(-1);
5212
5213   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5214                      DAG.getVectorShuffle(VecInVT, DL,
5215                                           VecIn, DAG.getUNDEF(VecInVT),
5216                                           &Mask[0]));
5217 }
5218
5219 SDValue
5220 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5221   DebugLoc dl = Op.getDebugLoc();
5222
5223   EVT VT = Op.getValueType();
5224   EVT ExtVT = VT.getVectorElementType();
5225   unsigned NumElems = Op.getNumOperands();
5226
5227   // Vectors containing all zeros can be matched by pxor and xorps later
5228   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5229     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5230     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5231     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5232       return Op;
5233
5234     return getZeroVector(VT, Subtarget, DAG, dl);
5235   }
5236
5237   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5238   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5239   // vpcmpeqd on 256-bit vectors.
5240   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5241     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5242       return Op;
5243
5244     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5245   }
5246
5247   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5248   if (Broadcast.getNode())
5249     return Broadcast;
5250
5251   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5252   if (FpExt.getNode())
5253     return FpExt;
5254
5255   unsigned EVTBits = ExtVT.getSizeInBits();
5256
5257   unsigned NumZero  = 0;
5258   unsigned NumNonZero = 0;
5259   unsigned NonZeros = 0;
5260   bool IsAllConstants = true;
5261   SmallSet<SDValue, 8> Values;
5262   for (unsigned i = 0; i < NumElems; ++i) {
5263     SDValue Elt = Op.getOperand(i);
5264     if (Elt.getOpcode() == ISD::UNDEF)
5265       continue;
5266     Values.insert(Elt);
5267     if (Elt.getOpcode() != ISD::Constant &&
5268         Elt.getOpcode() != ISD::ConstantFP)
5269       IsAllConstants = false;
5270     if (X86::isZeroNode(Elt))
5271       NumZero++;
5272     else {
5273       NonZeros |= (1 << i);
5274       NumNonZero++;
5275     }
5276   }
5277
5278   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5279   if (NumNonZero == 0)
5280     return DAG.getUNDEF(VT);
5281
5282   // Special case for single non-zero, non-undef, element.
5283   if (NumNonZero == 1) {
5284     unsigned Idx = CountTrailingZeros_32(NonZeros);
5285     SDValue Item = Op.getOperand(Idx);
5286
5287     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5288     // the value are obviously zero, truncate the value to i32 and do the
5289     // insertion that way.  Only do this if the value is non-constant or if the
5290     // value is a constant being inserted into element 0.  It is cheaper to do
5291     // a constant pool load than it is to do a movd + shuffle.
5292     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5293         (!IsAllConstants || Idx == 0)) {
5294       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5295         // Handle SSE only.
5296         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5297         EVT VecVT = MVT::v4i32;
5298         unsigned VecElts = 4;
5299
5300         // Truncate the value (which may itself be a constant) to i32, and
5301         // convert it to a vector with movd (S2V+shuffle to zero extend).
5302         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5303         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5304         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5305
5306         // Now we have our 32-bit value zero extended in the low element of
5307         // a vector.  If Idx != 0, swizzle it into place.
5308         if (Idx != 0) {
5309           SmallVector<int, 4> Mask;
5310           Mask.push_back(Idx);
5311           for (unsigned i = 1; i != VecElts; ++i)
5312             Mask.push_back(i);
5313           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5314                                       &Mask[0]);
5315         }
5316         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5317       }
5318     }
5319
5320     // If we have a constant or non-constant insertion into the low element of
5321     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5322     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5323     // depending on what the source datatype is.
5324     if (Idx == 0) {
5325       if (NumZero == 0)
5326         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5327
5328       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5329           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5330         if (VT.is256BitVector()) {
5331           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5332           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5333                              Item, DAG.getIntPtrConstant(0));
5334         }
5335         assert(VT.is128BitVector() && "Expected an SSE value type!");
5336         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5337         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5338         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5339       }
5340
5341       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5342         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5343         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5344         if (VT.is256BitVector()) {
5345           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5346           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5347         } else {
5348           assert(VT.is128BitVector() && "Expected an SSE value type!");
5349           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5350         }
5351         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5352       }
5353     }
5354
5355     // Is it a vector logical left shift?
5356     if (NumElems == 2 && Idx == 1 &&
5357         X86::isZeroNode(Op.getOperand(0)) &&
5358         !X86::isZeroNode(Op.getOperand(1))) {
5359       unsigned NumBits = VT.getSizeInBits();
5360       return getVShift(true, VT,
5361                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5362                                    VT, Op.getOperand(1)),
5363                        NumBits/2, DAG, *this, dl);
5364     }
5365
5366     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5367       return SDValue();
5368
5369     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5370     // is a non-constant being inserted into an element other than the low one,
5371     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5372     // movd/movss) to move this into the low element, then shuffle it into
5373     // place.
5374     if (EVTBits == 32) {
5375       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5376
5377       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5378       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5379       SmallVector<int, 8> MaskVec;
5380       for (unsigned i = 0; i != NumElems; ++i)
5381         MaskVec.push_back(i == Idx ? 0 : 1);
5382       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5383     }
5384   }
5385
5386   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5387   if (Values.size() == 1) {
5388     if (EVTBits == 32) {
5389       // Instead of a shuffle like this:
5390       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5391       // Check if it's possible to issue this instead.
5392       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5393       unsigned Idx = CountTrailingZeros_32(NonZeros);
5394       SDValue Item = Op.getOperand(Idx);
5395       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5396         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5397     }
5398     return SDValue();
5399   }
5400
5401   // A vector full of immediates; various special cases are already
5402   // handled, so this is best done with a single constant-pool load.
5403   if (IsAllConstants)
5404     return SDValue();
5405
5406   // For AVX-length vectors, build the individual 128-bit pieces and use
5407   // shuffles to put them in place.
5408   if (VT.is256BitVector()) {
5409     SmallVector<SDValue, 32> V;
5410     for (unsigned i = 0; i != NumElems; ++i)
5411       V.push_back(Op.getOperand(i));
5412
5413     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5414
5415     // Build both the lower and upper subvector.
5416     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5417     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5418                                 NumElems/2);
5419
5420     // Recreate the wider vector with the lower and upper part.
5421     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5422   }
5423
5424   // Let legalizer expand 2-wide build_vectors.
5425   if (EVTBits == 64) {
5426     if (NumNonZero == 1) {
5427       // One half is zero or undef.
5428       unsigned Idx = CountTrailingZeros_32(NonZeros);
5429       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5430                                  Op.getOperand(Idx));
5431       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5432     }
5433     return SDValue();
5434   }
5435
5436   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5437   if (EVTBits == 8 && NumElems == 16) {
5438     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5439                                         Subtarget, *this);
5440     if (V.getNode()) return V;
5441   }
5442
5443   if (EVTBits == 16 && NumElems == 8) {
5444     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5445                                       Subtarget, *this);
5446     if (V.getNode()) return V;
5447   }
5448
5449   // If element VT is == 32 bits, turn it into a number of shuffles.
5450   SmallVector<SDValue, 8> V(NumElems);
5451   if (NumElems == 4 && NumZero > 0) {
5452     for (unsigned i = 0; i < 4; ++i) {
5453       bool isZero = !(NonZeros & (1 << i));
5454       if (isZero)
5455         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5456       else
5457         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5458     }
5459
5460     for (unsigned i = 0; i < 2; ++i) {
5461       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5462         default: break;
5463         case 0:
5464           V[i] = V[i*2];  // Must be a zero vector.
5465           break;
5466         case 1:
5467           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5468           break;
5469         case 2:
5470           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5471           break;
5472         case 3:
5473           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5474           break;
5475       }
5476     }
5477
5478     bool Reverse1 = (NonZeros & 0x3) == 2;
5479     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5480     int MaskVec[] = {
5481       Reverse1 ? 1 : 0,
5482       Reverse1 ? 0 : 1,
5483       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5484       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5485     };
5486     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5487   }
5488
5489   if (Values.size() > 1 && VT.is128BitVector()) {
5490     // Check for a build vector of consecutive loads.
5491     for (unsigned i = 0; i < NumElems; ++i)
5492       V[i] = Op.getOperand(i);
5493
5494     // Check for elements which are consecutive loads.
5495     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5496     if (LD.getNode())
5497       return LD;
5498
5499     // For SSE 4.1, use insertps to put the high elements into the low element.
5500     if (getSubtarget()->hasSSE41()) {
5501       SDValue Result;
5502       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5503         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5504       else
5505         Result = DAG.getUNDEF(VT);
5506
5507       for (unsigned i = 1; i < NumElems; ++i) {
5508         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5509         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5510                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5511       }
5512       return Result;
5513     }
5514
5515     // Otherwise, expand into a number of unpckl*, start by extending each of
5516     // our (non-undef) elements to the full vector width with the element in the
5517     // bottom slot of the vector (which generates no code for SSE).
5518     for (unsigned i = 0; i < NumElems; ++i) {
5519       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5520         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5521       else
5522         V[i] = DAG.getUNDEF(VT);
5523     }
5524
5525     // Next, we iteratively mix elements, e.g. for v4f32:
5526     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5527     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5528     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5529     unsigned EltStride = NumElems >> 1;
5530     while (EltStride != 0) {
5531       for (unsigned i = 0; i < EltStride; ++i) {
5532         // If V[i+EltStride] is undef and this is the first round of mixing,
5533         // then it is safe to just drop this shuffle: V[i] is already in the
5534         // right place, the one element (since it's the first round) being
5535         // inserted as undef can be dropped.  This isn't safe for successive
5536         // rounds because they will permute elements within both vectors.
5537         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5538             EltStride == NumElems/2)
5539           continue;
5540
5541         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5542       }
5543       EltStride >>= 1;
5544     }
5545     return V[0];
5546   }
5547   return SDValue();
5548 }
5549
5550 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5551 // to create 256-bit vectors from two other 128-bit ones.
5552 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5553   DebugLoc dl = Op.getDebugLoc();
5554   EVT ResVT = Op.getValueType();
5555
5556   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5557
5558   SDValue V1 = Op.getOperand(0);
5559   SDValue V2 = Op.getOperand(1);
5560   unsigned NumElems = ResVT.getVectorNumElements();
5561
5562   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5563 }
5564
5565 SDValue
5566 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5567   assert(Op.getNumOperands() == 2);
5568
5569   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5570   // from two other 128-bit ones.
5571   return LowerAVXCONCAT_VECTORS(Op, DAG);
5572 }
5573
5574 // Try to lower a shuffle node into a simple blend instruction.
5575 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5576                                           const X86Subtarget *Subtarget,
5577                                           SelectionDAG &DAG) {
5578   SDValue V1 = SVOp->getOperand(0);
5579   SDValue V2 = SVOp->getOperand(1);
5580   DebugLoc dl = SVOp->getDebugLoc();
5581   MVT VT = SVOp->getValueType(0).getSimpleVT();
5582   unsigned NumElems = VT.getVectorNumElements();
5583
5584   if (!Subtarget->hasSSE41())
5585     return SDValue();
5586
5587   unsigned ISDNo = 0;
5588   MVT OpTy;
5589
5590   switch (VT.SimpleTy) {
5591   default: return SDValue();
5592   case MVT::v8i16:
5593     ISDNo = X86ISD::BLENDPW;
5594     OpTy = MVT::v8i16;
5595     break;
5596   case MVT::v4i32:
5597   case MVT::v4f32:
5598     ISDNo = X86ISD::BLENDPS;
5599     OpTy = MVT::v4f32;
5600     break;
5601   case MVT::v2i64:
5602   case MVT::v2f64:
5603     ISDNo = X86ISD::BLENDPD;
5604     OpTy = MVT::v2f64;
5605     break;
5606   case MVT::v8i32:
5607   case MVT::v8f32:
5608     if (!Subtarget->hasAVX())
5609       return SDValue();
5610     ISDNo = X86ISD::BLENDPS;
5611     OpTy = MVT::v8f32;
5612     break;
5613   case MVT::v4i64:
5614   case MVT::v4f64:
5615     if (!Subtarget->hasAVX())
5616       return SDValue();
5617     ISDNo = X86ISD::BLENDPD;
5618     OpTy = MVT::v4f64;
5619     break;
5620   }
5621   assert(ISDNo && "Invalid Op Number");
5622
5623   unsigned MaskVals = 0;
5624
5625   for (unsigned i = 0; i != NumElems; ++i) {
5626     int EltIdx = SVOp->getMaskElt(i);
5627     if (EltIdx == (int)i || EltIdx < 0)
5628       MaskVals |= (1<<i);
5629     else if (EltIdx == (int)(i + NumElems))
5630       continue; // Bit is set to zero;
5631     else
5632       return SDValue();
5633   }
5634
5635   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5636   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5637   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5638                              DAG.getConstant(MaskVals, MVT::i32));
5639   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5640 }
5641
5642 // v8i16 shuffles - Prefer shuffles in the following order:
5643 // 1. [all]   pshuflw, pshufhw, optional move
5644 // 2. [ssse3] 1 x pshufb
5645 // 3. [ssse3] 2 x pshufb + 1 x por
5646 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5647 SDValue
5648 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5649                                             SelectionDAG &DAG) const {
5650   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5651   SDValue V1 = SVOp->getOperand(0);
5652   SDValue V2 = SVOp->getOperand(1);
5653   DebugLoc dl = SVOp->getDebugLoc();
5654   SmallVector<int, 8> MaskVals;
5655
5656   // Determine if more than 1 of the words in each of the low and high quadwords
5657   // of the result come from the same quadword of one of the two inputs.  Undef
5658   // mask values count as coming from any quadword, for better codegen.
5659   unsigned LoQuad[] = { 0, 0, 0, 0 };
5660   unsigned HiQuad[] = { 0, 0, 0, 0 };
5661   std::bitset<4> InputQuads;
5662   for (unsigned i = 0; i < 8; ++i) {
5663     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5664     int EltIdx = SVOp->getMaskElt(i);
5665     MaskVals.push_back(EltIdx);
5666     if (EltIdx < 0) {
5667       ++Quad[0];
5668       ++Quad[1];
5669       ++Quad[2];
5670       ++Quad[3];
5671       continue;
5672     }
5673     ++Quad[EltIdx / 4];
5674     InputQuads.set(EltIdx / 4);
5675   }
5676
5677   int BestLoQuad = -1;
5678   unsigned MaxQuad = 1;
5679   for (unsigned i = 0; i < 4; ++i) {
5680     if (LoQuad[i] > MaxQuad) {
5681       BestLoQuad = i;
5682       MaxQuad = LoQuad[i];
5683     }
5684   }
5685
5686   int BestHiQuad = -1;
5687   MaxQuad = 1;
5688   for (unsigned i = 0; i < 4; ++i) {
5689     if (HiQuad[i] > MaxQuad) {
5690       BestHiQuad = i;
5691       MaxQuad = HiQuad[i];
5692     }
5693   }
5694
5695   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5696   // of the two input vectors, shuffle them into one input vector so only a
5697   // single pshufb instruction is necessary. If There are more than 2 input
5698   // quads, disable the next transformation since it does not help SSSE3.
5699   bool V1Used = InputQuads[0] || InputQuads[1];
5700   bool V2Used = InputQuads[2] || InputQuads[3];
5701   if (Subtarget->hasSSSE3()) {
5702     if (InputQuads.count() == 2 && V1Used && V2Used) {
5703       BestLoQuad = InputQuads[0] ? 0 : 1;
5704       BestHiQuad = InputQuads[2] ? 2 : 3;
5705     }
5706     if (InputQuads.count() > 2) {
5707       BestLoQuad = -1;
5708       BestHiQuad = -1;
5709     }
5710   }
5711
5712   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5713   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5714   // words from all 4 input quadwords.
5715   SDValue NewV;
5716   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5717     int MaskV[] = {
5718       BestLoQuad < 0 ? 0 : BestLoQuad,
5719       BestHiQuad < 0 ? 1 : BestHiQuad
5720     };
5721     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5722                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5723                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5724     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5725
5726     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5727     // source words for the shuffle, to aid later transformations.
5728     bool AllWordsInNewV = true;
5729     bool InOrder[2] = { true, true };
5730     for (unsigned i = 0; i != 8; ++i) {
5731       int idx = MaskVals[i];
5732       if (idx != (int)i)
5733         InOrder[i/4] = false;
5734       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5735         continue;
5736       AllWordsInNewV = false;
5737       break;
5738     }
5739
5740     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5741     if (AllWordsInNewV) {
5742       for (int i = 0; i != 8; ++i) {
5743         int idx = MaskVals[i];
5744         if (idx < 0)
5745           continue;
5746         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5747         if ((idx != i) && idx < 4)
5748           pshufhw = false;
5749         if ((idx != i) && idx > 3)
5750           pshuflw = false;
5751       }
5752       V1 = NewV;
5753       V2Used = false;
5754       BestLoQuad = 0;
5755       BestHiQuad = 1;
5756     }
5757
5758     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5759     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5760     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5761       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5762       unsigned TargetMask = 0;
5763       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5764                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5765       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5766       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5767                              getShufflePSHUFLWImmediate(SVOp);
5768       V1 = NewV.getOperand(0);
5769       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5770     }
5771   }
5772
5773   // If we have SSSE3, and all words of the result are from 1 input vector,
5774   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5775   // is present, fall back to case 4.
5776   if (Subtarget->hasSSSE3()) {
5777     SmallVector<SDValue,16> pshufbMask;
5778
5779     // If we have elements from both input vectors, set the high bit of the
5780     // shuffle mask element to zero out elements that come from V2 in the V1
5781     // mask, and elements that come from V1 in the V2 mask, so that the two
5782     // results can be OR'd together.
5783     bool TwoInputs = V1Used && V2Used;
5784     for (unsigned i = 0; i != 8; ++i) {
5785       int EltIdx = MaskVals[i] * 2;
5786       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5787       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5788       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5789       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5790     }
5791     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5792     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5793                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5794                                  MVT::v16i8, &pshufbMask[0], 16));
5795     if (!TwoInputs)
5796       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5797
5798     // Calculate the shuffle mask for the second input, shuffle it, and
5799     // OR it with the first shuffled input.
5800     pshufbMask.clear();
5801     for (unsigned i = 0; i != 8; ++i) {
5802       int EltIdx = MaskVals[i] * 2;
5803       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5804       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5805       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5806       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5807     }
5808     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5809     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5810                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5811                                  MVT::v16i8, &pshufbMask[0], 16));
5812     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5813     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5814   }
5815
5816   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5817   // and update MaskVals with new element order.
5818   std::bitset<8> InOrder;
5819   if (BestLoQuad >= 0) {
5820     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5821     for (int i = 0; i != 4; ++i) {
5822       int idx = MaskVals[i];
5823       if (idx < 0) {
5824         InOrder.set(i);
5825       } else if ((idx / 4) == BestLoQuad) {
5826         MaskV[i] = idx & 3;
5827         InOrder.set(i);
5828       }
5829     }
5830     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5831                                 &MaskV[0]);
5832
5833     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5834       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5835       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5836                                   NewV.getOperand(0),
5837                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5838     }
5839   }
5840
5841   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5842   // and update MaskVals with the new element order.
5843   if (BestHiQuad >= 0) {
5844     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5845     for (unsigned i = 4; i != 8; ++i) {
5846       int idx = MaskVals[i];
5847       if (idx < 0) {
5848         InOrder.set(i);
5849       } else if ((idx / 4) == BestHiQuad) {
5850         MaskV[i] = (idx & 3) + 4;
5851         InOrder.set(i);
5852       }
5853     }
5854     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5855                                 &MaskV[0]);
5856
5857     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5858       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5859       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5860                                   NewV.getOperand(0),
5861                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5862     }
5863   }
5864
5865   // In case BestHi & BestLo were both -1, which means each quadword has a word
5866   // from each of the four input quadwords, calculate the InOrder bitvector now
5867   // before falling through to the insert/extract cleanup.
5868   if (BestLoQuad == -1 && BestHiQuad == -1) {
5869     NewV = V1;
5870     for (int i = 0; i != 8; ++i)
5871       if (MaskVals[i] < 0 || MaskVals[i] == i)
5872         InOrder.set(i);
5873   }
5874
5875   // The other elements are put in the right place using pextrw and pinsrw.
5876   for (unsigned i = 0; i != 8; ++i) {
5877     if (InOrder[i])
5878       continue;
5879     int EltIdx = MaskVals[i];
5880     if (EltIdx < 0)
5881       continue;
5882     SDValue ExtOp = (EltIdx < 8) ?
5883       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5884                   DAG.getIntPtrConstant(EltIdx)) :
5885       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5886                   DAG.getIntPtrConstant(EltIdx - 8));
5887     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5888                        DAG.getIntPtrConstant(i));
5889   }
5890   return NewV;
5891 }
5892
5893 // v16i8 shuffles - Prefer shuffles in the following order:
5894 // 1. [ssse3] 1 x pshufb
5895 // 2. [ssse3] 2 x pshufb + 1 x por
5896 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5897 static
5898 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5899                                  SelectionDAG &DAG,
5900                                  const X86TargetLowering &TLI) {
5901   SDValue V1 = SVOp->getOperand(0);
5902   SDValue V2 = SVOp->getOperand(1);
5903   DebugLoc dl = SVOp->getDebugLoc();
5904   ArrayRef<int> MaskVals = SVOp->getMask();
5905
5906   // If we have SSSE3, case 1 is generated when all result bytes come from
5907   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5908   // present, fall back to case 3.
5909
5910   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5911   if (TLI.getSubtarget()->hasSSSE3()) {
5912     SmallVector<SDValue,16> pshufbMask;
5913
5914     // If all result elements are from one input vector, then only translate
5915     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5916     //
5917     // Otherwise, we have elements from both input vectors, and must zero out
5918     // elements that come from V2 in the first mask, and V1 in the second mask
5919     // so that we can OR them together.
5920     for (unsigned i = 0; i != 16; ++i) {
5921       int EltIdx = MaskVals[i];
5922       if (EltIdx < 0 || EltIdx >= 16)
5923         EltIdx = 0x80;
5924       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5925     }
5926     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5927                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5928                                  MVT::v16i8, &pshufbMask[0], 16));
5929
5930     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5931     // the 2nd operand if it's undefined or zero.
5932     if (V2.getOpcode() == ISD::UNDEF ||
5933         ISD::isBuildVectorAllZeros(V2.getNode()))
5934       return V1;
5935
5936     // Calculate the shuffle mask for the second input, shuffle it, and
5937     // OR it with the first shuffled input.
5938     pshufbMask.clear();
5939     for (unsigned i = 0; i != 16; ++i) {
5940       int EltIdx = MaskVals[i];
5941       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5942       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5943     }
5944     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5945                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5946                                  MVT::v16i8, &pshufbMask[0], 16));
5947     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5948   }
5949
5950   // No SSSE3 - Calculate in place words and then fix all out of place words
5951   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5952   // the 16 different words that comprise the two doublequadword input vectors.
5953   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5954   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5955   SDValue NewV = V1;
5956   for (int i = 0; i != 8; ++i) {
5957     int Elt0 = MaskVals[i*2];
5958     int Elt1 = MaskVals[i*2+1];
5959
5960     // This word of the result is all undef, skip it.
5961     if (Elt0 < 0 && Elt1 < 0)
5962       continue;
5963
5964     // This word of the result is already in the correct place, skip it.
5965     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5966       continue;
5967
5968     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5969     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5970     SDValue InsElt;
5971
5972     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5973     // using a single extract together, load it and store it.
5974     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5975       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5976                            DAG.getIntPtrConstant(Elt1 / 2));
5977       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5978                         DAG.getIntPtrConstant(i));
5979       continue;
5980     }
5981
5982     // If Elt1 is defined, extract it from the appropriate source.  If the
5983     // source byte is not also odd, shift the extracted word left 8 bits
5984     // otherwise clear the bottom 8 bits if we need to do an or.
5985     if (Elt1 >= 0) {
5986       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5987                            DAG.getIntPtrConstant(Elt1 / 2));
5988       if ((Elt1 & 1) == 0)
5989         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5990                              DAG.getConstant(8,
5991                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5992       else if (Elt0 >= 0)
5993         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5994                              DAG.getConstant(0xFF00, MVT::i16));
5995     }
5996     // If Elt0 is defined, extract it from the appropriate source.  If the
5997     // source byte is not also even, shift the extracted word right 8 bits. If
5998     // Elt1 was also defined, OR the extracted values together before
5999     // inserting them in the result.
6000     if (Elt0 >= 0) {
6001       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6002                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6003       if ((Elt0 & 1) != 0)
6004         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6005                               DAG.getConstant(8,
6006                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6007       else if (Elt1 >= 0)
6008         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6009                              DAG.getConstant(0x00FF, MVT::i16));
6010       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6011                          : InsElt0;
6012     }
6013     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6014                        DAG.getIntPtrConstant(i));
6015   }
6016   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6017 }
6018
6019 // v32i8 shuffles - Translate to VPSHUFB if possible.
6020 static
6021 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6022                                  SelectionDAG &DAG,
6023                                  const X86TargetLowering &TLI) {
6024   EVT VT = SVOp->getValueType(0);
6025   SDValue V1 = SVOp->getOperand(0);
6026   SDValue V2 = SVOp->getOperand(1);
6027   DebugLoc dl = SVOp->getDebugLoc();
6028   ArrayRef<int> MaskVals = SVOp->getMask();
6029
6030   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6031
6032   if (VT != MVT::v32i8 || !TLI.getSubtarget()->hasAVX2() || !V2IsUndef)
6033     return SDValue();
6034
6035   SmallVector<SDValue,32> pshufbMask;
6036   for (unsigned i = 0; i != 32; i++) {
6037     int EltIdx = MaskVals[i];
6038     if (EltIdx < 0 || EltIdx >= 32)
6039       EltIdx = 0x80;
6040     else {
6041       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6042         // Cross lane is not allowed.
6043         return SDValue();
6044       EltIdx &= 0xf;
6045     }
6046     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6047   }
6048   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6049                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6050                                   MVT::v32i8, &pshufbMask[0], 32));
6051 }
6052
6053 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6054 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6055 /// done when every pair / quad of shuffle mask elements point to elements in
6056 /// the right sequence. e.g.
6057 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6058 static
6059 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6060                                  SelectionDAG &DAG, DebugLoc dl) {
6061   MVT VT = SVOp->getValueType(0).getSimpleVT();
6062   unsigned NumElems = VT.getVectorNumElements();
6063   MVT NewVT;
6064   unsigned Scale;
6065   switch (VT.SimpleTy) {
6066   default: llvm_unreachable("Unexpected!");
6067   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6068   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6069   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6070   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6071   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6072   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6073   }
6074
6075   SmallVector<int, 8> MaskVec;
6076   for (unsigned i = 0; i != NumElems; i += Scale) {
6077     int StartIdx = -1;
6078     for (unsigned j = 0; j != Scale; ++j) {
6079       int EltIdx = SVOp->getMaskElt(i+j);
6080       if (EltIdx < 0)
6081         continue;
6082       if (StartIdx < 0)
6083         StartIdx = (EltIdx / Scale);
6084       if (EltIdx != (int)(StartIdx*Scale + j))
6085         return SDValue();
6086     }
6087     MaskVec.push_back(StartIdx);
6088   }
6089
6090   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6091   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6092   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6093 }
6094
6095 /// getVZextMovL - Return a zero-extending vector move low node.
6096 ///
6097 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6098                             SDValue SrcOp, SelectionDAG &DAG,
6099                             const X86Subtarget *Subtarget, DebugLoc dl) {
6100   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6101     LoadSDNode *LD = NULL;
6102     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6103       LD = dyn_cast<LoadSDNode>(SrcOp);
6104     if (!LD) {
6105       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6106       // instead.
6107       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6108       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6109           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6110           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6111           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6112         // PR2108
6113         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6114         return DAG.getNode(ISD::BITCAST, dl, VT,
6115                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6116                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6117                                                    OpVT,
6118                                                    SrcOp.getOperand(0)
6119                                                           .getOperand(0))));
6120       }
6121     }
6122   }
6123
6124   return DAG.getNode(ISD::BITCAST, dl, VT,
6125                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6126                                  DAG.getNode(ISD::BITCAST, dl,
6127                                              OpVT, SrcOp)));
6128 }
6129
6130 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6131 /// which could not be matched by any known target speficic shuffle
6132 static SDValue
6133 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6134
6135   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6136   if (NewOp.getNode())
6137     return NewOp;
6138
6139   EVT VT = SVOp->getValueType(0);
6140
6141   unsigned NumElems = VT.getVectorNumElements();
6142   unsigned NumLaneElems = NumElems / 2;
6143
6144   DebugLoc dl = SVOp->getDebugLoc();
6145   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6146   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6147   SDValue Output[2];
6148
6149   SmallVector<int, 16> Mask;
6150   for (unsigned l = 0; l < 2; ++l) {
6151     // Build a shuffle mask for the output, discovering on the fly which
6152     // input vectors to use as shuffle operands (recorded in InputUsed).
6153     // If building a suitable shuffle vector proves too hard, then bail
6154     // out with UseBuildVector set.
6155     bool UseBuildVector = false;
6156     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6157     unsigned LaneStart = l * NumLaneElems;
6158     for (unsigned i = 0; i != NumLaneElems; ++i) {
6159       // The mask element.  This indexes into the input.
6160       int Idx = SVOp->getMaskElt(i+LaneStart);
6161       if (Idx < 0) {
6162         // the mask element does not index into any input vector.
6163         Mask.push_back(-1);
6164         continue;
6165       }
6166
6167       // The input vector this mask element indexes into.
6168       int Input = Idx / NumLaneElems;
6169
6170       // Turn the index into an offset from the start of the input vector.
6171       Idx -= Input * NumLaneElems;
6172
6173       // Find or create a shuffle vector operand to hold this input.
6174       unsigned OpNo;
6175       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6176         if (InputUsed[OpNo] == Input)
6177           // This input vector is already an operand.
6178           break;
6179         if (InputUsed[OpNo] < 0) {
6180           // Create a new operand for this input vector.
6181           InputUsed[OpNo] = Input;
6182           break;
6183         }
6184       }
6185
6186       if (OpNo >= array_lengthof(InputUsed)) {
6187         // More than two input vectors used!  Give up on trying to create a
6188         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6189         UseBuildVector = true;
6190         break;
6191       }
6192
6193       // Add the mask index for the new shuffle vector.
6194       Mask.push_back(Idx + OpNo * NumLaneElems);
6195     }
6196
6197     if (UseBuildVector) {
6198       SmallVector<SDValue, 16> SVOps;
6199       for (unsigned i = 0; i != NumLaneElems; ++i) {
6200         // The mask element.  This indexes into the input.
6201         int Idx = SVOp->getMaskElt(i+LaneStart);
6202         if (Idx < 0) {
6203           SVOps.push_back(DAG.getUNDEF(EltVT));
6204           continue;
6205         }
6206
6207         // The input vector this mask element indexes into.
6208         int Input = Idx / NumElems;
6209
6210         // Turn the index into an offset from the start of the input vector.
6211         Idx -= Input * NumElems;
6212
6213         // Extract the vector element by hand.
6214         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6215                                     SVOp->getOperand(Input),
6216                                     DAG.getIntPtrConstant(Idx)));
6217       }
6218
6219       // Construct the output using a BUILD_VECTOR.
6220       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6221                               SVOps.size());
6222     } else if (InputUsed[0] < 0) {
6223       // No input vectors were used! The result is undefined.
6224       Output[l] = DAG.getUNDEF(NVT);
6225     } else {
6226       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6227                                         (InputUsed[0] % 2) * NumLaneElems,
6228                                         DAG, dl);
6229       // If only one input was used, use an undefined vector for the other.
6230       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6231         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6232                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6233       // At least one input vector was used. Create a new shuffle vector.
6234       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6235     }
6236
6237     Mask.clear();
6238   }
6239
6240   // Concatenate the result back
6241   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6242 }
6243
6244 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6245 /// 4 elements, and match them with several different shuffle types.
6246 static SDValue
6247 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6248   SDValue V1 = SVOp->getOperand(0);
6249   SDValue V2 = SVOp->getOperand(1);
6250   DebugLoc dl = SVOp->getDebugLoc();
6251   EVT VT = SVOp->getValueType(0);
6252
6253   assert(VT.is128BitVector() && "Unsupported vector size");
6254
6255   std::pair<int, int> Locs[4];
6256   int Mask1[] = { -1, -1, -1, -1 };
6257   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6258
6259   unsigned NumHi = 0;
6260   unsigned NumLo = 0;
6261   for (unsigned i = 0; i != 4; ++i) {
6262     int Idx = PermMask[i];
6263     if (Idx < 0) {
6264       Locs[i] = std::make_pair(-1, -1);
6265     } else {
6266       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6267       if (Idx < 4) {
6268         Locs[i] = std::make_pair(0, NumLo);
6269         Mask1[NumLo] = Idx;
6270         NumLo++;
6271       } else {
6272         Locs[i] = std::make_pair(1, NumHi);
6273         if (2+NumHi < 4)
6274           Mask1[2+NumHi] = Idx;
6275         NumHi++;
6276       }
6277     }
6278   }
6279
6280   if (NumLo <= 2 && NumHi <= 2) {
6281     // If no more than two elements come from either vector. This can be
6282     // implemented with two shuffles. First shuffle gather the elements.
6283     // The second shuffle, which takes the first shuffle as both of its
6284     // vector operands, put the elements into the right order.
6285     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6286
6287     int Mask2[] = { -1, -1, -1, -1 };
6288
6289     for (unsigned i = 0; i != 4; ++i)
6290       if (Locs[i].first != -1) {
6291         unsigned Idx = (i < 2) ? 0 : 4;
6292         Idx += Locs[i].first * 2 + Locs[i].second;
6293         Mask2[i] = Idx;
6294       }
6295
6296     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6297   }
6298
6299   if (NumLo == 3 || NumHi == 3) {
6300     // Otherwise, we must have three elements from one vector, call it X, and
6301     // one element from the other, call it Y.  First, use a shufps to build an
6302     // intermediate vector with the one element from Y and the element from X
6303     // that will be in the same half in the final destination (the indexes don't
6304     // matter). Then, use a shufps to build the final vector, taking the half
6305     // containing the element from Y from the intermediate, and the other half
6306     // from X.
6307     if (NumHi == 3) {
6308       // Normalize it so the 3 elements come from V1.
6309       CommuteVectorShuffleMask(PermMask, 4);
6310       std::swap(V1, V2);
6311     }
6312
6313     // Find the element from V2.
6314     unsigned HiIndex;
6315     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6316       int Val = PermMask[HiIndex];
6317       if (Val < 0)
6318         continue;
6319       if (Val >= 4)
6320         break;
6321     }
6322
6323     Mask1[0] = PermMask[HiIndex];
6324     Mask1[1] = -1;
6325     Mask1[2] = PermMask[HiIndex^1];
6326     Mask1[3] = -1;
6327     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6328
6329     if (HiIndex >= 2) {
6330       Mask1[0] = PermMask[0];
6331       Mask1[1] = PermMask[1];
6332       Mask1[2] = HiIndex & 1 ? 6 : 4;
6333       Mask1[3] = HiIndex & 1 ? 4 : 6;
6334       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6335     }
6336
6337     Mask1[0] = HiIndex & 1 ? 2 : 0;
6338     Mask1[1] = HiIndex & 1 ? 0 : 2;
6339     Mask1[2] = PermMask[2];
6340     Mask1[3] = PermMask[3];
6341     if (Mask1[2] >= 0)
6342       Mask1[2] += 4;
6343     if (Mask1[3] >= 0)
6344       Mask1[3] += 4;
6345     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6346   }
6347
6348   // Break it into (shuffle shuffle_hi, shuffle_lo).
6349   int LoMask[] = { -1, -1, -1, -1 };
6350   int HiMask[] = { -1, -1, -1, -1 };
6351
6352   int *MaskPtr = LoMask;
6353   unsigned MaskIdx = 0;
6354   unsigned LoIdx = 0;
6355   unsigned HiIdx = 2;
6356   for (unsigned i = 0; i != 4; ++i) {
6357     if (i == 2) {
6358       MaskPtr = HiMask;
6359       MaskIdx = 1;
6360       LoIdx = 0;
6361       HiIdx = 2;
6362     }
6363     int Idx = PermMask[i];
6364     if (Idx < 0) {
6365       Locs[i] = std::make_pair(-1, -1);
6366     } else if (Idx < 4) {
6367       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6368       MaskPtr[LoIdx] = Idx;
6369       LoIdx++;
6370     } else {
6371       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6372       MaskPtr[HiIdx] = Idx;
6373       HiIdx++;
6374     }
6375   }
6376
6377   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6378   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6379   int MaskOps[] = { -1, -1, -1, -1 };
6380   for (unsigned i = 0; i != 4; ++i)
6381     if (Locs[i].first != -1)
6382       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6383   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6384 }
6385
6386 static bool MayFoldVectorLoad(SDValue V) {
6387   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6388     V = V.getOperand(0);
6389   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6390     V = V.getOperand(0);
6391   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6392       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6393     // BUILD_VECTOR (load), undef
6394     V = V.getOperand(0);
6395   if (MayFoldLoad(V))
6396     return true;
6397   return false;
6398 }
6399
6400 // FIXME: the version above should always be used. Since there's
6401 // a bug where several vector shuffles can't be folded because the
6402 // DAG is not updated during lowering and a node claims to have two
6403 // uses while it only has one, use this version, and let isel match
6404 // another instruction if the load really happens to have more than
6405 // one use. Remove this version after this bug get fixed.
6406 // rdar://8434668, PR8156
6407 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6408   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6409     V = V.getOperand(0);
6410   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6411     V = V.getOperand(0);
6412   if (ISD::isNormalLoad(V.getNode()))
6413     return true;
6414   return false;
6415 }
6416
6417 static
6418 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6419   EVT VT = Op.getValueType();
6420
6421   // Canonizalize to v2f64.
6422   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6423   return DAG.getNode(ISD::BITCAST, dl, VT,
6424                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6425                                           V1, DAG));
6426 }
6427
6428 static
6429 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6430                         bool HasSSE2) {
6431   SDValue V1 = Op.getOperand(0);
6432   SDValue V2 = Op.getOperand(1);
6433   EVT VT = Op.getValueType();
6434
6435   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6436
6437   if (HasSSE2 && VT == MVT::v2f64)
6438     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6439
6440   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6441   return DAG.getNode(ISD::BITCAST, dl, VT,
6442                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6443                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6444                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6445 }
6446
6447 static
6448 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6449   SDValue V1 = Op.getOperand(0);
6450   SDValue V2 = Op.getOperand(1);
6451   EVT VT = Op.getValueType();
6452
6453   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6454          "unsupported shuffle type");
6455
6456   if (V2.getOpcode() == ISD::UNDEF)
6457     V2 = V1;
6458
6459   // v4i32 or v4f32
6460   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6461 }
6462
6463 static
6464 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6465   SDValue V1 = Op.getOperand(0);
6466   SDValue V2 = Op.getOperand(1);
6467   EVT VT = Op.getValueType();
6468   unsigned NumElems = VT.getVectorNumElements();
6469
6470   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6471   // operand of these instructions is only memory, so check if there's a
6472   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6473   // same masks.
6474   bool CanFoldLoad = false;
6475
6476   // Trivial case, when V2 comes from a load.
6477   if (MayFoldVectorLoad(V2))
6478     CanFoldLoad = true;
6479
6480   // When V1 is a load, it can be folded later into a store in isel, example:
6481   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6482   //    turns into:
6483   //  (MOVLPSmr addr:$src1, VR128:$src2)
6484   // So, recognize this potential and also use MOVLPS or MOVLPD
6485   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6486     CanFoldLoad = true;
6487
6488   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6489   if (CanFoldLoad) {
6490     if (HasSSE2 && NumElems == 2)
6491       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6492
6493     if (NumElems == 4)
6494       // If we don't care about the second element, proceed to use movss.
6495       if (SVOp->getMaskElt(1) != -1)
6496         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6497   }
6498
6499   // movl and movlp will both match v2i64, but v2i64 is never matched by
6500   // movl earlier because we make it strict to avoid messing with the movlp load
6501   // folding logic (see the code above getMOVLP call). Match it here then,
6502   // this is horrible, but will stay like this until we move all shuffle
6503   // matching to x86 specific nodes. Note that for the 1st condition all
6504   // types are matched with movsd.
6505   if (HasSSE2) {
6506     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6507     // as to remove this logic from here, as much as possible
6508     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6509       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6510     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6511   }
6512
6513   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6514
6515   // Invert the operand order and use SHUFPS to match it.
6516   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6517                               getShuffleSHUFImmediate(SVOp), DAG);
6518 }
6519
6520 SDValue
6521 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6522   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6523   EVT VT = Op.getValueType();
6524   DebugLoc dl = Op.getDebugLoc();
6525   SDValue V1 = Op.getOperand(0);
6526   SDValue V2 = Op.getOperand(1);
6527
6528   if (isZeroShuffle(SVOp))
6529     return getZeroVector(VT, Subtarget, DAG, dl);
6530
6531   // Handle splat operations
6532   if (SVOp->isSplat()) {
6533     unsigned NumElem = VT.getVectorNumElements();
6534     int Size = VT.getSizeInBits();
6535
6536     // Use vbroadcast whenever the splat comes from a foldable load
6537     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6538     if (Broadcast.getNode())
6539       return Broadcast;
6540
6541     // Handle splats by matching through known shuffle masks
6542     if ((Size == 128 && NumElem <= 4) ||
6543         (Size == 256 && NumElem < 8))
6544       return SDValue();
6545
6546     // All remaning splats are promoted to target supported vector shuffles.
6547     return PromoteSplat(SVOp, DAG);
6548   }
6549
6550   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6551   // do it!
6552   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6553       VT == MVT::v16i16 || VT == MVT::v32i8) {
6554     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6555     if (NewOp.getNode())
6556       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6557   } else if ((VT == MVT::v4i32 ||
6558              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6559     // FIXME: Figure out a cleaner way to do this.
6560     // Try to make use of movq to zero out the top part.
6561     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6562       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6563       if (NewOp.getNode()) {
6564         EVT NewVT = NewOp.getValueType();
6565         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6566                                NewVT, true, false))
6567           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6568                               DAG, Subtarget, dl);
6569       }
6570     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6571       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6572       if (NewOp.getNode()) {
6573         EVT NewVT = NewOp.getValueType();
6574         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6575           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6576                               DAG, Subtarget, dl);
6577       }
6578     }
6579   }
6580   return SDValue();
6581 }
6582
6583 SDValue
6584 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6585   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6586   SDValue V1 = Op.getOperand(0);
6587   SDValue V2 = Op.getOperand(1);
6588   EVT VT = Op.getValueType();
6589   DebugLoc dl = Op.getDebugLoc();
6590   unsigned NumElems = VT.getVectorNumElements();
6591   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6592   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6593   bool V1IsSplat = false;
6594   bool V2IsSplat = false;
6595   bool HasSSE2 = Subtarget->hasSSE2();
6596   bool HasAVX    = Subtarget->hasAVX();
6597   bool HasAVX2   = Subtarget->hasAVX2();
6598   MachineFunction &MF = DAG.getMachineFunction();
6599   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6600
6601   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6602
6603   if (V1IsUndef && V2IsUndef)
6604     return DAG.getUNDEF(VT);
6605
6606   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6607
6608   // Vector shuffle lowering takes 3 steps:
6609   //
6610   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6611   //    narrowing and commutation of operands should be handled.
6612   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6613   //    shuffle nodes.
6614   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6615   //    so the shuffle can be broken into other shuffles and the legalizer can
6616   //    try the lowering again.
6617   //
6618   // The general idea is that no vector_shuffle operation should be left to
6619   // be matched during isel, all of them must be converted to a target specific
6620   // node here.
6621
6622   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6623   // narrowing and commutation of operands should be handled. The actual code
6624   // doesn't include all of those, work in progress...
6625   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6626   if (NewOp.getNode())
6627     return NewOp;
6628
6629   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6630
6631   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6632   // unpckh_undef). Only use pshufd if speed is more important than size.
6633   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6634     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6635   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6636     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6637
6638   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6639       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6640     return getMOVDDup(Op, dl, V1, DAG);
6641
6642   if (isMOVHLPS_v_undef_Mask(M, VT))
6643     return getMOVHighToLow(Op, dl, DAG);
6644
6645   // Use to match splats
6646   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6647       (VT == MVT::v2f64 || VT == MVT::v2i64))
6648     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6649
6650   if (isPSHUFDMask(M, VT)) {
6651     // The actual implementation will match the mask in the if above and then
6652     // during isel it can match several different instructions, not only pshufd
6653     // as its name says, sad but true, emulate the behavior for now...
6654     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6655       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6656
6657     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6658
6659     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6660       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6661
6662     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6663       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6664
6665     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6666                                 TargetMask, DAG);
6667   }
6668
6669   // Check if this can be converted into a logical shift.
6670   bool isLeft = false;
6671   unsigned ShAmt = 0;
6672   SDValue ShVal;
6673   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6674   if (isShift && ShVal.hasOneUse()) {
6675     // If the shifted value has multiple uses, it may be cheaper to use
6676     // v_set0 + movlhps or movhlps, etc.
6677     EVT EltVT = VT.getVectorElementType();
6678     ShAmt *= EltVT.getSizeInBits();
6679     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6680   }
6681
6682   if (isMOVLMask(M, VT)) {
6683     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6684       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6685     if (!isMOVLPMask(M, VT)) {
6686       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6687         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6688
6689       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6690         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6691     }
6692   }
6693
6694   // FIXME: fold these into legal mask.
6695   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6696     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6697
6698   if (isMOVHLPSMask(M, VT))
6699     return getMOVHighToLow(Op, dl, DAG);
6700
6701   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6702     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6703
6704   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6705     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6706
6707   if (isMOVLPMask(M, VT))
6708     return getMOVLP(Op, dl, DAG, HasSSE2);
6709
6710   if (ShouldXformToMOVHLPS(M, VT) ||
6711       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6712     return CommuteVectorShuffle(SVOp, DAG);
6713
6714   if (isShift) {
6715     // No better options. Use a vshldq / vsrldq.
6716     EVT EltVT = VT.getVectorElementType();
6717     ShAmt *= EltVT.getSizeInBits();
6718     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6719   }
6720
6721   bool Commuted = false;
6722   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6723   // 1,1,1,1 -> v8i16 though.
6724   V1IsSplat = isSplatVector(V1.getNode());
6725   V2IsSplat = isSplatVector(V2.getNode());
6726
6727   // Canonicalize the splat or undef, if present, to be on the RHS.
6728   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6729     CommuteVectorShuffleMask(M, NumElems);
6730     std::swap(V1, V2);
6731     std::swap(V1IsSplat, V2IsSplat);
6732     Commuted = true;
6733   }
6734
6735   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6736     // Shuffling low element of v1 into undef, just return v1.
6737     if (V2IsUndef)
6738       return V1;
6739     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6740     // the instruction selector will not match, so get a canonical MOVL with
6741     // swapped operands to undo the commute.
6742     return getMOVL(DAG, dl, VT, V2, V1);
6743   }
6744
6745   if (isUNPCKLMask(M, VT, HasAVX2))
6746     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6747
6748   if (isUNPCKHMask(M, VT, HasAVX2))
6749     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6750
6751   if (V2IsSplat) {
6752     // Normalize mask so all entries that point to V2 points to its first
6753     // element then try to match unpck{h|l} again. If match, return a
6754     // new vector_shuffle with the corrected mask.p
6755     SmallVector<int, 8> NewMask(M.begin(), M.end());
6756     NormalizeMask(NewMask, NumElems);
6757     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6758       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6759     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6760       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6761   }
6762
6763   if (Commuted) {
6764     // Commute is back and try unpck* again.
6765     // FIXME: this seems wrong.
6766     CommuteVectorShuffleMask(M, NumElems);
6767     std::swap(V1, V2);
6768     std::swap(V1IsSplat, V2IsSplat);
6769     Commuted = false;
6770
6771     if (isUNPCKLMask(M, VT, HasAVX2))
6772       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6773
6774     if (isUNPCKHMask(M, VT, HasAVX2))
6775       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6776   }
6777
6778   // Normalize the node to match x86 shuffle ops if needed
6779   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6780     return CommuteVectorShuffle(SVOp, DAG);
6781
6782   // The checks below are all present in isShuffleMaskLegal, but they are
6783   // inlined here right now to enable us to directly emit target specific
6784   // nodes, and remove one by one until they don't return Op anymore.
6785
6786   if (isPALIGNRMask(M, VT, Subtarget))
6787     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6788                                 getShufflePALIGNRImmediate(SVOp),
6789                                 DAG);
6790
6791   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6792       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6793     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6794       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6795   }
6796
6797   if (isPSHUFHWMask(M, VT, HasAVX2))
6798     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6799                                 getShufflePSHUFHWImmediate(SVOp),
6800                                 DAG);
6801
6802   if (isPSHUFLWMask(M, VT, HasAVX2))
6803     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6804                                 getShufflePSHUFLWImmediate(SVOp),
6805                                 DAG);
6806
6807   if (isSHUFPMask(M, VT, HasAVX))
6808     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6809                                 getShuffleSHUFImmediate(SVOp), DAG);
6810
6811   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6812     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6813   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6814     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6815
6816   //===--------------------------------------------------------------------===//
6817   // Generate target specific nodes for 128 or 256-bit shuffles only
6818   // supported in the AVX instruction set.
6819   //
6820
6821   // Handle VMOVDDUPY permutations
6822   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6823     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6824
6825   // Handle VPERMILPS/D* permutations
6826   if (isVPERMILPMask(M, VT, HasAVX)) {
6827     if (HasAVX2 && VT == MVT::v8i32)
6828       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6829                                   getShuffleSHUFImmediate(SVOp), DAG);
6830     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6831                                 getShuffleSHUFImmediate(SVOp), DAG);
6832   }
6833
6834   // Handle VPERM2F128/VPERM2I128 permutations
6835   if (isVPERM2X128Mask(M, VT, HasAVX))
6836     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6837                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6838
6839   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6840   if (BlendOp.getNode())
6841     return BlendOp;
6842
6843   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6844     SmallVector<SDValue, 8> permclMask;
6845     for (unsigned i = 0; i != 8; ++i) {
6846       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6847     }
6848     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6849                                &permclMask[0], 8);
6850     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6851     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6852                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6853   }
6854
6855   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6856     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6857                                 getShuffleCLImmediate(SVOp), DAG);
6858
6859
6860   //===--------------------------------------------------------------------===//
6861   // Since no target specific shuffle was selected for this generic one,
6862   // lower it into other known shuffles. FIXME: this isn't true yet, but
6863   // this is the plan.
6864   //
6865
6866   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6867   if (VT == MVT::v8i16) {
6868     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6869     if (NewOp.getNode())
6870       return NewOp;
6871   }
6872
6873   if (VT == MVT::v16i8) {
6874     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6875     if (NewOp.getNode())
6876       return NewOp;
6877   }
6878
6879   if (VT == MVT::v32i8) {
6880     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, DAG, *this);
6881     if (NewOp.getNode())
6882       return NewOp;
6883   }
6884
6885   // Handle all 128-bit wide vectors with 4 elements, and match them with
6886   // several different shuffle types.
6887   if (NumElems == 4 && VT.is128BitVector())
6888     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6889
6890   // Handle general 256-bit shuffles
6891   if (VT.is256BitVector())
6892     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6893
6894   return SDValue();
6895 }
6896
6897 SDValue
6898 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6899                                                 SelectionDAG &DAG) const {
6900   EVT VT = Op.getValueType();
6901   DebugLoc dl = Op.getDebugLoc();
6902
6903   if (!Op.getOperand(0).getValueType().is128BitVector())
6904     return SDValue();
6905
6906   if (VT.getSizeInBits() == 8) {
6907     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6908                                     Op.getOperand(0), Op.getOperand(1));
6909     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6910                                     DAG.getValueType(VT));
6911     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6912   }
6913
6914   if (VT.getSizeInBits() == 16) {
6915     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6916     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6917     if (Idx == 0)
6918       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6919                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6920                                      DAG.getNode(ISD::BITCAST, dl,
6921                                                  MVT::v4i32,
6922                                                  Op.getOperand(0)),
6923                                      Op.getOperand(1)));
6924     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6925                                     Op.getOperand(0), Op.getOperand(1));
6926     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6927                                     DAG.getValueType(VT));
6928     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6929   }
6930
6931   if (VT == MVT::f32) {
6932     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6933     // the result back to FR32 register. It's only worth matching if the
6934     // result has a single use which is a store or a bitcast to i32.  And in
6935     // the case of a store, it's not worth it if the index is a constant 0,
6936     // because a MOVSSmr can be used instead, which is smaller and faster.
6937     if (!Op.hasOneUse())
6938       return SDValue();
6939     SDNode *User = *Op.getNode()->use_begin();
6940     if ((User->getOpcode() != ISD::STORE ||
6941          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6942           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6943         (User->getOpcode() != ISD::BITCAST ||
6944          User->getValueType(0) != MVT::i32))
6945       return SDValue();
6946     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6947                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6948                                               Op.getOperand(0)),
6949                                               Op.getOperand(1));
6950     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6951   }
6952
6953   if (VT == MVT::i32 || VT == MVT::i64) {
6954     // ExtractPS/pextrq works with constant index.
6955     if (isa<ConstantSDNode>(Op.getOperand(1)))
6956       return Op;
6957   }
6958   return SDValue();
6959 }
6960
6961
6962 SDValue
6963 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6964                                            SelectionDAG &DAG) const {
6965   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6966     return SDValue();
6967
6968   SDValue Vec = Op.getOperand(0);
6969   EVT VecVT = Vec.getValueType();
6970
6971   // If this is a 256-bit vector result, first extract the 128-bit vector and
6972   // then extract the element from the 128-bit vector.
6973   if (VecVT.is256BitVector()) {
6974     DebugLoc dl = Op.getNode()->getDebugLoc();
6975     unsigned NumElems = VecVT.getVectorNumElements();
6976     SDValue Idx = Op.getOperand(1);
6977     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6978
6979     // Get the 128-bit vector.
6980     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6981
6982     if (IdxVal >= NumElems/2)
6983       IdxVal -= NumElems/2;
6984     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6985                        DAG.getConstant(IdxVal, MVT::i32));
6986   }
6987
6988   assert(VecVT.is128BitVector() && "Unexpected vector length");
6989
6990   if (Subtarget->hasSSE41()) {
6991     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6992     if (Res.getNode())
6993       return Res;
6994   }
6995
6996   EVT VT = Op.getValueType();
6997   DebugLoc dl = Op.getDebugLoc();
6998   // TODO: handle v16i8.
6999   if (VT.getSizeInBits() == 16) {
7000     SDValue Vec = Op.getOperand(0);
7001     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7002     if (Idx == 0)
7003       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7004                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7005                                      DAG.getNode(ISD::BITCAST, dl,
7006                                                  MVT::v4i32, Vec),
7007                                      Op.getOperand(1)));
7008     // Transform it so it match pextrw which produces a 32-bit result.
7009     EVT EltVT = MVT::i32;
7010     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7011                                     Op.getOperand(0), Op.getOperand(1));
7012     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7013                                     DAG.getValueType(VT));
7014     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7015   }
7016
7017   if (VT.getSizeInBits() == 32) {
7018     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7019     if (Idx == 0)
7020       return Op;
7021
7022     // SHUFPS the element to the lowest double word, then movss.
7023     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7024     EVT VVT = Op.getOperand(0).getValueType();
7025     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7026                                        DAG.getUNDEF(VVT), Mask);
7027     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7028                        DAG.getIntPtrConstant(0));
7029   }
7030
7031   if (VT.getSizeInBits() == 64) {
7032     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7033     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7034     //        to match extract_elt for f64.
7035     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7036     if (Idx == 0)
7037       return Op;
7038
7039     // UNPCKHPD the element to the lowest double word, then movsd.
7040     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7041     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7042     int Mask[2] = { 1, -1 };
7043     EVT VVT = Op.getOperand(0).getValueType();
7044     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7045                                        DAG.getUNDEF(VVT), Mask);
7046     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7047                        DAG.getIntPtrConstant(0));
7048   }
7049
7050   return SDValue();
7051 }
7052
7053 SDValue
7054 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7055                                                SelectionDAG &DAG) const {
7056   EVT VT = Op.getValueType();
7057   EVT EltVT = VT.getVectorElementType();
7058   DebugLoc dl = Op.getDebugLoc();
7059
7060   SDValue N0 = Op.getOperand(0);
7061   SDValue N1 = Op.getOperand(1);
7062   SDValue N2 = Op.getOperand(2);
7063
7064   if (!VT.is128BitVector())
7065     return SDValue();
7066
7067   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7068       isa<ConstantSDNode>(N2)) {
7069     unsigned Opc;
7070     if (VT == MVT::v8i16)
7071       Opc = X86ISD::PINSRW;
7072     else if (VT == MVT::v16i8)
7073       Opc = X86ISD::PINSRB;
7074     else
7075       Opc = X86ISD::PINSRB;
7076
7077     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7078     // argument.
7079     if (N1.getValueType() != MVT::i32)
7080       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7081     if (N2.getValueType() != MVT::i32)
7082       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7083     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7084   }
7085
7086   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7087     // Bits [7:6] of the constant are the source select.  This will always be
7088     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7089     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7090     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7091     // Bits [5:4] of the constant are the destination select.  This is the
7092     //  value of the incoming immediate.
7093     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7094     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7095     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7096     // Create this as a scalar to vector..
7097     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7098     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7099   }
7100
7101   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7102     // PINSR* works with constant index.
7103     return Op;
7104   }
7105   return SDValue();
7106 }
7107
7108 SDValue
7109 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7110   EVT VT = Op.getValueType();
7111   EVT EltVT = VT.getVectorElementType();
7112
7113   DebugLoc dl = Op.getDebugLoc();
7114   SDValue N0 = Op.getOperand(0);
7115   SDValue N1 = Op.getOperand(1);
7116   SDValue N2 = Op.getOperand(2);
7117
7118   // If this is a 256-bit vector result, first extract the 128-bit vector,
7119   // insert the element into the extracted half and then place it back.
7120   if (VT.is256BitVector()) {
7121     if (!isa<ConstantSDNode>(N2))
7122       return SDValue();
7123
7124     // Get the desired 128-bit vector half.
7125     unsigned NumElems = VT.getVectorNumElements();
7126     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7127     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7128
7129     // Insert the element into the desired half.
7130     bool Upper = IdxVal >= NumElems/2;
7131     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7132                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7133
7134     // Insert the changed part back to the 256-bit vector
7135     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7136   }
7137
7138   if (Subtarget->hasSSE41())
7139     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7140
7141   if (EltVT == MVT::i8)
7142     return SDValue();
7143
7144   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7145     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7146     // as its second argument.
7147     if (N1.getValueType() != MVT::i32)
7148       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7149     if (N2.getValueType() != MVT::i32)
7150       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7151     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7152   }
7153   return SDValue();
7154 }
7155
7156 SDValue
7157 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7158   LLVMContext *Context = DAG.getContext();
7159   DebugLoc dl = Op.getDebugLoc();
7160   EVT OpVT = Op.getValueType();
7161
7162   // If this is a 256-bit vector result, first insert into a 128-bit
7163   // vector and then insert into the 256-bit vector.
7164   if (!OpVT.is128BitVector()) {
7165     // Insert into a 128-bit vector.
7166     EVT VT128 = EVT::getVectorVT(*Context,
7167                                  OpVT.getVectorElementType(),
7168                                  OpVT.getVectorNumElements() / 2);
7169
7170     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7171
7172     // Insert the 128-bit vector.
7173     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7174   }
7175
7176   if (OpVT == MVT::v1i64 &&
7177       Op.getOperand(0).getValueType() == MVT::i64)
7178     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7179
7180   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7181   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7182   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7183                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7184 }
7185
7186 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7187 // a simple subregister reference or explicit instructions to grab
7188 // upper bits of a vector.
7189 SDValue
7190 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7191   if (Subtarget->hasAVX()) {
7192     DebugLoc dl = Op.getNode()->getDebugLoc();
7193     SDValue Vec = Op.getNode()->getOperand(0);
7194     SDValue Idx = Op.getNode()->getOperand(1);
7195
7196     if (Op.getNode()->getValueType(0).is128BitVector() &&
7197         Vec.getNode()->getValueType(0).is256BitVector() &&
7198         isa<ConstantSDNode>(Idx)) {
7199       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7200       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7201     }
7202   }
7203   return SDValue();
7204 }
7205
7206 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7207 // simple superregister reference or explicit instructions to insert
7208 // the upper bits of a vector.
7209 SDValue
7210 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7211   if (Subtarget->hasAVX()) {
7212     DebugLoc dl = Op.getNode()->getDebugLoc();
7213     SDValue Vec = Op.getNode()->getOperand(0);
7214     SDValue SubVec = Op.getNode()->getOperand(1);
7215     SDValue Idx = Op.getNode()->getOperand(2);
7216
7217     if (Op.getNode()->getValueType(0).is256BitVector() &&
7218         SubVec.getNode()->getValueType(0).is128BitVector() &&
7219         isa<ConstantSDNode>(Idx)) {
7220       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7221       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7222     }
7223   }
7224   return SDValue();
7225 }
7226
7227 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7228 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7229 // one of the above mentioned nodes. It has to be wrapped because otherwise
7230 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7231 // be used to form addressing mode. These wrapped nodes will be selected
7232 // into MOV32ri.
7233 SDValue
7234 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7235   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7236
7237   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7238   // global base reg.
7239   unsigned char OpFlag = 0;
7240   unsigned WrapperKind = X86ISD::Wrapper;
7241   CodeModel::Model M = getTargetMachine().getCodeModel();
7242
7243   if (Subtarget->isPICStyleRIPRel() &&
7244       (M == CodeModel::Small || M == CodeModel::Kernel))
7245     WrapperKind = X86ISD::WrapperRIP;
7246   else if (Subtarget->isPICStyleGOT())
7247     OpFlag = X86II::MO_GOTOFF;
7248   else if (Subtarget->isPICStyleStubPIC())
7249     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7250
7251   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7252                                              CP->getAlignment(),
7253                                              CP->getOffset(), OpFlag);
7254   DebugLoc DL = CP->getDebugLoc();
7255   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7256   // With PIC, the address is actually $g + Offset.
7257   if (OpFlag) {
7258     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7259                          DAG.getNode(X86ISD::GlobalBaseReg,
7260                                      DebugLoc(), getPointerTy()),
7261                          Result);
7262   }
7263
7264   return Result;
7265 }
7266
7267 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7268   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7269
7270   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7271   // global base reg.
7272   unsigned char OpFlag = 0;
7273   unsigned WrapperKind = X86ISD::Wrapper;
7274   CodeModel::Model M = getTargetMachine().getCodeModel();
7275
7276   if (Subtarget->isPICStyleRIPRel() &&
7277       (M == CodeModel::Small || M == CodeModel::Kernel))
7278     WrapperKind = X86ISD::WrapperRIP;
7279   else if (Subtarget->isPICStyleGOT())
7280     OpFlag = X86II::MO_GOTOFF;
7281   else if (Subtarget->isPICStyleStubPIC())
7282     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7283
7284   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7285                                           OpFlag);
7286   DebugLoc DL = JT->getDebugLoc();
7287   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7288
7289   // With PIC, the address is actually $g + Offset.
7290   if (OpFlag)
7291     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7292                          DAG.getNode(X86ISD::GlobalBaseReg,
7293                                      DebugLoc(), getPointerTy()),
7294                          Result);
7295
7296   return Result;
7297 }
7298
7299 SDValue
7300 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7301   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7302
7303   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7304   // global base reg.
7305   unsigned char OpFlag = 0;
7306   unsigned WrapperKind = X86ISD::Wrapper;
7307   CodeModel::Model M = getTargetMachine().getCodeModel();
7308
7309   if (Subtarget->isPICStyleRIPRel() &&
7310       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7311     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7312       OpFlag = X86II::MO_GOTPCREL;
7313     WrapperKind = X86ISD::WrapperRIP;
7314   } else if (Subtarget->isPICStyleGOT()) {
7315     OpFlag = X86II::MO_GOT;
7316   } else if (Subtarget->isPICStyleStubPIC()) {
7317     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7318   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7319     OpFlag = X86II::MO_DARWIN_NONLAZY;
7320   }
7321
7322   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7323
7324   DebugLoc DL = Op.getDebugLoc();
7325   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7326
7327
7328   // With PIC, the address is actually $g + Offset.
7329   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7330       !Subtarget->is64Bit()) {
7331     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7332                          DAG.getNode(X86ISD::GlobalBaseReg,
7333                                      DebugLoc(), getPointerTy()),
7334                          Result);
7335   }
7336
7337   // For symbols that require a load from a stub to get the address, emit the
7338   // load.
7339   if (isGlobalStubReference(OpFlag))
7340     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7341                          MachinePointerInfo::getGOT(), false, false, false, 0);
7342
7343   return Result;
7344 }
7345
7346 SDValue
7347 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7348   // Create the TargetBlockAddressAddress node.
7349   unsigned char OpFlags =
7350     Subtarget->ClassifyBlockAddressReference();
7351   CodeModel::Model M = getTargetMachine().getCodeModel();
7352   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7353   DebugLoc dl = Op.getDebugLoc();
7354   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7355                                        /*isTarget=*/true, OpFlags);
7356
7357   if (Subtarget->isPICStyleRIPRel() &&
7358       (M == CodeModel::Small || M == CodeModel::Kernel))
7359     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7360   else
7361     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7362
7363   // With PIC, the address is actually $g + Offset.
7364   if (isGlobalRelativeToPICBase(OpFlags)) {
7365     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7366                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7367                          Result);
7368   }
7369
7370   return Result;
7371 }
7372
7373 SDValue
7374 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7375                                       int64_t Offset,
7376                                       SelectionDAG &DAG) const {
7377   // Create the TargetGlobalAddress node, folding in the constant
7378   // offset if it is legal.
7379   unsigned char OpFlags =
7380     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7381   CodeModel::Model M = getTargetMachine().getCodeModel();
7382   SDValue Result;
7383   if (OpFlags == X86II::MO_NO_FLAG &&
7384       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7385     // A direct static reference to a global.
7386     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7387     Offset = 0;
7388   } else {
7389     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7390   }
7391
7392   if (Subtarget->isPICStyleRIPRel() &&
7393       (M == CodeModel::Small || M == CodeModel::Kernel))
7394     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7395   else
7396     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7397
7398   // With PIC, the address is actually $g + Offset.
7399   if (isGlobalRelativeToPICBase(OpFlags)) {
7400     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7401                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7402                          Result);
7403   }
7404
7405   // For globals that require a load from a stub to get the address, emit the
7406   // load.
7407   if (isGlobalStubReference(OpFlags))
7408     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7409                          MachinePointerInfo::getGOT(), false, false, false, 0);
7410
7411   // If there was a non-zero offset that we didn't fold, create an explicit
7412   // addition for it.
7413   if (Offset != 0)
7414     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7415                          DAG.getConstant(Offset, getPointerTy()));
7416
7417   return Result;
7418 }
7419
7420 SDValue
7421 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7422   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7423   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7424   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7425 }
7426
7427 static SDValue
7428 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7429            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7430            unsigned char OperandFlags, bool LocalDynamic = false) {
7431   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7432   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7433   DebugLoc dl = GA->getDebugLoc();
7434   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7435                                            GA->getValueType(0),
7436                                            GA->getOffset(),
7437                                            OperandFlags);
7438
7439   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7440                                            : X86ISD::TLSADDR;
7441
7442   if (InFlag) {
7443     SDValue Ops[] = { Chain,  TGA, *InFlag };
7444     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7445   } else {
7446     SDValue Ops[]  = { Chain, TGA };
7447     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7448   }
7449
7450   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7451   MFI->setAdjustsStack(true);
7452
7453   SDValue Flag = Chain.getValue(1);
7454   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7455 }
7456
7457 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7458 static SDValue
7459 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7460                                 const EVT PtrVT) {
7461   SDValue InFlag;
7462   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7463   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7464                                      DAG.getNode(X86ISD::GlobalBaseReg,
7465                                                  DebugLoc(), PtrVT), InFlag);
7466   InFlag = Chain.getValue(1);
7467
7468   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7469 }
7470
7471 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7472 static SDValue
7473 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7474                                 const EVT PtrVT) {
7475   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7476                     X86::RAX, X86II::MO_TLSGD);
7477 }
7478
7479 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7480                                            SelectionDAG &DAG,
7481                                            const EVT PtrVT,
7482                                            bool is64Bit) {
7483   DebugLoc dl = GA->getDebugLoc();
7484
7485   // Get the start address of the TLS block for this module.
7486   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7487       .getInfo<X86MachineFunctionInfo>();
7488   MFI->incNumLocalDynamicTLSAccesses();
7489
7490   SDValue Base;
7491   if (is64Bit) {
7492     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7493                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7494   } else {
7495     SDValue InFlag;
7496     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7497         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7498     InFlag = Chain.getValue(1);
7499     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7500                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7501   }
7502
7503   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7504   // of Base.
7505
7506   // Build x@dtpoff.
7507   unsigned char OperandFlags = X86II::MO_DTPOFF;
7508   unsigned WrapperKind = X86ISD::Wrapper;
7509   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7510                                            GA->getValueType(0),
7511                                            GA->getOffset(), OperandFlags);
7512   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7513
7514   // Add x@dtpoff with the base.
7515   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7516 }
7517
7518 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7519 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7520                                    const EVT PtrVT, TLSModel::Model model,
7521                                    bool is64Bit, bool isPIC) {
7522   DebugLoc dl = GA->getDebugLoc();
7523
7524   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7525   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7526                                                          is64Bit ? 257 : 256));
7527
7528   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7529                                       DAG.getIntPtrConstant(0),
7530                                       MachinePointerInfo(Ptr),
7531                                       false, false, false, 0);
7532
7533   unsigned char OperandFlags = 0;
7534   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7535   // initialexec.
7536   unsigned WrapperKind = X86ISD::Wrapper;
7537   if (model == TLSModel::LocalExec) {
7538     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7539   } else if (model == TLSModel::InitialExec) {
7540     if (is64Bit) {
7541       OperandFlags = X86II::MO_GOTTPOFF;
7542       WrapperKind = X86ISD::WrapperRIP;
7543     } else {
7544       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7545     }
7546   } else {
7547     llvm_unreachable("Unexpected model");
7548   }
7549
7550   // emit "addl x@ntpoff,%eax" (local exec)
7551   // or "addl x@indntpoff,%eax" (initial exec)
7552   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7553   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7554                                            GA->getValueType(0),
7555                                            GA->getOffset(), OperandFlags);
7556   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7557
7558   if (model == TLSModel::InitialExec) {
7559     if (isPIC && !is64Bit) {
7560       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7561                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7562                            Offset);
7563     }
7564
7565     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7566                          MachinePointerInfo::getGOT(), false, false, false,
7567                          0);
7568   }
7569
7570   // The address of the thread local variable is the add of the thread
7571   // pointer with the offset of the variable.
7572   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7577
7578   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7579   const GlobalValue *GV = GA->getGlobal();
7580
7581   if (Subtarget->isTargetELF()) {
7582     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7583
7584     switch (model) {
7585       case TLSModel::GeneralDynamic:
7586         if (Subtarget->is64Bit())
7587           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7588         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7589       case TLSModel::LocalDynamic:
7590         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7591                                            Subtarget->is64Bit());
7592       case TLSModel::InitialExec:
7593       case TLSModel::LocalExec:
7594         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7595                                    Subtarget->is64Bit(),
7596                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7597     }
7598     llvm_unreachable("Unknown TLS model.");
7599   }
7600
7601   if (Subtarget->isTargetDarwin()) {
7602     // Darwin only has one model of TLS.  Lower to that.
7603     unsigned char OpFlag = 0;
7604     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7605                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7606
7607     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7608     // global base reg.
7609     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7610                   !Subtarget->is64Bit();
7611     if (PIC32)
7612       OpFlag = X86II::MO_TLVP_PIC_BASE;
7613     else
7614       OpFlag = X86II::MO_TLVP;
7615     DebugLoc DL = Op.getDebugLoc();
7616     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7617                                                 GA->getValueType(0),
7618                                                 GA->getOffset(), OpFlag);
7619     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7620
7621     // With PIC32, the address is actually $g + Offset.
7622     if (PIC32)
7623       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7624                            DAG.getNode(X86ISD::GlobalBaseReg,
7625                                        DebugLoc(), getPointerTy()),
7626                            Offset);
7627
7628     // Lowering the machine isd will make sure everything is in the right
7629     // location.
7630     SDValue Chain = DAG.getEntryNode();
7631     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7632     SDValue Args[] = { Chain, Offset };
7633     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7634
7635     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7636     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7637     MFI->setAdjustsStack(true);
7638
7639     // And our return value (tls address) is in the standard call return value
7640     // location.
7641     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7642     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7643                               Chain.getValue(1));
7644   }
7645
7646   if (Subtarget->isTargetWindows()) {
7647     // Just use the implicit TLS architecture
7648     // Need to generate someting similar to:
7649     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7650     //                                  ; from TEB
7651     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7652     //   mov     rcx, qword [rdx+rcx*8]
7653     //   mov     eax, .tls$:tlsvar
7654     //   [rax+rcx] contains the address
7655     // Windows 64bit: gs:0x58
7656     // Windows 32bit: fs:__tls_array
7657
7658     // If GV is an alias then use the aliasee for determining
7659     // thread-localness.
7660     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7661       GV = GA->resolveAliasedGlobal(false);
7662     DebugLoc dl = GA->getDebugLoc();
7663     SDValue Chain = DAG.getEntryNode();
7664
7665     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7666     // %gs:0x58 (64-bit).
7667     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7668                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7669                                                              256)
7670                                         : Type::getInt32PtrTy(*DAG.getContext(),
7671                                                               257));
7672
7673     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7674                                         Subtarget->is64Bit()
7675                                         ? DAG.getIntPtrConstant(0x58)
7676                                         : DAG.getExternalSymbol("_tls_array",
7677                                                                 getPointerTy()),
7678                                         MachinePointerInfo(Ptr),
7679                                         false, false, false, 0);
7680
7681     // Load the _tls_index variable
7682     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7683     if (Subtarget->is64Bit())
7684       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7685                            IDX, MachinePointerInfo(), MVT::i32,
7686                            false, false, 0);
7687     else
7688       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7689                         false, false, false, 0);
7690
7691     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7692                                     getPointerTy());
7693     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7694
7695     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7696     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7697                       false, false, false, 0);
7698
7699     // Get the offset of start of .tls section
7700     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7701                                              GA->getValueType(0),
7702                                              GA->getOffset(), X86II::MO_SECREL);
7703     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7704
7705     // The address of the thread local variable is the add of the thread
7706     // pointer with the offset of the variable.
7707     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7708   }
7709
7710   llvm_unreachable("TLS not implemented for this target.");
7711 }
7712
7713
7714 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7715 /// and take a 2 x i32 value to shift plus a shift amount.
7716 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7717   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7718   EVT VT = Op.getValueType();
7719   unsigned VTBits = VT.getSizeInBits();
7720   DebugLoc dl = Op.getDebugLoc();
7721   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7722   SDValue ShOpLo = Op.getOperand(0);
7723   SDValue ShOpHi = Op.getOperand(1);
7724   SDValue ShAmt  = Op.getOperand(2);
7725   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7726                                      DAG.getConstant(VTBits - 1, MVT::i8))
7727                        : DAG.getConstant(0, VT);
7728
7729   SDValue Tmp2, Tmp3;
7730   if (Op.getOpcode() == ISD::SHL_PARTS) {
7731     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7732     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7733   } else {
7734     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7735     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7736   }
7737
7738   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7739                                 DAG.getConstant(VTBits, MVT::i8));
7740   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7741                              AndNode, DAG.getConstant(0, MVT::i8));
7742
7743   SDValue Hi, Lo;
7744   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7745   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7746   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7747
7748   if (Op.getOpcode() == ISD::SHL_PARTS) {
7749     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7750     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7751   } else {
7752     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7753     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7754   }
7755
7756   SDValue Ops[2] = { Lo, Hi };
7757   return DAG.getMergeValues(Ops, 2, dl);
7758 }
7759
7760 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7761                                            SelectionDAG &DAG) const {
7762   EVT SrcVT = Op.getOperand(0).getValueType();
7763
7764   if (SrcVT.isVector())
7765     return SDValue();
7766
7767   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7768          "Unknown SINT_TO_FP to lower!");
7769
7770   // These are really Legal; return the operand so the caller accepts it as
7771   // Legal.
7772   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7773     return Op;
7774   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7775       Subtarget->is64Bit()) {
7776     return Op;
7777   }
7778
7779   DebugLoc dl = Op.getDebugLoc();
7780   unsigned Size = SrcVT.getSizeInBits()/8;
7781   MachineFunction &MF = DAG.getMachineFunction();
7782   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7783   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7784   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7785                                StackSlot,
7786                                MachinePointerInfo::getFixedStack(SSFI),
7787                                false, false, 0);
7788   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7789 }
7790
7791 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7792                                      SDValue StackSlot,
7793                                      SelectionDAG &DAG) const {
7794   // Build the FILD
7795   DebugLoc DL = Op.getDebugLoc();
7796   SDVTList Tys;
7797   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7798   if (useSSE)
7799     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7800   else
7801     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7802
7803   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7804
7805   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7806   MachineMemOperand *MMO;
7807   if (FI) {
7808     int SSFI = FI->getIndex();
7809     MMO =
7810       DAG.getMachineFunction()
7811       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7812                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7813   } else {
7814     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7815     StackSlot = StackSlot.getOperand(1);
7816   }
7817   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7818   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7819                                            X86ISD::FILD, DL,
7820                                            Tys, Ops, array_lengthof(Ops),
7821                                            SrcVT, MMO);
7822
7823   if (useSSE) {
7824     Chain = Result.getValue(1);
7825     SDValue InFlag = Result.getValue(2);
7826
7827     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7828     // shouldn't be necessary except that RFP cannot be live across
7829     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7830     MachineFunction &MF = DAG.getMachineFunction();
7831     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7832     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7833     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7834     Tys = DAG.getVTList(MVT::Other);
7835     SDValue Ops[] = {
7836       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7837     };
7838     MachineMemOperand *MMO =
7839       DAG.getMachineFunction()
7840       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7841                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7842
7843     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7844                                     Ops, array_lengthof(Ops),
7845                                     Op.getValueType(), MMO);
7846     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7847                          MachinePointerInfo::getFixedStack(SSFI),
7848                          false, false, false, 0);
7849   }
7850
7851   return Result;
7852 }
7853
7854 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7855 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7856                                                SelectionDAG &DAG) const {
7857   // This algorithm is not obvious. Here it is what we're trying to output:
7858   /*
7859      movq       %rax,  %xmm0
7860      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7861      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7862      #ifdef __SSE3__
7863        haddpd   %xmm0, %xmm0
7864      #else
7865        pshufd   $0x4e, %xmm0, %xmm1
7866        addpd    %xmm1, %xmm0
7867      #endif
7868   */
7869
7870   DebugLoc dl = Op.getDebugLoc();
7871   LLVMContext *Context = DAG.getContext();
7872
7873   // Build some magic constants.
7874   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7875   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7876   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7877
7878   SmallVector<Constant*,2> CV1;
7879   CV1.push_back(
7880         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7881   CV1.push_back(
7882         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7883   Constant *C1 = ConstantVector::get(CV1);
7884   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7885
7886   // Load the 64-bit value into an XMM register.
7887   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7888                             Op.getOperand(0));
7889   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7890                               MachinePointerInfo::getConstantPool(),
7891                               false, false, false, 16);
7892   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7893                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7894                               CLod0);
7895
7896   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7897                               MachinePointerInfo::getConstantPool(),
7898                               false, false, false, 16);
7899   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7900   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7901   SDValue Result;
7902
7903   if (Subtarget->hasSSE3()) {
7904     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7905     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7906   } else {
7907     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7908     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7909                                            S2F, 0x4E, DAG);
7910     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7911                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7912                          Sub);
7913   }
7914
7915   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7916                      DAG.getIntPtrConstant(0));
7917 }
7918
7919 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7920 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7921                                                SelectionDAG &DAG) const {
7922   DebugLoc dl = Op.getDebugLoc();
7923   // FP constant to bias correct the final result.
7924   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7925                                    MVT::f64);
7926
7927   // Load the 32-bit value into an XMM register.
7928   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7929                              Op.getOperand(0));
7930
7931   // Zero out the upper parts of the register.
7932   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7933
7934   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7935                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7936                      DAG.getIntPtrConstant(0));
7937
7938   // Or the load with the bias.
7939   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7940                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7941                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7942                                                    MVT::v2f64, Load)),
7943                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7944                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7945                                                    MVT::v2f64, Bias)));
7946   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7947                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7948                    DAG.getIntPtrConstant(0));
7949
7950   // Subtract the bias.
7951   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7952
7953   // Handle final rounding.
7954   EVT DestVT = Op.getValueType();
7955
7956   if (DestVT.bitsLT(MVT::f64))
7957     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7958                        DAG.getIntPtrConstant(0));
7959   if (DestVT.bitsGT(MVT::f64))
7960     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7961
7962   // Handle final rounding.
7963   return Sub;
7964 }
7965
7966 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7967                                            SelectionDAG &DAG) const {
7968   SDValue N0 = Op.getOperand(0);
7969   DebugLoc dl = Op.getDebugLoc();
7970
7971   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7972   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7973   // the optimization here.
7974   if (DAG.SignBitIsZero(N0))
7975     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7976
7977   EVT SrcVT = N0.getValueType();
7978   EVT DstVT = Op.getValueType();
7979   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7980     return LowerUINT_TO_FP_i64(Op, DAG);
7981   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7982     return LowerUINT_TO_FP_i32(Op, DAG);
7983   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7984     return SDValue();
7985
7986   // Make a 64-bit buffer, and use it to build an FILD.
7987   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7988   if (SrcVT == MVT::i32) {
7989     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7990     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7991                                      getPointerTy(), StackSlot, WordOff);
7992     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7993                                   StackSlot, MachinePointerInfo(),
7994                                   false, false, 0);
7995     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7996                                   OffsetSlot, MachinePointerInfo(),
7997                                   false, false, 0);
7998     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7999     return Fild;
8000   }
8001
8002   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8003   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8004                                StackSlot, MachinePointerInfo(),
8005                                false, false, 0);
8006   // For i64 source, we need to add the appropriate power of 2 if the input
8007   // was negative.  This is the same as the optimization in
8008   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8009   // we must be careful to do the computation in x87 extended precision, not
8010   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8011   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8012   MachineMemOperand *MMO =
8013     DAG.getMachineFunction()
8014     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8015                           MachineMemOperand::MOLoad, 8, 8);
8016
8017   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8018   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8019   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8020                                          MVT::i64, MMO);
8021
8022   APInt FF(32, 0x5F800000ULL);
8023
8024   // Check whether the sign bit is set.
8025   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8026                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8027                                  ISD::SETLT);
8028
8029   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8030   SDValue FudgePtr = DAG.getConstantPool(
8031                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8032                                          getPointerTy());
8033
8034   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8035   SDValue Zero = DAG.getIntPtrConstant(0);
8036   SDValue Four = DAG.getIntPtrConstant(4);
8037   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8038                                Zero, Four);
8039   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8040
8041   // Load the value out, extending it from f32 to f80.
8042   // FIXME: Avoid the extend by constructing the right constant pool?
8043   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8044                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8045                                  MVT::f32, false, false, 4);
8046   // Extend everything to 80 bits to force it to be done on x87.
8047   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8048   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8049 }
8050
8051 std::pair<SDValue,SDValue> X86TargetLowering::
8052 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8053   DebugLoc DL = Op.getDebugLoc();
8054
8055   EVT DstTy = Op.getValueType();
8056
8057   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8058     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8059     DstTy = MVT::i64;
8060   }
8061
8062   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8063          DstTy.getSimpleVT() >= MVT::i16 &&
8064          "Unknown FP_TO_INT to lower!");
8065
8066   // These are really Legal.
8067   if (DstTy == MVT::i32 &&
8068       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8069     return std::make_pair(SDValue(), SDValue());
8070   if (Subtarget->is64Bit() &&
8071       DstTy == MVT::i64 &&
8072       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8073     return std::make_pair(SDValue(), SDValue());
8074
8075   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8076   // stack slot, or into the FTOL runtime function.
8077   MachineFunction &MF = DAG.getMachineFunction();
8078   unsigned MemSize = DstTy.getSizeInBits()/8;
8079   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8080   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8081
8082   unsigned Opc;
8083   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8084     Opc = X86ISD::WIN_FTOL;
8085   else
8086     switch (DstTy.getSimpleVT().SimpleTy) {
8087     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8088     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8089     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8090     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8091     }
8092
8093   SDValue Chain = DAG.getEntryNode();
8094   SDValue Value = Op.getOperand(0);
8095   EVT TheVT = Op.getOperand(0).getValueType();
8096   // FIXME This causes a redundant load/store if the SSE-class value is already
8097   // in memory, such as if it is on the callstack.
8098   if (isScalarFPTypeInSSEReg(TheVT)) {
8099     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8100     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8101                          MachinePointerInfo::getFixedStack(SSFI),
8102                          false, false, 0);
8103     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8104     SDValue Ops[] = {
8105       Chain, StackSlot, DAG.getValueType(TheVT)
8106     };
8107
8108     MachineMemOperand *MMO =
8109       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8110                               MachineMemOperand::MOLoad, MemSize, MemSize);
8111     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8112                                     DstTy, MMO);
8113     Chain = Value.getValue(1);
8114     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8115     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8116   }
8117
8118   MachineMemOperand *MMO =
8119     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8120                             MachineMemOperand::MOStore, MemSize, MemSize);
8121
8122   if (Opc != X86ISD::WIN_FTOL) {
8123     // Build the FP_TO_INT*_IN_MEM
8124     SDValue Ops[] = { Chain, Value, StackSlot };
8125     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8126                                            Ops, 3, DstTy, MMO);
8127     return std::make_pair(FIST, StackSlot);
8128   } else {
8129     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8130       DAG.getVTList(MVT::Other, MVT::Glue),
8131       Chain, Value);
8132     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8133       MVT::i32, ftol.getValue(1));
8134     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8135       MVT::i32, eax.getValue(2));
8136     SDValue Ops[] = { eax, edx };
8137     SDValue pair = IsReplace
8138       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8139       : DAG.getMergeValues(Ops, 2, DL);
8140     return std::make_pair(pair, SDValue());
8141   }
8142 }
8143
8144 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8145                                            SelectionDAG &DAG) const {
8146   if (Op.getValueType().isVector())
8147     return SDValue();
8148
8149   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8150     /*IsSigned=*/ true, /*IsReplace=*/ false);
8151   SDValue FIST = Vals.first, StackSlot = Vals.second;
8152   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8153   if (FIST.getNode() == 0) return Op;
8154
8155   if (StackSlot.getNode())
8156     // Load the result.
8157     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8158                        FIST, StackSlot, MachinePointerInfo(),
8159                        false, false, false, 0);
8160
8161   // The node is the result.
8162   return FIST;
8163 }
8164
8165 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8166                                            SelectionDAG &DAG) const {
8167   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8168     /*IsSigned=*/ false, /*IsReplace=*/ false);
8169   SDValue FIST = Vals.first, StackSlot = Vals.second;
8170   assert(FIST.getNode() && "Unexpected failure");
8171
8172   if (StackSlot.getNode())
8173     // Load the result.
8174     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8175                        FIST, StackSlot, MachinePointerInfo(),
8176                        false, false, false, 0);
8177
8178   // The node is the result.
8179   return FIST;
8180 }
8181
8182 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8183   LLVMContext *Context = DAG.getContext();
8184   DebugLoc dl = Op.getDebugLoc();
8185   EVT VT = Op.getValueType();
8186   EVT EltVT = VT;
8187   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8188   if (VT.isVector()) {
8189     EltVT = VT.getVectorElementType();
8190     NumElts = VT.getVectorNumElements();
8191   }
8192   Constant *C;
8193   if (EltVT == MVT::f64)
8194     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8195   else
8196     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8197   C = ConstantVector::getSplat(NumElts, C);
8198   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8199   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8200   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8201                              MachinePointerInfo::getConstantPool(),
8202                              false, false, false, Alignment);
8203   if (VT.isVector()) {
8204     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8205     return DAG.getNode(ISD::BITCAST, dl, VT,
8206                        DAG.getNode(ISD::AND, dl, ANDVT,
8207                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8208                                                Op.getOperand(0)),
8209                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8210   }
8211   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8212 }
8213
8214 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8215   LLVMContext *Context = DAG.getContext();
8216   DebugLoc dl = Op.getDebugLoc();
8217   EVT VT = Op.getValueType();
8218   EVT EltVT = VT;
8219   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8220   if (VT.isVector()) {
8221     EltVT = VT.getVectorElementType();
8222     NumElts = VT.getVectorNumElements();
8223   }
8224   Constant *C;
8225   if (EltVT == MVT::f64)
8226     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8227   else
8228     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8229   C = ConstantVector::getSplat(NumElts, C);
8230   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8231   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8232   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8233                              MachinePointerInfo::getConstantPool(),
8234                              false, false, false, Alignment);
8235   if (VT.isVector()) {
8236     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8237     return DAG.getNode(ISD::BITCAST, dl, VT,
8238                        DAG.getNode(ISD::XOR, dl, XORVT,
8239                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8240                                                Op.getOperand(0)),
8241                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8242   }
8243
8244   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8245 }
8246
8247 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8248   LLVMContext *Context = DAG.getContext();
8249   SDValue Op0 = Op.getOperand(0);
8250   SDValue Op1 = Op.getOperand(1);
8251   DebugLoc dl = Op.getDebugLoc();
8252   EVT VT = Op.getValueType();
8253   EVT SrcVT = Op1.getValueType();
8254
8255   // If second operand is smaller, extend it first.
8256   if (SrcVT.bitsLT(VT)) {
8257     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8258     SrcVT = VT;
8259   }
8260   // And if it is bigger, shrink it first.
8261   if (SrcVT.bitsGT(VT)) {
8262     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8263     SrcVT = VT;
8264   }
8265
8266   // At this point the operands and the result should have the same
8267   // type, and that won't be f80 since that is not custom lowered.
8268
8269   // First get the sign bit of second operand.
8270   SmallVector<Constant*,4> CV;
8271   if (SrcVT == MVT::f64) {
8272     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8273     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8274   } else {
8275     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8276     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8277     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8278     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8279   }
8280   Constant *C = ConstantVector::get(CV);
8281   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8282   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8283                               MachinePointerInfo::getConstantPool(),
8284                               false, false, false, 16);
8285   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8286
8287   // Shift sign bit right or left if the two operands have different types.
8288   if (SrcVT.bitsGT(VT)) {
8289     // Op0 is MVT::f32, Op1 is MVT::f64.
8290     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8291     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8292                           DAG.getConstant(32, MVT::i32));
8293     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8294     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8295                           DAG.getIntPtrConstant(0));
8296   }
8297
8298   // Clear first operand sign bit.
8299   CV.clear();
8300   if (VT == MVT::f64) {
8301     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8302     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8303   } else {
8304     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8305     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8306     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8307     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8308   }
8309   C = ConstantVector::get(CV);
8310   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8311   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8312                               MachinePointerInfo::getConstantPool(),
8313                               false, false, false, 16);
8314   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8315
8316   // Or the value with the sign bit.
8317   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8318 }
8319
8320 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8321   SDValue N0 = Op.getOperand(0);
8322   DebugLoc dl = Op.getDebugLoc();
8323   EVT VT = Op.getValueType();
8324
8325   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8326   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8327                                   DAG.getConstant(1, VT));
8328   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8329 }
8330
8331 /// Emit nodes that will be selected as "test Op0,Op0", or something
8332 /// equivalent.
8333 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8334                                     SelectionDAG &DAG) const {
8335   DebugLoc dl = Op.getDebugLoc();
8336
8337   // CF and OF aren't always set the way we want. Determine which
8338   // of these we need.
8339   bool NeedCF = false;
8340   bool NeedOF = false;
8341   switch (X86CC) {
8342   default: break;
8343   case X86::COND_A: case X86::COND_AE:
8344   case X86::COND_B: case X86::COND_BE:
8345     NeedCF = true;
8346     break;
8347   case X86::COND_G: case X86::COND_GE:
8348   case X86::COND_L: case X86::COND_LE:
8349   case X86::COND_O: case X86::COND_NO:
8350     NeedOF = true;
8351     break;
8352   }
8353
8354   // See if we can use the EFLAGS value from the operand instead of
8355   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8356   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8357   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8358     // Emit a CMP with 0, which is the TEST pattern.
8359     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8360                        DAG.getConstant(0, Op.getValueType()));
8361
8362   unsigned Opcode = 0;
8363   unsigned NumOperands = 0;
8364
8365   // Truncate operations may prevent the merge of the SETCC instruction
8366   // and the arithmetic intruction before it. Attempt to truncate the operands
8367   // of the arithmetic instruction and use a reduced bit-width instruction.
8368   bool NeedTruncation = false;
8369   SDValue ArithOp = Op;
8370   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8371     SDValue Arith = Op->getOperand(0);
8372     // Both the trunc and the arithmetic op need to have one user each.
8373     if (Arith->hasOneUse())
8374       switch (Arith.getOpcode()) {
8375         default: break;
8376         case ISD::ADD:
8377         case ISD::SUB:
8378         case ISD::AND:
8379         case ISD::OR:
8380         case ISD::XOR: {
8381           NeedTruncation = true;
8382           ArithOp = Arith;
8383         }
8384       }
8385   }
8386
8387   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8388   // which may be the result of a CAST.  We use the variable 'Op', which is the
8389   // non-casted variable when we check for possible users.
8390   switch (ArithOp.getOpcode()) {
8391   case ISD::ADD:
8392     // Due to an isel shortcoming, be conservative if this add is likely to be
8393     // selected as part of a load-modify-store instruction. When the root node
8394     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8395     // uses of other nodes in the match, such as the ADD in this case. This
8396     // leads to the ADD being left around and reselected, with the result being
8397     // two adds in the output.  Alas, even if none our users are stores, that
8398     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8399     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8400     // climbing the DAG back to the root, and it doesn't seem to be worth the
8401     // effort.
8402     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8403          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8404       if (UI->getOpcode() != ISD::CopyToReg &&
8405           UI->getOpcode() != ISD::SETCC &&
8406           UI->getOpcode() != ISD::STORE)
8407         goto default_case;
8408
8409     if (ConstantSDNode *C =
8410         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8411       // An add of one will be selected as an INC.
8412       if (C->getAPIntValue() == 1) {
8413         Opcode = X86ISD::INC;
8414         NumOperands = 1;
8415         break;
8416       }
8417
8418       // An add of negative one (subtract of one) will be selected as a DEC.
8419       if (C->getAPIntValue().isAllOnesValue()) {
8420         Opcode = X86ISD::DEC;
8421         NumOperands = 1;
8422         break;
8423       }
8424     }
8425
8426     // Otherwise use a regular EFLAGS-setting add.
8427     Opcode = X86ISD::ADD;
8428     NumOperands = 2;
8429     break;
8430   case ISD::AND: {
8431     // If the primary and result isn't used, don't bother using X86ISD::AND,
8432     // because a TEST instruction will be better.
8433     bool NonFlagUse = false;
8434     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8435            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8436       SDNode *User = *UI;
8437       unsigned UOpNo = UI.getOperandNo();
8438       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8439         // Look pass truncate.
8440         UOpNo = User->use_begin().getOperandNo();
8441         User = *User->use_begin();
8442       }
8443
8444       if (User->getOpcode() != ISD::BRCOND &&
8445           User->getOpcode() != ISD::SETCC &&
8446           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8447         NonFlagUse = true;
8448         break;
8449       }
8450     }
8451
8452     if (!NonFlagUse)
8453       break;
8454   }
8455     // FALL THROUGH
8456   case ISD::SUB:
8457   case ISD::OR:
8458   case ISD::XOR:
8459     // Due to the ISEL shortcoming noted above, be conservative if this op is
8460     // likely to be selected as part of a load-modify-store instruction.
8461     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8462            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8463       if (UI->getOpcode() == ISD::STORE)
8464         goto default_case;
8465
8466     // Otherwise use a regular EFLAGS-setting instruction.
8467     switch (ArithOp.getOpcode()) {
8468     default: llvm_unreachable("unexpected operator!");
8469     case ISD::SUB: Opcode = X86ISD::SUB; break;
8470     case ISD::OR:  Opcode = X86ISD::OR;  break;
8471     case ISD::XOR: Opcode = X86ISD::XOR; break;
8472     case ISD::AND: Opcode = X86ISD::AND; break;
8473     }
8474
8475     NumOperands = 2;
8476     break;
8477   case X86ISD::ADD:
8478   case X86ISD::SUB:
8479   case X86ISD::INC:
8480   case X86ISD::DEC:
8481   case X86ISD::OR:
8482   case X86ISD::XOR:
8483   case X86ISD::AND:
8484     return SDValue(Op.getNode(), 1);
8485   default:
8486   default_case:
8487     break;
8488   }
8489
8490   // If we found that truncation is beneficial, perform the truncation and
8491   // update 'Op'.
8492   if (NeedTruncation) {
8493     EVT VT = Op.getValueType();
8494     SDValue WideVal = Op->getOperand(0);
8495     EVT WideVT = WideVal.getValueType();
8496     unsigned ConvertedOp = 0;
8497     // Use a target machine opcode to prevent further DAGCombine
8498     // optimizations that may separate the arithmetic operations
8499     // from the setcc node.
8500     switch (WideVal.getOpcode()) {
8501       default: break;
8502       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8503       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8504       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8505       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8506       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8507     }
8508
8509     if (ConvertedOp) {
8510       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8511       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8512         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8513         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8514         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8515       }
8516     }
8517   }
8518
8519   if (Opcode == 0)
8520     // Emit a CMP with 0, which is the TEST pattern.
8521     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8522                        DAG.getConstant(0, Op.getValueType()));
8523
8524   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8525   SmallVector<SDValue, 4> Ops;
8526   for (unsigned i = 0; i != NumOperands; ++i)
8527     Ops.push_back(Op.getOperand(i));
8528
8529   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8530   DAG.ReplaceAllUsesWith(Op, New);
8531   return SDValue(New.getNode(), 1);
8532 }
8533
8534 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8535 /// equivalent.
8536 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8537                                    SelectionDAG &DAG) const {
8538   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8539     if (C->getAPIntValue() == 0)
8540       return EmitTest(Op0, X86CC, DAG);
8541
8542   DebugLoc dl = Op0.getDebugLoc();
8543   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8544        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8545     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8546     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8547     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8548                               Op0, Op1);
8549     return SDValue(Sub.getNode(), 1);
8550   }
8551   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8552 }
8553
8554 /// Convert a comparison if required by the subtarget.
8555 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8556                                                  SelectionDAG &DAG) const {
8557   // If the subtarget does not support the FUCOMI instruction, floating-point
8558   // comparisons have to be converted.
8559   if (Subtarget->hasCMov() ||
8560       Cmp.getOpcode() != X86ISD::CMP ||
8561       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8562       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8563     return Cmp;
8564
8565   // The instruction selector will select an FUCOM instruction instead of
8566   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8567   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8568   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8569   DebugLoc dl = Cmp.getDebugLoc();
8570   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8571   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8572   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8573                             DAG.getConstant(8, MVT::i8));
8574   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8575   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8576 }
8577
8578 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8579 /// if it's possible.
8580 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8581                                      DebugLoc dl, SelectionDAG &DAG) const {
8582   SDValue Op0 = And.getOperand(0);
8583   SDValue Op1 = And.getOperand(1);
8584   if (Op0.getOpcode() == ISD::TRUNCATE)
8585     Op0 = Op0.getOperand(0);
8586   if (Op1.getOpcode() == ISD::TRUNCATE)
8587     Op1 = Op1.getOperand(0);
8588
8589   SDValue LHS, RHS;
8590   if (Op1.getOpcode() == ISD::SHL)
8591     std::swap(Op0, Op1);
8592   if (Op0.getOpcode() == ISD::SHL) {
8593     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8594       if (And00C->getZExtValue() == 1) {
8595         // If we looked past a truncate, check that it's only truncating away
8596         // known zeros.
8597         unsigned BitWidth = Op0.getValueSizeInBits();
8598         unsigned AndBitWidth = And.getValueSizeInBits();
8599         if (BitWidth > AndBitWidth) {
8600           APInt Zeros, Ones;
8601           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8602           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8603             return SDValue();
8604         }
8605         LHS = Op1;
8606         RHS = Op0.getOperand(1);
8607       }
8608   } else if (Op1.getOpcode() == ISD::Constant) {
8609     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8610     uint64_t AndRHSVal = AndRHS->getZExtValue();
8611     SDValue AndLHS = Op0;
8612
8613     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8614       LHS = AndLHS.getOperand(0);
8615       RHS = AndLHS.getOperand(1);
8616     }
8617
8618     // Use BT if the immediate can't be encoded in a TEST instruction.
8619     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8620       LHS = AndLHS;
8621       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8622     }
8623   }
8624
8625   if (LHS.getNode()) {
8626     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8627     // instruction.  Since the shift amount is in-range-or-undefined, we know
8628     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8629     // the encoding for the i16 version is larger than the i32 version.
8630     // Also promote i16 to i32 for performance / code size reason.
8631     if (LHS.getValueType() == MVT::i8 ||
8632         LHS.getValueType() == MVT::i16)
8633       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8634
8635     // If the operand types disagree, extend the shift amount to match.  Since
8636     // BT ignores high bits (like shifts) we can use anyextend.
8637     if (LHS.getValueType() != RHS.getValueType())
8638       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8639
8640     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8641     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8642     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8643                        DAG.getConstant(Cond, MVT::i8), BT);
8644   }
8645
8646   return SDValue();
8647 }
8648
8649 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8650
8651   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8652
8653   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8654   SDValue Op0 = Op.getOperand(0);
8655   SDValue Op1 = Op.getOperand(1);
8656   DebugLoc dl = Op.getDebugLoc();
8657   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8658
8659   // Optimize to BT if possible.
8660   // Lower (X & (1 << N)) == 0 to BT(X, N).
8661   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8662   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8663   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8664       Op1.getOpcode() == ISD::Constant &&
8665       cast<ConstantSDNode>(Op1)->isNullValue() &&
8666       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8667     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8668     if (NewSetCC.getNode())
8669       return NewSetCC;
8670   }
8671
8672   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8673   // these.
8674   if (Op1.getOpcode() == ISD::Constant &&
8675       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8676        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8677       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8678
8679     // If the input is a setcc, then reuse the input setcc or use a new one with
8680     // the inverted condition.
8681     if (Op0.getOpcode() == X86ISD::SETCC) {
8682       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8683       bool Invert = (CC == ISD::SETNE) ^
8684         cast<ConstantSDNode>(Op1)->isNullValue();
8685       if (!Invert) return Op0;
8686
8687       CCode = X86::GetOppositeBranchCondition(CCode);
8688       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8689                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8690     }
8691   }
8692
8693   bool isFP = Op1.getValueType().isFloatingPoint();
8694   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8695   if (X86CC == X86::COND_INVALID)
8696     return SDValue();
8697
8698   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8699   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8700   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8701                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8702 }
8703
8704 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8705 // ones, and then concatenate the result back.
8706 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8707   EVT VT = Op.getValueType();
8708
8709   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8710          "Unsupported value type for operation");
8711
8712   unsigned NumElems = VT.getVectorNumElements();
8713   DebugLoc dl = Op.getDebugLoc();
8714   SDValue CC = Op.getOperand(2);
8715
8716   // Extract the LHS vectors
8717   SDValue LHS = Op.getOperand(0);
8718   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8719   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8720
8721   // Extract the RHS vectors
8722   SDValue RHS = Op.getOperand(1);
8723   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8724   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8725
8726   // Issue the operation on the smaller types and concatenate the result back
8727   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8728   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8729   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8730                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8731                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8732 }
8733
8734
8735 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8736   SDValue Cond;
8737   SDValue Op0 = Op.getOperand(0);
8738   SDValue Op1 = Op.getOperand(1);
8739   SDValue CC = Op.getOperand(2);
8740   EVT VT = Op.getValueType();
8741   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8742   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8743   DebugLoc dl = Op.getDebugLoc();
8744
8745   if (isFP) {
8746 #ifndef NDEBUG
8747     EVT EltVT = Op0.getValueType().getVectorElementType();
8748     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8749 #endif
8750
8751     unsigned SSECC;
8752     bool Swap = false;
8753
8754     // SSE Condition code mapping:
8755     //  0 - EQ
8756     //  1 - LT
8757     //  2 - LE
8758     //  3 - UNORD
8759     //  4 - NEQ
8760     //  5 - NLT
8761     //  6 - NLE
8762     //  7 - ORD
8763     switch (SetCCOpcode) {
8764     default: llvm_unreachable("Unexpected SETCC condition");
8765     case ISD::SETOEQ:
8766     case ISD::SETEQ:  SSECC = 0; break;
8767     case ISD::SETOGT:
8768     case ISD::SETGT: Swap = true; // Fallthrough
8769     case ISD::SETLT:
8770     case ISD::SETOLT: SSECC = 1; break;
8771     case ISD::SETOGE:
8772     case ISD::SETGE: Swap = true; // Fallthrough
8773     case ISD::SETLE:
8774     case ISD::SETOLE: SSECC = 2; break;
8775     case ISD::SETUO:  SSECC = 3; break;
8776     case ISD::SETUNE:
8777     case ISD::SETNE:  SSECC = 4; break;
8778     case ISD::SETULE: Swap = true; // Fallthrough
8779     case ISD::SETUGE: SSECC = 5; break;
8780     case ISD::SETULT: Swap = true; // Fallthrough
8781     case ISD::SETUGT: SSECC = 6; break;
8782     case ISD::SETO:   SSECC = 7; break;
8783     case ISD::SETUEQ:
8784     case ISD::SETONE: SSECC = 8; break;
8785     }
8786     if (Swap)
8787       std::swap(Op0, Op1);
8788
8789     // In the two special cases we can't handle, emit two comparisons.
8790     if (SSECC == 8) {
8791       unsigned CC0, CC1;
8792       unsigned CombineOpc;
8793       if (SetCCOpcode == ISD::SETUEQ) {
8794         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8795       } else {
8796         assert(SetCCOpcode == ISD::SETONE);
8797         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8798       }
8799
8800       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8801                                  DAG.getConstant(CC0, MVT::i8));
8802       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8803                                  DAG.getConstant(CC1, MVT::i8));
8804       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8805     }
8806     // Handle all other FP comparisons here.
8807     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8808                        DAG.getConstant(SSECC, MVT::i8));
8809   }
8810
8811   // Break 256-bit integer vector compare into smaller ones.
8812   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8813     return Lower256IntVSETCC(Op, DAG);
8814
8815   // We are handling one of the integer comparisons here.  Since SSE only has
8816   // GT and EQ comparisons for integer, swapping operands and multiple
8817   // operations may be required for some comparisons.
8818   unsigned Opc;
8819   bool Swap = false, Invert = false, FlipSigns = false;
8820
8821   switch (SetCCOpcode) {
8822   default: llvm_unreachable("Unexpected SETCC condition");
8823   case ISD::SETNE:  Invert = true;
8824   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8825   case ISD::SETLT:  Swap = true;
8826   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8827   case ISD::SETGE:  Swap = true;
8828   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8829   case ISD::SETULT: Swap = true;
8830   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8831   case ISD::SETUGE: Swap = true;
8832   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8833   }
8834   if (Swap)
8835     std::swap(Op0, Op1);
8836
8837   // Check that the operation in question is available (most are plain SSE2,
8838   // but PCMPGTQ and PCMPEQQ have different requirements).
8839   if (VT == MVT::v2i64) {
8840     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8841       return SDValue();
8842     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8843       return SDValue();
8844   }
8845
8846   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8847   // bits of the inputs before performing those operations.
8848   if (FlipSigns) {
8849     EVT EltVT = VT.getVectorElementType();
8850     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8851                                       EltVT);
8852     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8853     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8854                                     SignBits.size());
8855     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8856     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8857   }
8858
8859   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8860
8861   // If the logical-not of the result is required, perform that now.
8862   if (Invert)
8863     Result = DAG.getNOT(dl, Result, VT);
8864
8865   return Result;
8866 }
8867
8868 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8869 static bool isX86LogicalCmp(SDValue Op) {
8870   unsigned Opc = Op.getNode()->getOpcode();
8871   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8872       Opc == X86ISD::SAHF)
8873     return true;
8874   if (Op.getResNo() == 1 &&
8875       (Opc == X86ISD::ADD ||
8876        Opc == X86ISD::SUB ||
8877        Opc == X86ISD::ADC ||
8878        Opc == X86ISD::SBB ||
8879        Opc == X86ISD::SMUL ||
8880        Opc == X86ISD::UMUL ||
8881        Opc == X86ISD::INC ||
8882        Opc == X86ISD::DEC ||
8883        Opc == X86ISD::OR ||
8884        Opc == X86ISD::XOR ||
8885        Opc == X86ISD::AND))
8886     return true;
8887
8888   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8889     return true;
8890
8891   return false;
8892 }
8893
8894 static bool isZero(SDValue V) {
8895   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8896   return C && C->isNullValue();
8897 }
8898
8899 static bool isAllOnes(SDValue V) {
8900   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8901   return C && C->isAllOnesValue();
8902 }
8903
8904 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8905   if (V.getOpcode() != ISD::TRUNCATE)
8906     return false;
8907
8908   SDValue VOp0 = V.getOperand(0);
8909   unsigned InBits = VOp0.getValueSizeInBits();
8910   unsigned Bits = V.getValueSizeInBits();
8911   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8912 }
8913
8914 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8915   bool addTest = true;
8916   SDValue Cond  = Op.getOperand(0);
8917   SDValue Op1 = Op.getOperand(1);
8918   SDValue Op2 = Op.getOperand(2);
8919   DebugLoc DL = Op.getDebugLoc();
8920   SDValue CC;
8921
8922   if (Cond.getOpcode() == ISD::SETCC) {
8923     SDValue NewCond = LowerSETCC(Cond, DAG);
8924     if (NewCond.getNode())
8925       Cond = NewCond;
8926   }
8927
8928   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8929   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8930   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8931   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8932   if (Cond.getOpcode() == X86ISD::SETCC &&
8933       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8934       isZero(Cond.getOperand(1).getOperand(1))) {
8935     SDValue Cmp = Cond.getOperand(1);
8936
8937     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8938
8939     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8940         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8941       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8942
8943       SDValue CmpOp0 = Cmp.getOperand(0);
8944       // Apply further optimizations for special cases
8945       // (select (x != 0), -1, 0) -> neg & sbb
8946       // (select (x == 0), 0, -1) -> neg & sbb
8947       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8948         if (YC->isNullValue() &&
8949             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8950           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8951           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8952                                     DAG.getConstant(0, CmpOp0.getValueType()),
8953                                     CmpOp0);
8954           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8955                                     DAG.getConstant(X86::COND_B, MVT::i8),
8956                                     SDValue(Neg.getNode(), 1));
8957           return Res;
8958         }
8959
8960       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8961                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8962       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8963
8964       SDValue Res =   // Res = 0 or -1.
8965         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8966                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8967
8968       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8969         Res = DAG.getNOT(DL, Res, Res.getValueType());
8970
8971       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8972       if (N2C == 0 || !N2C->isNullValue())
8973         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8974       return Res;
8975     }
8976   }
8977
8978   // Look past (and (setcc_carry (cmp ...)), 1).
8979   if (Cond.getOpcode() == ISD::AND &&
8980       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8981     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8982     if (C && C->getAPIntValue() == 1)
8983       Cond = Cond.getOperand(0);
8984   }
8985
8986   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8987   // setting operand in place of the X86ISD::SETCC.
8988   unsigned CondOpcode = Cond.getOpcode();
8989   if (CondOpcode == X86ISD::SETCC ||
8990       CondOpcode == X86ISD::SETCC_CARRY) {
8991     CC = Cond.getOperand(0);
8992
8993     SDValue Cmp = Cond.getOperand(1);
8994     unsigned Opc = Cmp.getOpcode();
8995     EVT VT = Op.getValueType();
8996
8997     bool IllegalFPCMov = false;
8998     if (VT.isFloatingPoint() && !VT.isVector() &&
8999         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9000       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9001
9002     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9003         Opc == X86ISD::BT) { // FIXME
9004       Cond = Cmp;
9005       addTest = false;
9006     }
9007   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9008              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9009              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9010               Cond.getOperand(0).getValueType() != MVT::i8)) {
9011     SDValue LHS = Cond.getOperand(0);
9012     SDValue RHS = Cond.getOperand(1);
9013     unsigned X86Opcode;
9014     unsigned X86Cond;
9015     SDVTList VTs;
9016     switch (CondOpcode) {
9017     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9018     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9019     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9020     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9021     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9022     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9023     default: llvm_unreachable("unexpected overflowing operator");
9024     }
9025     if (CondOpcode == ISD::UMULO)
9026       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9027                           MVT::i32);
9028     else
9029       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9030
9031     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9032
9033     if (CondOpcode == ISD::UMULO)
9034       Cond = X86Op.getValue(2);
9035     else
9036       Cond = X86Op.getValue(1);
9037
9038     CC = DAG.getConstant(X86Cond, MVT::i8);
9039     addTest = false;
9040   }
9041
9042   if (addTest) {
9043     // Look pass the truncate if the high bits are known zero.
9044     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9045         Cond = Cond.getOperand(0);
9046
9047     // We know the result of AND is compared against zero. Try to match
9048     // it to BT.
9049     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9050       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9051       if (NewSetCC.getNode()) {
9052         CC = NewSetCC.getOperand(0);
9053         Cond = NewSetCC.getOperand(1);
9054         addTest = false;
9055       }
9056     }
9057   }
9058
9059   if (addTest) {
9060     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9061     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9062   }
9063
9064   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9065   // a <  b ?  0 : -1 -> RES = setcc_carry
9066   // a >= b ? -1 :  0 -> RES = setcc_carry
9067   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9068   if (Cond.getOpcode() == X86ISD::SUB) {
9069     Cond = ConvertCmpIfNecessary(Cond, DAG);
9070     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9071
9072     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9073         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9074       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9075                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9076       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9077         return DAG.getNOT(DL, Res, Res.getValueType());
9078       return Res;
9079     }
9080   }
9081
9082   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9083   // condition is true.
9084   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9085   SDValue Ops[] = { Op2, Op1, CC, Cond };
9086   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9087 }
9088
9089 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9090 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9091 // from the AND / OR.
9092 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9093   Opc = Op.getOpcode();
9094   if (Opc != ISD::OR && Opc != ISD::AND)
9095     return false;
9096   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9097           Op.getOperand(0).hasOneUse() &&
9098           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9099           Op.getOperand(1).hasOneUse());
9100 }
9101
9102 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9103 // 1 and that the SETCC node has a single use.
9104 static bool isXor1OfSetCC(SDValue Op) {
9105   if (Op.getOpcode() != ISD::XOR)
9106     return false;
9107   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9108   if (N1C && N1C->getAPIntValue() == 1) {
9109     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9110       Op.getOperand(0).hasOneUse();
9111   }
9112   return false;
9113 }
9114
9115 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9116   bool addTest = true;
9117   SDValue Chain = Op.getOperand(0);
9118   SDValue Cond  = Op.getOperand(1);
9119   SDValue Dest  = Op.getOperand(2);
9120   DebugLoc dl = Op.getDebugLoc();
9121   SDValue CC;
9122   bool Inverted = false;
9123
9124   if (Cond.getOpcode() == ISD::SETCC) {
9125     // Check for setcc([su]{add,sub,mul}o == 0).
9126     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9127         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9128         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9129         Cond.getOperand(0).getResNo() == 1 &&
9130         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9131          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9132          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9133          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9134          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9135          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9136       Inverted = true;
9137       Cond = Cond.getOperand(0);
9138     } else {
9139       SDValue NewCond = LowerSETCC(Cond, DAG);
9140       if (NewCond.getNode())
9141         Cond = NewCond;
9142     }
9143   }
9144 #if 0
9145   // FIXME: LowerXALUO doesn't handle these!!
9146   else if (Cond.getOpcode() == X86ISD::ADD  ||
9147            Cond.getOpcode() == X86ISD::SUB  ||
9148            Cond.getOpcode() == X86ISD::SMUL ||
9149            Cond.getOpcode() == X86ISD::UMUL)
9150     Cond = LowerXALUO(Cond, DAG);
9151 #endif
9152
9153   // Look pass (and (setcc_carry (cmp ...)), 1).
9154   if (Cond.getOpcode() == ISD::AND &&
9155       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9156     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9157     if (C && C->getAPIntValue() == 1)
9158       Cond = Cond.getOperand(0);
9159   }
9160
9161   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9162   // setting operand in place of the X86ISD::SETCC.
9163   unsigned CondOpcode = Cond.getOpcode();
9164   if (CondOpcode == X86ISD::SETCC ||
9165       CondOpcode == X86ISD::SETCC_CARRY) {
9166     CC = Cond.getOperand(0);
9167
9168     SDValue Cmp = Cond.getOperand(1);
9169     unsigned Opc = Cmp.getOpcode();
9170     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9171     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9172       Cond = Cmp;
9173       addTest = false;
9174     } else {
9175       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9176       default: break;
9177       case X86::COND_O:
9178       case X86::COND_B:
9179         // These can only come from an arithmetic instruction with overflow,
9180         // e.g. SADDO, UADDO.
9181         Cond = Cond.getNode()->getOperand(1);
9182         addTest = false;
9183         break;
9184       }
9185     }
9186   }
9187   CondOpcode = Cond.getOpcode();
9188   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9189       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9190       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9191        Cond.getOperand(0).getValueType() != MVT::i8)) {
9192     SDValue LHS = Cond.getOperand(0);
9193     SDValue RHS = Cond.getOperand(1);
9194     unsigned X86Opcode;
9195     unsigned X86Cond;
9196     SDVTList VTs;
9197     switch (CondOpcode) {
9198     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9199     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9200     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9201     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9202     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9203     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9204     default: llvm_unreachable("unexpected overflowing operator");
9205     }
9206     if (Inverted)
9207       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9208     if (CondOpcode == ISD::UMULO)
9209       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9210                           MVT::i32);
9211     else
9212       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9213
9214     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9215
9216     if (CondOpcode == ISD::UMULO)
9217       Cond = X86Op.getValue(2);
9218     else
9219       Cond = X86Op.getValue(1);
9220
9221     CC = DAG.getConstant(X86Cond, MVT::i8);
9222     addTest = false;
9223   } else {
9224     unsigned CondOpc;
9225     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9226       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9227       if (CondOpc == ISD::OR) {
9228         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9229         // two branches instead of an explicit OR instruction with a
9230         // separate test.
9231         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9232             isX86LogicalCmp(Cmp)) {
9233           CC = Cond.getOperand(0).getOperand(0);
9234           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9235                               Chain, Dest, CC, Cmp);
9236           CC = Cond.getOperand(1).getOperand(0);
9237           Cond = Cmp;
9238           addTest = false;
9239         }
9240       } else { // ISD::AND
9241         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9242         // two branches instead of an explicit AND instruction with a
9243         // separate test. However, we only do this if this block doesn't
9244         // have a fall-through edge, because this requires an explicit
9245         // jmp when the condition is false.
9246         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9247             isX86LogicalCmp(Cmp) &&
9248             Op.getNode()->hasOneUse()) {
9249           X86::CondCode CCode =
9250             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9251           CCode = X86::GetOppositeBranchCondition(CCode);
9252           CC = DAG.getConstant(CCode, MVT::i8);
9253           SDNode *User = *Op.getNode()->use_begin();
9254           // Look for an unconditional branch following this conditional branch.
9255           // We need this because we need to reverse the successors in order
9256           // to implement FCMP_OEQ.
9257           if (User->getOpcode() == ISD::BR) {
9258             SDValue FalseBB = User->getOperand(1);
9259             SDNode *NewBR =
9260               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9261             assert(NewBR == User);
9262             (void)NewBR;
9263             Dest = FalseBB;
9264
9265             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9266                                 Chain, Dest, CC, Cmp);
9267             X86::CondCode CCode =
9268               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9269             CCode = X86::GetOppositeBranchCondition(CCode);
9270             CC = DAG.getConstant(CCode, MVT::i8);
9271             Cond = Cmp;
9272             addTest = false;
9273           }
9274         }
9275       }
9276     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9277       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9278       // It should be transformed during dag combiner except when the condition
9279       // is set by a arithmetics with overflow node.
9280       X86::CondCode CCode =
9281         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9282       CCode = X86::GetOppositeBranchCondition(CCode);
9283       CC = DAG.getConstant(CCode, MVT::i8);
9284       Cond = Cond.getOperand(0).getOperand(1);
9285       addTest = false;
9286     } else if (Cond.getOpcode() == ISD::SETCC &&
9287                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9288       // For FCMP_OEQ, we can emit
9289       // two branches instead of an explicit AND instruction with a
9290       // separate test. However, we only do this if this block doesn't
9291       // have a fall-through edge, because this requires an explicit
9292       // jmp when the condition is false.
9293       if (Op.getNode()->hasOneUse()) {
9294         SDNode *User = *Op.getNode()->use_begin();
9295         // Look for an unconditional branch following this conditional branch.
9296         // We need this because we need to reverse the successors in order
9297         // to implement FCMP_OEQ.
9298         if (User->getOpcode() == ISD::BR) {
9299           SDValue FalseBB = User->getOperand(1);
9300           SDNode *NewBR =
9301             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9302           assert(NewBR == User);
9303           (void)NewBR;
9304           Dest = FalseBB;
9305
9306           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9307                                     Cond.getOperand(0), Cond.getOperand(1));
9308           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9309           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9310           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9311                               Chain, Dest, CC, Cmp);
9312           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9313           Cond = Cmp;
9314           addTest = false;
9315         }
9316       }
9317     } else if (Cond.getOpcode() == ISD::SETCC &&
9318                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9319       // For FCMP_UNE, we can emit
9320       // two branches instead of an explicit AND instruction with a
9321       // separate test. However, we only do this if this block doesn't
9322       // have a fall-through edge, because this requires an explicit
9323       // jmp when the condition is false.
9324       if (Op.getNode()->hasOneUse()) {
9325         SDNode *User = *Op.getNode()->use_begin();
9326         // Look for an unconditional branch following this conditional branch.
9327         // We need this because we need to reverse the successors in order
9328         // to implement FCMP_UNE.
9329         if (User->getOpcode() == ISD::BR) {
9330           SDValue FalseBB = User->getOperand(1);
9331           SDNode *NewBR =
9332             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9333           assert(NewBR == User);
9334           (void)NewBR;
9335
9336           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9337                                     Cond.getOperand(0), Cond.getOperand(1));
9338           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9339           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9340           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9341                               Chain, Dest, CC, Cmp);
9342           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9343           Cond = Cmp;
9344           addTest = false;
9345           Dest = FalseBB;
9346         }
9347       }
9348     }
9349   }
9350
9351   if (addTest) {
9352     // Look pass the truncate if the high bits are known zero.
9353     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9354         Cond = Cond.getOperand(0);
9355
9356     // We know the result of AND is compared against zero. Try to match
9357     // it to BT.
9358     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9359       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9360       if (NewSetCC.getNode()) {
9361         CC = NewSetCC.getOperand(0);
9362         Cond = NewSetCC.getOperand(1);
9363         addTest = false;
9364       }
9365     }
9366   }
9367
9368   if (addTest) {
9369     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9370     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9371   }
9372   Cond = ConvertCmpIfNecessary(Cond, DAG);
9373   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9374                      Chain, Dest, CC, Cond);
9375 }
9376
9377
9378 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9379 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9380 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9381 // that the guard pages used by the OS virtual memory manager are allocated in
9382 // correct sequence.
9383 SDValue
9384 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9385                                            SelectionDAG &DAG) const {
9386   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9387           getTargetMachine().Options.EnableSegmentedStacks) &&
9388          "This should be used only on Windows targets or when segmented stacks "
9389          "are being used");
9390   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9391   DebugLoc dl = Op.getDebugLoc();
9392
9393   // Get the inputs.
9394   SDValue Chain = Op.getOperand(0);
9395   SDValue Size  = Op.getOperand(1);
9396   // FIXME: Ensure alignment here
9397
9398   bool Is64Bit = Subtarget->is64Bit();
9399   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9400
9401   if (getTargetMachine().Options.EnableSegmentedStacks) {
9402     MachineFunction &MF = DAG.getMachineFunction();
9403     MachineRegisterInfo &MRI = MF.getRegInfo();
9404
9405     if (Is64Bit) {
9406       // The 64 bit implementation of segmented stacks needs to clobber both r10
9407       // r11. This makes it impossible to use it along with nested parameters.
9408       const Function *F = MF.getFunction();
9409
9410       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9411            I != E; ++I)
9412         if (I->hasNestAttr())
9413           report_fatal_error("Cannot use segmented stacks with functions that "
9414                              "have nested arguments.");
9415     }
9416
9417     const TargetRegisterClass *AddrRegClass =
9418       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9419     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9420     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9421     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9422                                 DAG.getRegister(Vreg, SPTy));
9423     SDValue Ops1[2] = { Value, Chain };
9424     return DAG.getMergeValues(Ops1, 2, dl);
9425   } else {
9426     SDValue Flag;
9427     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9428
9429     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9430     Flag = Chain.getValue(1);
9431     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9432
9433     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9434     Flag = Chain.getValue(1);
9435
9436     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9437
9438     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9439     return DAG.getMergeValues(Ops1, 2, dl);
9440   }
9441 }
9442
9443 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9444   MachineFunction &MF = DAG.getMachineFunction();
9445   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9446
9447   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9448   DebugLoc DL = Op.getDebugLoc();
9449
9450   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9451     // vastart just stores the address of the VarArgsFrameIndex slot into the
9452     // memory location argument.
9453     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9454                                    getPointerTy());
9455     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9456                         MachinePointerInfo(SV), false, false, 0);
9457   }
9458
9459   // __va_list_tag:
9460   //   gp_offset         (0 - 6 * 8)
9461   //   fp_offset         (48 - 48 + 8 * 16)
9462   //   overflow_arg_area (point to parameters coming in memory).
9463   //   reg_save_area
9464   SmallVector<SDValue, 8> MemOps;
9465   SDValue FIN = Op.getOperand(1);
9466   // Store gp_offset
9467   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9468                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9469                                                MVT::i32),
9470                                FIN, MachinePointerInfo(SV), false, false, 0);
9471   MemOps.push_back(Store);
9472
9473   // Store fp_offset
9474   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9475                     FIN, DAG.getIntPtrConstant(4));
9476   Store = DAG.getStore(Op.getOperand(0), DL,
9477                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9478                                        MVT::i32),
9479                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9480   MemOps.push_back(Store);
9481
9482   // Store ptr to overflow_arg_area
9483   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9484                     FIN, DAG.getIntPtrConstant(4));
9485   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9486                                     getPointerTy());
9487   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9488                        MachinePointerInfo(SV, 8),
9489                        false, false, 0);
9490   MemOps.push_back(Store);
9491
9492   // Store ptr to reg_save_area.
9493   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9494                     FIN, DAG.getIntPtrConstant(8));
9495   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9496                                     getPointerTy());
9497   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9498                        MachinePointerInfo(SV, 16), false, false, 0);
9499   MemOps.push_back(Store);
9500   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9501                      &MemOps[0], MemOps.size());
9502 }
9503
9504 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9505   assert(Subtarget->is64Bit() &&
9506          "LowerVAARG only handles 64-bit va_arg!");
9507   assert((Subtarget->isTargetLinux() ||
9508           Subtarget->isTargetDarwin()) &&
9509           "Unhandled target in LowerVAARG");
9510   assert(Op.getNode()->getNumOperands() == 4);
9511   SDValue Chain = Op.getOperand(0);
9512   SDValue SrcPtr = Op.getOperand(1);
9513   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9514   unsigned Align = Op.getConstantOperandVal(3);
9515   DebugLoc dl = Op.getDebugLoc();
9516
9517   EVT ArgVT = Op.getNode()->getValueType(0);
9518   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9519   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9520   uint8_t ArgMode;
9521
9522   // Decide which area this value should be read from.
9523   // TODO: Implement the AMD64 ABI in its entirety. This simple
9524   // selection mechanism works only for the basic types.
9525   if (ArgVT == MVT::f80) {
9526     llvm_unreachable("va_arg for f80 not yet implemented");
9527   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9528     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9529   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9530     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9531   } else {
9532     llvm_unreachable("Unhandled argument type in LowerVAARG");
9533   }
9534
9535   if (ArgMode == 2) {
9536     // Sanity Check: Make sure using fp_offset makes sense.
9537     assert(!getTargetMachine().Options.UseSoftFloat &&
9538            !(DAG.getMachineFunction()
9539                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9540            Subtarget->hasSSE1());
9541   }
9542
9543   // Insert VAARG_64 node into the DAG
9544   // VAARG_64 returns two values: Variable Argument Address, Chain
9545   SmallVector<SDValue, 11> InstOps;
9546   InstOps.push_back(Chain);
9547   InstOps.push_back(SrcPtr);
9548   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9549   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9550   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9551   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9552   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9553                                           VTs, &InstOps[0], InstOps.size(),
9554                                           MVT::i64,
9555                                           MachinePointerInfo(SV),
9556                                           /*Align=*/0,
9557                                           /*Volatile=*/false,
9558                                           /*ReadMem=*/true,
9559                                           /*WriteMem=*/true);
9560   Chain = VAARG.getValue(1);
9561
9562   // Load the next argument and return it
9563   return DAG.getLoad(ArgVT, dl,
9564                      Chain,
9565                      VAARG,
9566                      MachinePointerInfo(),
9567                      false, false, false, 0);
9568 }
9569
9570 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9571   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9572   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9573   SDValue Chain = Op.getOperand(0);
9574   SDValue DstPtr = Op.getOperand(1);
9575   SDValue SrcPtr = Op.getOperand(2);
9576   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9577   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9578   DebugLoc DL = Op.getDebugLoc();
9579
9580   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9581                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9582                        false,
9583                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9584 }
9585
9586 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9587 // may or may not be a constant. Takes immediate version of shift as input.
9588 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9589                                    SDValue SrcOp, SDValue ShAmt,
9590                                    SelectionDAG &DAG) {
9591   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9592
9593   if (isa<ConstantSDNode>(ShAmt)) {
9594     // Constant may be a TargetConstant. Use a regular constant.
9595     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9596     switch (Opc) {
9597       default: llvm_unreachable("Unknown target vector shift node");
9598       case X86ISD::VSHLI:
9599       case X86ISD::VSRLI:
9600       case X86ISD::VSRAI:
9601         return DAG.getNode(Opc, dl, VT, SrcOp,
9602                            DAG.getConstant(ShiftAmt, MVT::i32));
9603     }
9604   }
9605
9606   // Change opcode to non-immediate version
9607   switch (Opc) {
9608     default: llvm_unreachable("Unknown target vector shift node");
9609     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9610     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9611     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9612   }
9613
9614   // Need to build a vector containing shift amount
9615   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9616   SDValue ShOps[4];
9617   ShOps[0] = ShAmt;
9618   ShOps[1] = DAG.getConstant(0, MVT::i32);
9619   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9620   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9621
9622   // The return type has to be a 128-bit type with the same element
9623   // type as the input type.
9624   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9625   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9626
9627   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9628   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9629 }
9630
9631 SDValue
9632 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9633   DebugLoc dl = Op.getDebugLoc();
9634   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9635   switch (IntNo) {
9636   default: return SDValue();    // Don't custom lower most intrinsics.
9637   // Comparison intrinsics.
9638   case Intrinsic::x86_sse_comieq_ss:
9639   case Intrinsic::x86_sse_comilt_ss:
9640   case Intrinsic::x86_sse_comile_ss:
9641   case Intrinsic::x86_sse_comigt_ss:
9642   case Intrinsic::x86_sse_comige_ss:
9643   case Intrinsic::x86_sse_comineq_ss:
9644   case Intrinsic::x86_sse_ucomieq_ss:
9645   case Intrinsic::x86_sse_ucomilt_ss:
9646   case Intrinsic::x86_sse_ucomile_ss:
9647   case Intrinsic::x86_sse_ucomigt_ss:
9648   case Intrinsic::x86_sse_ucomige_ss:
9649   case Intrinsic::x86_sse_ucomineq_ss:
9650   case Intrinsic::x86_sse2_comieq_sd:
9651   case Intrinsic::x86_sse2_comilt_sd:
9652   case Intrinsic::x86_sse2_comile_sd:
9653   case Intrinsic::x86_sse2_comigt_sd:
9654   case Intrinsic::x86_sse2_comige_sd:
9655   case Intrinsic::x86_sse2_comineq_sd:
9656   case Intrinsic::x86_sse2_ucomieq_sd:
9657   case Intrinsic::x86_sse2_ucomilt_sd:
9658   case Intrinsic::x86_sse2_ucomile_sd:
9659   case Intrinsic::x86_sse2_ucomigt_sd:
9660   case Intrinsic::x86_sse2_ucomige_sd:
9661   case Intrinsic::x86_sse2_ucomineq_sd: {
9662     unsigned Opc;
9663     ISD::CondCode CC;
9664     switch (IntNo) {
9665     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9666     case Intrinsic::x86_sse_comieq_ss:
9667     case Intrinsic::x86_sse2_comieq_sd:
9668       Opc = X86ISD::COMI;
9669       CC = ISD::SETEQ;
9670       break;
9671     case Intrinsic::x86_sse_comilt_ss:
9672     case Intrinsic::x86_sse2_comilt_sd:
9673       Opc = X86ISD::COMI;
9674       CC = ISD::SETLT;
9675       break;
9676     case Intrinsic::x86_sse_comile_ss:
9677     case Intrinsic::x86_sse2_comile_sd:
9678       Opc = X86ISD::COMI;
9679       CC = ISD::SETLE;
9680       break;
9681     case Intrinsic::x86_sse_comigt_ss:
9682     case Intrinsic::x86_sse2_comigt_sd:
9683       Opc = X86ISD::COMI;
9684       CC = ISD::SETGT;
9685       break;
9686     case Intrinsic::x86_sse_comige_ss:
9687     case Intrinsic::x86_sse2_comige_sd:
9688       Opc = X86ISD::COMI;
9689       CC = ISD::SETGE;
9690       break;
9691     case Intrinsic::x86_sse_comineq_ss:
9692     case Intrinsic::x86_sse2_comineq_sd:
9693       Opc = X86ISD::COMI;
9694       CC = ISD::SETNE;
9695       break;
9696     case Intrinsic::x86_sse_ucomieq_ss:
9697     case Intrinsic::x86_sse2_ucomieq_sd:
9698       Opc = X86ISD::UCOMI;
9699       CC = ISD::SETEQ;
9700       break;
9701     case Intrinsic::x86_sse_ucomilt_ss:
9702     case Intrinsic::x86_sse2_ucomilt_sd:
9703       Opc = X86ISD::UCOMI;
9704       CC = ISD::SETLT;
9705       break;
9706     case Intrinsic::x86_sse_ucomile_ss:
9707     case Intrinsic::x86_sse2_ucomile_sd:
9708       Opc = X86ISD::UCOMI;
9709       CC = ISD::SETLE;
9710       break;
9711     case Intrinsic::x86_sse_ucomigt_ss:
9712     case Intrinsic::x86_sse2_ucomigt_sd:
9713       Opc = X86ISD::UCOMI;
9714       CC = ISD::SETGT;
9715       break;
9716     case Intrinsic::x86_sse_ucomige_ss:
9717     case Intrinsic::x86_sse2_ucomige_sd:
9718       Opc = X86ISD::UCOMI;
9719       CC = ISD::SETGE;
9720       break;
9721     case Intrinsic::x86_sse_ucomineq_ss:
9722     case Intrinsic::x86_sse2_ucomineq_sd:
9723       Opc = X86ISD::UCOMI;
9724       CC = ISD::SETNE;
9725       break;
9726     }
9727
9728     SDValue LHS = Op.getOperand(1);
9729     SDValue RHS = Op.getOperand(2);
9730     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9731     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9732     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9733     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9734                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9735     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9736   }
9737
9738   // Arithmetic intrinsics.
9739   case Intrinsic::x86_sse2_pmulu_dq:
9740   case Intrinsic::x86_avx2_pmulu_dq:
9741     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9742                        Op.getOperand(1), Op.getOperand(2));
9743
9744   // SSE3/AVX horizontal add/sub intrinsics
9745   case Intrinsic::x86_sse3_hadd_ps:
9746   case Intrinsic::x86_sse3_hadd_pd:
9747   case Intrinsic::x86_avx_hadd_ps_256:
9748   case Intrinsic::x86_avx_hadd_pd_256:
9749   case Intrinsic::x86_sse3_hsub_ps:
9750   case Intrinsic::x86_sse3_hsub_pd:
9751   case Intrinsic::x86_avx_hsub_ps_256:
9752   case Intrinsic::x86_avx_hsub_pd_256:
9753   case Intrinsic::x86_ssse3_phadd_w_128:
9754   case Intrinsic::x86_ssse3_phadd_d_128:
9755   case Intrinsic::x86_avx2_phadd_w:
9756   case Intrinsic::x86_avx2_phadd_d:
9757   case Intrinsic::x86_ssse3_phsub_w_128:
9758   case Intrinsic::x86_ssse3_phsub_d_128:
9759   case Intrinsic::x86_avx2_phsub_w:
9760   case Intrinsic::x86_avx2_phsub_d: {
9761     unsigned Opcode;
9762     switch (IntNo) {
9763     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9764     case Intrinsic::x86_sse3_hadd_ps:
9765     case Intrinsic::x86_sse3_hadd_pd:
9766     case Intrinsic::x86_avx_hadd_ps_256:
9767     case Intrinsic::x86_avx_hadd_pd_256:
9768       Opcode = X86ISD::FHADD;
9769       break;
9770     case Intrinsic::x86_sse3_hsub_ps:
9771     case Intrinsic::x86_sse3_hsub_pd:
9772     case Intrinsic::x86_avx_hsub_ps_256:
9773     case Intrinsic::x86_avx_hsub_pd_256:
9774       Opcode = X86ISD::FHSUB;
9775       break;
9776     case Intrinsic::x86_ssse3_phadd_w_128:
9777     case Intrinsic::x86_ssse3_phadd_d_128:
9778     case Intrinsic::x86_avx2_phadd_w:
9779     case Intrinsic::x86_avx2_phadd_d:
9780       Opcode = X86ISD::HADD;
9781       break;
9782     case Intrinsic::x86_ssse3_phsub_w_128:
9783     case Intrinsic::x86_ssse3_phsub_d_128:
9784     case Intrinsic::x86_avx2_phsub_w:
9785     case Intrinsic::x86_avx2_phsub_d:
9786       Opcode = X86ISD::HSUB;
9787       break;
9788     }
9789     return DAG.getNode(Opcode, dl, Op.getValueType(),
9790                        Op.getOperand(1), Op.getOperand(2));
9791   }
9792
9793   // AVX2 variable shift intrinsics
9794   case Intrinsic::x86_avx2_psllv_d:
9795   case Intrinsic::x86_avx2_psllv_q:
9796   case Intrinsic::x86_avx2_psllv_d_256:
9797   case Intrinsic::x86_avx2_psllv_q_256:
9798   case Intrinsic::x86_avx2_psrlv_d:
9799   case Intrinsic::x86_avx2_psrlv_q:
9800   case Intrinsic::x86_avx2_psrlv_d_256:
9801   case Intrinsic::x86_avx2_psrlv_q_256:
9802   case Intrinsic::x86_avx2_psrav_d:
9803   case Intrinsic::x86_avx2_psrav_d_256: {
9804     unsigned Opcode;
9805     switch (IntNo) {
9806     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9807     case Intrinsic::x86_avx2_psllv_d:
9808     case Intrinsic::x86_avx2_psllv_q:
9809     case Intrinsic::x86_avx2_psllv_d_256:
9810     case Intrinsic::x86_avx2_psllv_q_256:
9811       Opcode = ISD::SHL;
9812       break;
9813     case Intrinsic::x86_avx2_psrlv_d:
9814     case Intrinsic::x86_avx2_psrlv_q:
9815     case Intrinsic::x86_avx2_psrlv_d_256:
9816     case Intrinsic::x86_avx2_psrlv_q_256:
9817       Opcode = ISD::SRL;
9818       break;
9819     case Intrinsic::x86_avx2_psrav_d:
9820     case Intrinsic::x86_avx2_psrav_d_256:
9821       Opcode = ISD::SRA;
9822       break;
9823     }
9824     return DAG.getNode(Opcode, dl, Op.getValueType(),
9825                        Op.getOperand(1), Op.getOperand(2));
9826   }
9827
9828   case Intrinsic::x86_ssse3_pshuf_b_128:
9829   case Intrinsic::x86_avx2_pshuf_b:
9830     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9831                        Op.getOperand(1), Op.getOperand(2));
9832
9833   case Intrinsic::x86_ssse3_psign_b_128:
9834   case Intrinsic::x86_ssse3_psign_w_128:
9835   case Intrinsic::x86_ssse3_psign_d_128:
9836   case Intrinsic::x86_avx2_psign_b:
9837   case Intrinsic::x86_avx2_psign_w:
9838   case Intrinsic::x86_avx2_psign_d:
9839     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9840                        Op.getOperand(1), Op.getOperand(2));
9841
9842   case Intrinsic::x86_sse41_insertps:
9843     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9844                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9845
9846   case Intrinsic::x86_avx_vperm2f128_ps_256:
9847   case Intrinsic::x86_avx_vperm2f128_pd_256:
9848   case Intrinsic::x86_avx_vperm2f128_si_256:
9849   case Intrinsic::x86_avx2_vperm2i128:
9850     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9851                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9852
9853   case Intrinsic::x86_avx2_permd:
9854   case Intrinsic::x86_avx2_permps:
9855     // Operands intentionally swapped. Mask is last operand to intrinsic,
9856     // but second operand for node/intruction.
9857     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9858                        Op.getOperand(2), Op.getOperand(1));
9859
9860   // ptest and testp intrinsics. The intrinsic these come from are designed to
9861   // return an integer value, not just an instruction so lower it to the ptest
9862   // or testp pattern and a setcc for the result.
9863   case Intrinsic::x86_sse41_ptestz:
9864   case Intrinsic::x86_sse41_ptestc:
9865   case Intrinsic::x86_sse41_ptestnzc:
9866   case Intrinsic::x86_avx_ptestz_256:
9867   case Intrinsic::x86_avx_ptestc_256:
9868   case Intrinsic::x86_avx_ptestnzc_256:
9869   case Intrinsic::x86_avx_vtestz_ps:
9870   case Intrinsic::x86_avx_vtestc_ps:
9871   case Intrinsic::x86_avx_vtestnzc_ps:
9872   case Intrinsic::x86_avx_vtestz_pd:
9873   case Intrinsic::x86_avx_vtestc_pd:
9874   case Intrinsic::x86_avx_vtestnzc_pd:
9875   case Intrinsic::x86_avx_vtestz_ps_256:
9876   case Intrinsic::x86_avx_vtestc_ps_256:
9877   case Intrinsic::x86_avx_vtestnzc_ps_256:
9878   case Intrinsic::x86_avx_vtestz_pd_256:
9879   case Intrinsic::x86_avx_vtestc_pd_256:
9880   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9881     bool IsTestPacked = false;
9882     unsigned X86CC;
9883     switch (IntNo) {
9884     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9885     case Intrinsic::x86_avx_vtestz_ps:
9886     case Intrinsic::x86_avx_vtestz_pd:
9887     case Intrinsic::x86_avx_vtestz_ps_256:
9888     case Intrinsic::x86_avx_vtestz_pd_256:
9889       IsTestPacked = true; // Fallthrough
9890     case Intrinsic::x86_sse41_ptestz:
9891     case Intrinsic::x86_avx_ptestz_256:
9892       // ZF = 1
9893       X86CC = X86::COND_E;
9894       break;
9895     case Intrinsic::x86_avx_vtestc_ps:
9896     case Intrinsic::x86_avx_vtestc_pd:
9897     case Intrinsic::x86_avx_vtestc_ps_256:
9898     case Intrinsic::x86_avx_vtestc_pd_256:
9899       IsTestPacked = true; // Fallthrough
9900     case Intrinsic::x86_sse41_ptestc:
9901     case Intrinsic::x86_avx_ptestc_256:
9902       // CF = 1
9903       X86CC = X86::COND_B;
9904       break;
9905     case Intrinsic::x86_avx_vtestnzc_ps:
9906     case Intrinsic::x86_avx_vtestnzc_pd:
9907     case Intrinsic::x86_avx_vtestnzc_ps_256:
9908     case Intrinsic::x86_avx_vtestnzc_pd_256:
9909       IsTestPacked = true; // Fallthrough
9910     case Intrinsic::x86_sse41_ptestnzc:
9911     case Intrinsic::x86_avx_ptestnzc_256:
9912       // ZF and CF = 0
9913       X86CC = X86::COND_A;
9914       break;
9915     }
9916
9917     SDValue LHS = Op.getOperand(1);
9918     SDValue RHS = Op.getOperand(2);
9919     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9920     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9921     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9922     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9923     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9924   }
9925
9926   // SSE/AVX shift intrinsics
9927   case Intrinsic::x86_sse2_psll_w:
9928   case Intrinsic::x86_sse2_psll_d:
9929   case Intrinsic::x86_sse2_psll_q:
9930   case Intrinsic::x86_avx2_psll_w:
9931   case Intrinsic::x86_avx2_psll_d:
9932   case Intrinsic::x86_avx2_psll_q:
9933   case Intrinsic::x86_sse2_psrl_w:
9934   case Intrinsic::x86_sse2_psrl_d:
9935   case Intrinsic::x86_sse2_psrl_q:
9936   case Intrinsic::x86_avx2_psrl_w:
9937   case Intrinsic::x86_avx2_psrl_d:
9938   case Intrinsic::x86_avx2_psrl_q:
9939   case Intrinsic::x86_sse2_psra_w:
9940   case Intrinsic::x86_sse2_psra_d:
9941   case Intrinsic::x86_avx2_psra_w:
9942   case Intrinsic::x86_avx2_psra_d: {
9943     unsigned Opcode;
9944     switch (IntNo) {
9945     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9946     case Intrinsic::x86_sse2_psll_w:
9947     case Intrinsic::x86_sse2_psll_d:
9948     case Intrinsic::x86_sse2_psll_q:
9949     case Intrinsic::x86_avx2_psll_w:
9950     case Intrinsic::x86_avx2_psll_d:
9951     case Intrinsic::x86_avx2_psll_q:
9952       Opcode = X86ISD::VSHL;
9953       break;
9954     case Intrinsic::x86_sse2_psrl_w:
9955     case Intrinsic::x86_sse2_psrl_d:
9956     case Intrinsic::x86_sse2_psrl_q:
9957     case Intrinsic::x86_avx2_psrl_w:
9958     case Intrinsic::x86_avx2_psrl_d:
9959     case Intrinsic::x86_avx2_psrl_q:
9960       Opcode = X86ISD::VSRL;
9961       break;
9962     case Intrinsic::x86_sse2_psra_w:
9963     case Intrinsic::x86_sse2_psra_d:
9964     case Intrinsic::x86_avx2_psra_w:
9965     case Intrinsic::x86_avx2_psra_d:
9966       Opcode = X86ISD::VSRA;
9967       break;
9968     }
9969     return DAG.getNode(Opcode, dl, Op.getValueType(),
9970                        Op.getOperand(1), Op.getOperand(2));
9971   }
9972
9973   // SSE/AVX immediate shift intrinsics
9974   case Intrinsic::x86_sse2_pslli_w:
9975   case Intrinsic::x86_sse2_pslli_d:
9976   case Intrinsic::x86_sse2_pslli_q:
9977   case Intrinsic::x86_avx2_pslli_w:
9978   case Intrinsic::x86_avx2_pslli_d:
9979   case Intrinsic::x86_avx2_pslli_q:
9980   case Intrinsic::x86_sse2_psrli_w:
9981   case Intrinsic::x86_sse2_psrli_d:
9982   case Intrinsic::x86_sse2_psrli_q:
9983   case Intrinsic::x86_avx2_psrli_w:
9984   case Intrinsic::x86_avx2_psrli_d:
9985   case Intrinsic::x86_avx2_psrli_q:
9986   case Intrinsic::x86_sse2_psrai_w:
9987   case Intrinsic::x86_sse2_psrai_d:
9988   case Intrinsic::x86_avx2_psrai_w:
9989   case Intrinsic::x86_avx2_psrai_d: {
9990     unsigned Opcode;
9991     switch (IntNo) {
9992     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9993     case Intrinsic::x86_sse2_pslli_w:
9994     case Intrinsic::x86_sse2_pslli_d:
9995     case Intrinsic::x86_sse2_pslli_q:
9996     case Intrinsic::x86_avx2_pslli_w:
9997     case Intrinsic::x86_avx2_pslli_d:
9998     case Intrinsic::x86_avx2_pslli_q:
9999       Opcode = X86ISD::VSHLI;
10000       break;
10001     case Intrinsic::x86_sse2_psrli_w:
10002     case Intrinsic::x86_sse2_psrli_d:
10003     case Intrinsic::x86_sse2_psrli_q:
10004     case Intrinsic::x86_avx2_psrli_w:
10005     case Intrinsic::x86_avx2_psrli_d:
10006     case Intrinsic::x86_avx2_psrli_q:
10007       Opcode = X86ISD::VSRLI;
10008       break;
10009     case Intrinsic::x86_sse2_psrai_w:
10010     case Intrinsic::x86_sse2_psrai_d:
10011     case Intrinsic::x86_avx2_psrai_w:
10012     case Intrinsic::x86_avx2_psrai_d:
10013       Opcode = X86ISD::VSRAI;
10014       break;
10015     }
10016     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10017                                Op.getOperand(1), Op.getOperand(2), DAG);
10018   }
10019
10020   case Intrinsic::x86_sse42_pcmpistria128:
10021   case Intrinsic::x86_sse42_pcmpestria128:
10022   case Intrinsic::x86_sse42_pcmpistric128:
10023   case Intrinsic::x86_sse42_pcmpestric128:
10024   case Intrinsic::x86_sse42_pcmpistrio128:
10025   case Intrinsic::x86_sse42_pcmpestrio128:
10026   case Intrinsic::x86_sse42_pcmpistris128:
10027   case Intrinsic::x86_sse42_pcmpestris128:
10028   case Intrinsic::x86_sse42_pcmpistriz128:
10029   case Intrinsic::x86_sse42_pcmpestriz128: {
10030     unsigned Opcode;
10031     unsigned X86CC;
10032     switch (IntNo) {
10033     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10034     case Intrinsic::x86_sse42_pcmpistria128:
10035       Opcode = X86ISD::PCMPISTRI;
10036       X86CC = X86::COND_A;
10037       break;
10038     case Intrinsic::x86_sse42_pcmpestria128:
10039       Opcode = X86ISD::PCMPESTRI;
10040       X86CC = X86::COND_A;
10041       break;
10042     case Intrinsic::x86_sse42_pcmpistric128:
10043       Opcode = X86ISD::PCMPISTRI;
10044       X86CC = X86::COND_B;
10045       break;
10046     case Intrinsic::x86_sse42_pcmpestric128:
10047       Opcode = X86ISD::PCMPESTRI;
10048       X86CC = X86::COND_B;
10049       break;
10050     case Intrinsic::x86_sse42_pcmpistrio128:
10051       Opcode = X86ISD::PCMPISTRI;
10052       X86CC = X86::COND_O;
10053       break;
10054     case Intrinsic::x86_sse42_pcmpestrio128:
10055       Opcode = X86ISD::PCMPESTRI;
10056       X86CC = X86::COND_O;
10057       break;
10058     case Intrinsic::x86_sse42_pcmpistris128:
10059       Opcode = X86ISD::PCMPISTRI;
10060       X86CC = X86::COND_S;
10061       break;
10062     case Intrinsic::x86_sse42_pcmpestris128:
10063       Opcode = X86ISD::PCMPESTRI;
10064       X86CC = X86::COND_S;
10065       break;
10066     case Intrinsic::x86_sse42_pcmpistriz128:
10067       Opcode = X86ISD::PCMPISTRI;
10068       X86CC = X86::COND_E;
10069       break;
10070     case Intrinsic::x86_sse42_pcmpestriz128:
10071       Opcode = X86ISD::PCMPESTRI;
10072       X86CC = X86::COND_E;
10073       break;
10074     }
10075     SmallVector<SDValue, 5> NewOps;
10076     NewOps.append(Op->op_begin()+1, Op->op_end());
10077     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10078     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10079     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10080                                 DAG.getConstant(X86CC, MVT::i8),
10081                                 SDValue(PCMP.getNode(), 1));
10082     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10083   }
10084
10085   case Intrinsic::x86_sse42_pcmpistri128:
10086   case Intrinsic::x86_sse42_pcmpestri128: {
10087     unsigned Opcode;
10088     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10089       Opcode = X86ISD::PCMPISTRI;
10090     else
10091       Opcode = X86ISD::PCMPESTRI;
10092
10093     SmallVector<SDValue, 5> NewOps;
10094     NewOps.append(Op->op_begin()+1, Op->op_end());
10095     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10096     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10097   }
10098   case Intrinsic::x86_fma_vfmadd_ps:
10099   case Intrinsic::x86_fma_vfmadd_pd:
10100   case Intrinsic::x86_fma_vfmsub_ps:
10101   case Intrinsic::x86_fma_vfmsub_pd:
10102   case Intrinsic::x86_fma_vfnmadd_ps:
10103   case Intrinsic::x86_fma_vfnmadd_pd:
10104   case Intrinsic::x86_fma_vfnmsub_ps:
10105   case Intrinsic::x86_fma_vfnmsub_pd:
10106   case Intrinsic::x86_fma_vfmaddsub_ps:
10107   case Intrinsic::x86_fma_vfmaddsub_pd:
10108   case Intrinsic::x86_fma_vfmsubadd_ps:
10109   case Intrinsic::x86_fma_vfmsubadd_pd:
10110   case Intrinsic::x86_fma_vfmadd_ps_256:
10111   case Intrinsic::x86_fma_vfmadd_pd_256:
10112   case Intrinsic::x86_fma_vfmsub_ps_256:
10113   case Intrinsic::x86_fma_vfmsub_pd_256:
10114   case Intrinsic::x86_fma_vfnmadd_ps_256:
10115   case Intrinsic::x86_fma_vfnmadd_pd_256:
10116   case Intrinsic::x86_fma_vfnmsub_ps_256:
10117   case Intrinsic::x86_fma_vfnmsub_pd_256:
10118   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10119   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10120   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10121   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10122     unsigned Opc;
10123     switch (IntNo) {
10124     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10125     case Intrinsic::x86_fma_vfmadd_ps:
10126     case Intrinsic::x86_fma_vfmadd_pd:
10127     case Intrinsic::x86_fma_vfmadd_ps_256:
10128     case Intrinsic::x86_fma_vfmadd_pd_256:
10129       Opc = X86ISD::FMADD;
10130       break;
10131     case Intrinsic::x86_fma_vfmsub_ps:
10132     case Intrinsic::x86_fma_vfmsub_pd:
10133     case Intrinsic::x86_fma_vfmsub_ps_256:
10134     case Intrinsic::x86_fma_vfmsub_pd_256:
10135       Opc = X86ISD::FMSUB;
10136       break;
10137     case Intrinsic::x86_fma_vfnmadd_ps:
10138     case Intrinsic::x86_fma_vfnmadd_pd:
10139     case Intrinsic::x86_fma_vfnmadd_ps_256:
10140     case Intrinsic::x86_fma_vfnmadd_pd_256:
10141       Opc = X86ISD::FNMADD;
10142       break;
10143     case Intrinsic::x86_fma_vfnmsub_ps:
10144     case Intrinsic::x86_fma_vfnmsub_pd:
10145     case Intrinsic::x86_fma_vfnmsub_ps_256:
10146     case Intrinsic::x86_fma_vfnmsub_pd_256:
10147       Opc = X86ISD::FNMSUB;
10148       break;
10149     case Intrinsic::x86_fma_vfmaddsub_ps:
10150     case Intrinsic::x86_fma_vfmaddsub_pd:
10151     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10152     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10153       Opc = X86ISD::FMADDSUB;
10154       break;
10155     case Intrinsic::x86_fma_vfmsubadd_ps:
10156     case Intrinsic::x86_fma_vfmsubadd_pd:
10157     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10158     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10159       Opc = X86ISD::FMSUBADD;
10160       break;
10161     }
10162
10163     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10164                        Op.getOperand(2), Op.getOperand(3));
10165   }
10166   }
10167 }
10168
10169 SDValue
10170 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10171   DebugLoc dl = Op.getDebugLoc();
10172   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10173   switch (IntNo) {
10174   default: return SDValue();    // Don't custom lower most intrinsics.
10175
10176   // RDRAND intrinsics.
10177   case Intrinsic::x86_rdrand_16:
10178   case Intrinsic::x86_rdrand_32:
10179   case Intrinsic::x86_rdrand_64: {
10180     // Emit the node with the right value type.
10181     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10182     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10183
10184     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10185     // return the value from Rand, which is always 0, casted to i32.
10186     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10187                       DAG.getConstant(1, Op->getValueType(1)),
10188                       DAG.getConstant(X86::COND_B, MVT::i32),
10189                       SDValue(Result.getNode(), 1) };
10190     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10191                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10192                                   Ops, 4);
10193
10194     // Return { result, isValid, chain }.
10195     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10196                        SDValue(Result.getNode(), 2));
10197   }
10198   }
10199 }
10200
10201 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10202                                            SelectionDAG &DAG) const {
10203   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10204   MFI->setReturnAddressIsTaken(true);
10205
10206   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10207   DebugLoc dl = Op.getDebugLoc();
10208
10209   if (Depth > 0) {
10210     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10211     SDValue Offset =
10212       DAG.getConstant(TD->getPointerSize(),
10213                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10214     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10215                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10216                                    FrameAddr, Offset),
10217                        MachinePointerInfo(), false, false, false, 0);
10218   }
10219
10220   // Just load the return address.
10221   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10222   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10223                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10224 }
10225
10226 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10227   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10228   MFI->setFrameAddressIsTaken(true);
10229
10230   EVT VT = Op.getValueType();
10231   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10232   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10233   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10234   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10235   while (Depth--)
10236     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10237                             MachinePointerInfo(),
10238                             false, false, false, 0);
10239   return FrameAddr;
10240 }
10241
10242 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10243                                                      SelectionDAG &DAG) const {
10244   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10245 }
10246
10247 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10248   SDValue Chain     = Op.getOperand(0);
10249   SDValue Offset    = Op.getOperand(1);
10250   SDValue Handler   = Op.getOperand(2);
10251   DebugLoc dl       = Op.getDebugLoc();
10252
10253   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10254                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10255                                      getPointerTy());
10256   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10257
10258   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10259                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10260   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10261   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10262                        false, false, 0);
10263   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10264
10265   return DAG.getNode(X86ISD::EH_RETURN, dl,
10266                      MVT::Other,
10267                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10268 }
10269
10270 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10271                                                   SelectionDAG &DAG) const {
10272   return Op.getOperand(0);
10273 }
10274
10275 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10276                                                 SelectionDAG &DAG) const {
10277   SDValue Root = Op.getOperand(0);
10278   SDValue Trmp = Op.getOperand(1); // trampoline
10279   SDValue FPtr = Op.getOperand(2); // nested function
10280   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10281   DebugLoc dl  = Op.getDebugLoc();
10282
10283   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10284
10285   if (Subtarget->is64Bit()) {
10286     SDValue OutChains[6];
10287
10288     // Large code-model.
10289     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10290     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10291
10292     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10293     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10294
10295     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10296
10297     // Load the pointer to the nested function into R11.
10298     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10299     SDValue Addr = Trmp;
10300     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10301                                 Addr, MachinePointerInfo(TrmpAddr),
10302                                 false, false, 0);
10303
10304     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10305                        DAG.getConstant(2, MVT::i64));
10306     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10307                                 MachinePointerInfo(TrmpAddr, 2),
10308                                 false, false, 2);
10309
10310     // Load the 'nest' parameter value into R10.
10311     // R10 is specified in X86CallingConv.td
10312     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10313     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10314                        DAG.getConstant(10, MVT::i64));
10315     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10316                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10317                                 false, false, 0);
10318
10319     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10320                        DAG.getConstant(12, MVT::i64));
10321     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10322                                 MachinePointerInfo(TrmpAddr, 12),
10323                                 false, false, 2);
10324
10325     // Jump to the nested function.
10326     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10327     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10328                        DAG.getConstant(20, MVT::i64));
10329     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10330                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10331                                 false, false, 0);
10332
10333     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10334     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10335                        DAG.getConstant(22, MVT::i64));
10336     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10337                                 MachinePointerInfo(TrmpAddr, 22),
10338                                 false, false, 0);
10339
10340     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10341   } else {
10342     const Function *Func =
10343       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10344     CallingConv::ID CC = Func->getCallingConv();
10345     unsigned NestReg;
10346
10347     switch (CC) {
10348     default:
10349       llvm_unreachable("Unsupported calling convention");
10350     case CallingConv::C:
10351     case CallingConv::X86_StdCall: {
10352       // Pass 'nest' parameter in ECX.
10353       // Must be kept in sync with X86CallingConv.td
10354       NestReg = X86::ECX;
10355
10356       // Check that ECX wasn't needed by an 'inreg' parameter.
10357       FunctionType *FTy = Func->getFunctionType();
10358       const AttrListPtr &Attrs = Func->getAttributes();
10359
10360       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10361         unsigned InRegCount = 0;
10362         unsigned Idx = 1;
10363
10364         for (FunctionType::param_iterator I = FTy->param_begin(),
10365              E = FTy->param_end(); I != E; ++I, ++Idx)
10366           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10367             // FIXME: should only count parameters that are lowered to integers.
10368             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10369
10370         if (InRegCount > 2) {
10371           report_fatal_error("Nest register in use - reduce number of inreg"
10372                              " parameters!");
10373         }
10374       }
10375       break;
10376     }
10377     case CallingConv::X86_FastCall:
10378     case CallingConv::X86_ThisCall:
10379     case CallingConv::Fast:
10380       // Pass 'nest' parameter in EAX.
10381       // Must be kept in sync with X86CallingConv.td
10382       NestReg = X86::EAX;
10383       break;
10384     }
10385
10386     SDValue OutChains[4];
10387     SDValue Addr, Disp;
10388
10389     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10390                        DAG.getConstant(10, MVT::i32));
10391     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10392
10393     // This is storing the opcode for MOV32ri.
10394     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10395     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10396     OutChains[0] = DAG.getStore(Root, dl,
10397                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10398                                 Trmp, MachinePointerInfo(TrmpAddr),
10399                                 false, false, 0);
10400
10401     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10402                        DAG.getConstant(1, MVT::i32));
10403     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10404                                 MachinePointerInfo(TrmpAddr, 1),
10405                                 false, false, 1);
10406
10407     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10408     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10409                        DAG.getConstant(5, MVT::i32));
10410     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10411                                 MachinePointerInfo(TrmpAddr, 5),
10412                                 false, false, 1);
10413
10414     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10415                        DAG.getConstant(6, MVT::i32));
10416     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10417                                 MachinePointerInfo(TrmpAddr, 6),
10418                                 false, false, 1);
10419
10420     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10421   }
10422 }
10423
10424 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10425                                             SelectionDAG &DAG) const {
10426   /*
10427    The rounding mode is in bits 11:10 of FPSR, and has the following
10428    settings:
10429      00 Round to nearest
10430      01 Round to -inf
10431      10 Round to +inf
10432      11 Round to 0
10433
10434   FLT_ROUNDS, on the other hand, expects the following:
10435     -1 Undefined
10436      0 Round to 0
10437      1 Round to nearest
10438      2 Round to +inf
10439      3 Round to -inf
10440
10441   To perform the conversion, we do:
10442     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10443   */
10444
10445   MachineFunction &MF = DAG.getMachineFunction();
10446   const TargetMachine &TM = MF.getTarget();
10447   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10448   unsigned StackAlignment = TFI.getStackAlignment();
10449   EVT VT = Op.getValueType();
10450   DebugLoc DL = Op.getDebugLoc();
10451
10452   // Save FP Control Word to stack slot
10453   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10454   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10455
10456
10457   MachineMemOperand *MMO =
10458    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10459                            MachineMemOperand::MOStore, 2, 2);
10460
10461   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10462   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10463                                           DAG.getVTList(MVT::Other),
10464                                           Ops, 2, MVT::i16, MMO);
10465
10466   // Load FP Control Word from stack slot
10467   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10468                             MachinePointerInfo(), false, false, false, 0);
10469
10470   // Transform as necessary
10471   SDValue CWD1 =
10472     DAG.getNode(ISD::SRL, DL, MVT::i16,
10473                 DAG.getNode(ISD::AND, DL, MVT::i16,
10474                             CWD, DAG.getConstant(0x800, MVT::i16)),
10475                 DAG.getConstant(11, MVT::i8));
10476   SDValue CWD2 =
10477     DAG.getNode(ISD::SRL, DL, MVT::i16,
10478                 DAG.getNode(ISD::AND, DL, MVT::i16,
10479                             CWD, DAG.getConstant(0x400, MVT::i16)),
10480                 DAG.getConstant(9, MVT::i8));
10481
10482   SDValue RetVal =
10483     DAG.getNode(ISD::AND, DL, MVT::i16,
10484                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10485                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10486                             DAG.getConstant(1, MVT::i16)),
10487                 DAG.getConstant(3, MVT::i16));
10488
10489
10490   return DAG.getNode((VT.getSizeInBits() < 16 ?
10491                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10492 }
10493
10494 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10495   EVT VT = Op.getValueType();
10496   EVT OpVT = VT;
10497   unsigned NumBits = VT.getSizeInBits();
10498   DebugLoc dl = Op.getDebugLoc();
10499
10500   Op = Op.getOperand(0);
10501   if (VT == MVT::i8) {
10502     // Zero extend to i32 since there is not an i8 bsr.
10503     OpVT = MVT::i32;
10504     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10505   }
10506
10507   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10508   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10509   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10510
10511   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10512   SDValue Ops[] = {
10513     Op,
10514     DAG.getConstant(NumBits+NumBits-1, OpVT),
10515     DAG.getConstant(X86::COND_E, MVT::i8),
10516     Op.getValue(1)
10517   };
10518   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10519
10520   // Finally xor with NumBits-1.
10521   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10522
10523   if (VT == MVT::i8)
10524     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10525   return Op;
10526 }
10527
10528 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10529                                                 SelectionDAG &DAG) const {
10530   EVT VT = Op.getValueType();
10531   EVT OpVT = VT;
10532   unsigned NumBits = VT.getSizeInBits();
10533   DebugLoc dl = Op.getDebugLoc();
10534
10535   Op = Op.getOperand(0);
10536   if (VT == MVT::i8) {
10537     // Zero extend to i32 since there is not an i8 bsr.
10538     OpVT = MVT::i32;
10539     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10540   }
10541
10542   // Issue a bsr (scan bits in reverse).
10543   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10544   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10545
10546   // And xor with NumBits-1.
10547   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10548
10549   if (VT == MVT::i8)
10550     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10551   return Op;
10552 }
10553
10554 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10555   EVT VT = Op.getValueType();
10556   unsigned NumBits = VT.getSizeInBits();
10557   DebugLoc dl = Op.getDebugLoc();
10558   Op = Op.getOperand(0);
10559
10560   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10561   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10562   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10563
10564   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10565   SDValue Ops[] = {
10566     Op,
10567     DAG.getConstant(NumBits, VT),
10568     DAG.getConstant(X86::COND_E, MVT::i8),
10569     Op.getValue(1)
10570   };
10571   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10572 }
10573
10574 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10575 // ones, and then concatenate the result back.
10576 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10577   EVT VT = Op.getValueType();
10578
10579   assert(VT.is256BitVector() && VT.isInteger() &&
10580          "Unsupported value type for operation");
10581
10582   unsigned NumElems = VT.getVectorNumElements();
10583   DebugLoc dl = Op.getDebugLoc();
10584
10585   // Extract the LHS vectors
10586   SDValue LHS = Op.getOperand(0);
10587   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10588   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10589
10590   // Extract the RHS vectors
10591   SDValue RHS = Op.getOperand(1);
10592   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10593   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10594
10595   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10596   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10597
10598   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10599                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10600                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10601 }
10602
10603 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10604   assert(Op.getValueType().is256BitVector() &&
10605          Op.getValueType().isInteger() &&
10606          "Only handle AVX 256-bit vector integer operation");
10607   return Lower256IntArith(Op, DAG);
10608 }
10609
10610 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10611   assert(Op.getValueType().is256BitVector() &&
10612          Op.getValueType().isInteger() &&
10613          "Only handle AVX 256-bit vector integer operation");
10614   return Lower256IntArith(Op, DAG);
10615 }
10616
10617 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10618   EVT VT = Op.getValueType();
10619
10620   // Decompose 256-bit ops into smaller 128-bit ops.
10621   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10622     return Lower256IntArith(Op, DAG);
10623
10624   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10625          "Only know how to lower V2I64/V4I64 multiply");
10626
10627   DebugLoc dl = Op.getDebugLoc();
10628
10629   //  Ahi = psrlqi(a, 32);
10630   //  Bhi = psrlqi(b, 32);
10631   //
10632   //  AloBlo = pmuludq(a, b);
10633   //  AloBhi = pmuludq(a, Bhi);
10634   //  AhiBlo = pmuludq(Ahi, b);
10635
10636   //  AloBhi = psllqi(AloBhi, 32);
10637   //  AhiBlo = psllqi(AhiBlo, 32);
10638   //  return AloBlo + AloBhi + AhiBlo;
10639
10640   SDValue A = Op.getOperand(0);
10641   SDValue B = Op.getOperand(1);
10642
10643   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10644
10645   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10646   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10647
10648   // Bit cast to 32-bit vectors for MULUDQ
10649   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10650   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10651   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10652   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10653   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10654
10655   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10656   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10657   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10658
10659   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10660   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10661
10662   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10663   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10664 }
10665
10666 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10667
10668   EVT VT = Op.getValueType();
10669   DebugLoc dl = Op.getDebugLoc();
10670   SDValue R = Op.getOperand(0);
10671   SDValue Amt = Op.getOperand(1);
10672   LLVMContext *Context = DAG.getContext();
10673
10674   if (!Subtarget->hasSSE2())
10675     return SDValue();
10676
10677   // Optimize shl/srl/sra with constant shift amount.
10678   if (isSplatVector(Amt.getNode())) {
10679     SDValue SclrAmt = Amt->getOperand(0);
10680     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10681       uint64_t ShiftAmt = C->getZExtValue();
10682
10683       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10684           (Subtarget->hasAVX2() &&
10685            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10686         if (Op.getOpcode() == ISD::SHL)
10687           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10688                              DAG.getConstant(ShiftAmt, MVT::i32));
10689         if (Op.getOpcode() == ISD::SRL)
10690           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10691                              DAG.getConstant(ShiftAmt, MVT::i32));
10692         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10693           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10694                              DAG.getConstant(ShiftAmt, MVT::i32));
10695       }
10696
10697       if (VT == MVT::v16i8) {
10698         if (Op.getOpcode() == ISD::SHL) {
10699           // Make a large shift.
10700           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10701                                     DAG.getConstant(ShiftAmt, MVT::i32));
10702           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10703           // Zero out the rightmost bits.
10704           SmallVector<SDValue, 16> V(16,
10705                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10706                                                      MVT::i8));
10707           return DAG.getNode(ISD::AND, dl, VT, SHL,
10708                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10709         }
10710         if (Op.getOpcode() == ISD::SRL) {
10711           // Make a large shift.
10712           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10713                                     DAG.getConstant(ShiftAmt, MVT::i32));
10714           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10715           // Zero out the leftmost bits.
10716           SmallVector<SDValue, 16> V(16,
10717                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10718                                                      MVT::i8));
10719           return DAG.getNode(ISD::AND, dl, VT, SRL,
10720                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10721         }
10722         if (Op.getOpcode() == ISD::SRA) {
10723           if (ShiftAmt == 7) {
10724             // R s>> 7  ===  R s< 0
10725             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10726             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10727           }
10728
10729           // R s>> a === ((R u>> a) ^ m) - m
10730           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10731           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10732                                                          MVT::i8));
10733           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10734           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10735           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10736           return Res;
10737         }
10738         llvm_unreachable("Unknown shift opcode.");
10739       }
10740
10741       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10742         if (Op.getOpcode() == ISD::SHL) {
10743           // Make a large shift.
10744           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10745                                     DAG.getConstant(ShiftAmt, MVT::i32));
10746           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10747           // Zero out the rightmost bits.
10748           SmallVector<SDValue, 32> V(32,
10749                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10750                                                      MVT::i8));
10751           return DAG.getNode(ISD::AND, dl, VT, SHL,
10752                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10753         }
10754         if (Op.getOpcode() == ISD::SRL) {
10755           // Make a large shift.
10756           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10757                                     DAG.getConstant(ShiftAmt, MVT::i32));
10758           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10759           // Zero out the leftmost bits.
10760           SmallVector<SDValue, 32> V(32,
10761                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10762                                                      MVT::i8));
10763           return DAG.getNode(ISD::AND, dl, VT, SRL,
10764                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10765         }
10766         if (Op.getOpcode() == ISD::SRA) {
10767           if (ShiftAmt == 7) {
10768             // R s>> 7  ===  R s< 0
10769             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10770             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10771           }
10772
10773           // R s>> a === ((R u>> a) ^ m) - m
10774           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10775           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10776                                                          MVT::i8));
10777           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10778           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10779           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10780           return Res;
10781         }
10782         llvm_unreachable("Unknown shift opcode.");
10783       }
10784     }
10785   }
10786
10787   // Lower SHL with variable shift amount.
10788   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10789     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10790                      DAG.getConstant(23, MVT::i32));
10791
10792     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10793     Constant *C = ConstantDataVector::get(*Context, CV);
10794     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10795     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10796                                  MachinePointerInfo::getConstantPool(),
10797                                  false, false, false, 16);
10798
10799     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10800     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10801     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10802     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10803   }
10804   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10805     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10806
10807     // a = a << 5;
10808     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10809                      DAG.getConstant(5, MVT::i32));
10810     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10811
10812     // Turn 'a' into a mask suitable for VSELECT
10813     SDValue VSelM = DAG.getConstant(0x80, VT);
10814     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10815     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10816
10817     SDValue CM1 = DAG.getConstant(0x0f, VT);
10818     SDValue CM2 = DAG.getConstant(0x3f, VT);
10819
10820     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10821     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10822     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10823                             DAG.getConstant(4, MVT::i32), DAG);
10824     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10825     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10826
10827     // a += a
10828     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10829     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10830     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10831
10832     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10833     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10834     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10835                             DAG.getConstant(2, MVT::i32), DAG);
10836     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10837     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10838
10839     // a += a
10840     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10841     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10842     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10843
10844     // return VSELECT(r, r+r, a);
10845     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10846                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10847     return R;
10848   }
10849
10850   // Decompose 256-bit shifts into smaller 128-bit shifts.
10851   if (VT.is256BitVector()) {
10852     unsigned NumElems = VT.getVectorNumElements();
10853     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10854     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10855
10856     // Extract the two vectors
10857     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10858     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10859
10860     // Recreate the shift amount vectors
10861     SDValue Amt1, Amt2;
10862     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10863       // Constant shift amount
10864       SmallVector<SDValue, 4> Amt1Csts;
10865       SmallVector<SDValue, 4> Amt2Csts;
10866       for (unsigned i = 0; i != NumElems/2; ++i)
10867         Amt1Csts.push_back(Amt->getOperand(i));
10868       for (unsigned i = NumElems/2; i != NumElems; ++i)
10869         Amt2Csts.push_back(Amt->getOperand(i));
10870
10871       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10872                                  &Amt1Csts[0], NumElems/2);
10873       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10874                                  &Amt2Csts[0], NumElems/2);
10875     } else {
10876       // Variable shift amount
10877       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10878       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10879     }
10880
10881     // Issue new vector shifts for the smaller types
10882     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10883     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10884
10885     // Concatenate the result back
10886     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10887   }
10888
10889   return SDValue();
10890 }
10891
10892 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10893   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10894   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10895   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10896   // has only one use.
10897   SDNode *N = Op.getNode();
10898   SDValue LHS = N->getOperand(0);
10899   SDValue RHS = N->getOperand(1);
10900   unsigned BaseOp = 0;
10901   unsigned Cond = 0;
10902   DebugLoc DL = Op.getDebugLoc();
10903   switch (Op.getOpcode()) {
10904   default: llvm_unreachable("Unknown ovf instruction!");
10905   case ISD::SADDO:
10906     // A subtract of one will be selected as a INC. Note that INC doesn't
10907     // set CF, so we can't do this for UADDO.
10908     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10909       if (C->isOne()) {
10910         BaseOp = X86ISD::INC;
10911         Cond = X86::COND_O;
10912         break;
10913       }
10914     BaseOp = X86ISD::ADD;
10915     Cond = X86::COND_O;
10916     break;
10917   case ISD::UADDO:
10918     BaseOp = X86ISD::ADD;
10919     Cond = X86::COND_B;
10920     break;
10921   case ISD::SSUBO:
10922     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10923     // set CF, so we can't do this for USUBO.
10924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10925       if (C->isOne()) {
10926         BaseOp = X86ISD::DEC;
10927         Cond = X86::COND_O;
10928         break;
10929       }
10930     BaseOp = X86ISD::SUB;
10931     Cond = X86::COND_O;
10932     break;
10933   case ISD::USUBO:
10934     BaseOp = X86ISD::SUB;
10935     Cond = X86::COND_B;
10936     break;
10937   case ISD::SMULO:
10938     BaseOp = X86ISD::SMUL;
10939     Cond = X86::COND_O;
10940     break;
10941   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10942     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10943                                  MVT::i32);
10944     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10945
10946     SDValue SetCC =
10947       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10948                   DAG.getConstant(X86::COND_O, MVT::i32),
10949                   SDValue(Sum.getNode(), 2));
10950
10951     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10952   }
10953   }
10954
10955   // Also sets EFLAGS.
10956   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10957   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10958
10959   SDValue SetCC =
10960     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10961                 DAG.getConstant(Cond, MVT::i32),
10962                 SDValue(Sum.getNode(), 1));
10963
10964   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10965 }
10966
10967 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10968                                                   SelectionDAG &DAG) const {
10969   DebugLoc dl = Op.getDebugLoc();
10970   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10971   EVT VT = Op.getValueType();
10972
10973   if (!Subtarget->hasSSE2() || !VT.isVector())
10974     return SDValue();
10975
10976   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10977                       ExtraVT.getScalarType().getSizeInBits();
10978   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10979
10980   switch (VT.getSimpleVT().SimpleTy) {
10981     default: return SDValue();
10982     case MVT::v8i32:
10983     case MVT::v16i16:
10984       if (!Subtarget->hasAVX())
10985         return SDValue();
10986       if (!Subtarget->hasAVX2()) {
10987         // needs to be split
10988         unsigned NumElems = VT.getVectorNumElements();
10989
10990         // Extract the LHS vectors
10991         SDValue LHS = Op.getOperand(0);
10992         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10993         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10994
10995         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10996         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10997
10998         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10999         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11000         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11001                                    ExtraNumElems/2);
11002         SDValue Extra = DAG.getValueType(ExtraVT);
11003
11004         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11005         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11006
11007         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
11008       }
11009       // fall through
11010     case MVT::v4i32:
11011     case MVT::v8i16: {
11012       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11013                                          Op.getOperand(0), ShAmt, DAG);
11014       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11015     }
11016   }
11017 }
11018
11019
11020 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
11021   DebugLoc dl = Op.getDebugLoc();
11022
11023   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11024   // There isn't any reason to disable it if the target processor supports it.
11025   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11026     SDValue Chain = Op.getOperand(0);
11027     SDValue Zero = DAG.getConstant(0, MVT::i32);
11028     SDValue Ops[] = {
11029       DAG.getRegister(X86::ESP, MVT::i32), // Base
11030       DAG.getTargetConstant(1, MVT::i8),   // Scale
11031       DAG.getRegister(0, MVT::i32),        // Index
11032       DAG.getTargetConstant(0, MVT::i32),  // Disp
11033       DAG.getRegister(0, MVT::i32),        // Segment.
11034       Zero,
11035       Chain
11036     };
11037     SDNode *Res =
11038       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11039                           array_lengthof(Ops));
11040     return SDValue(Res, 0);
11041   }
11042
11043   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11044   if (!isDev)
11045     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11046
11047   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11048   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11049   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11050   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11051
11052   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11053   if (!Op1 && !Op2 && !Op3 && Op4)
11054     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11055
11056   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11057   if (Op1 && !Op2 && !Op3 && !Op4)
11058     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11059
11060   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11061   //           (MFENCE)>;
11062   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11063 }
11064
11065 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11066                                              SelectionDAG &DAG) const {
11067   DebugLoc dl = Op.getDebugLoc();
11068   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11069     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11070   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11071     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11072
11073   // The only fence that needs an instruction is a sequentially-consistent
11074   // cross-thread fence.
11075   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11076     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11077     // no-sse2). There isn't any reason to disable it if the target processor
11078     // supports it.
11079     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11080       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11081
11082     SDValue Chain = Op.getOperand(0);
11083     SDValue Zero = DAG.getConstant(0, MVT::i32);
11084     SDValue Ops[] = {
11085       DAG.getRegister(X86::ESP, MVT::i32), // Base
11086       DAG.getTargetConstant(1, MVT::i8),   // Scale
11087       DAG.getRegister(0, MVT::i32),        // Index
11088       DAG.getTargetConstant(0, MVT::i32),  // Disp
11089       DAG.getRegister(0, MVT::i32),        // Segment.
11090       Zero,
11091       Chain
11092     };
11093     SDNode *Res =
11094       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11095                          array_lengthof(Ops));
11096     return SDValue(Res, 0);
11097   }
11098
11099   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11100   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11101 }
11102
11103
11104 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11105   EVT T = Op.getValueType();
11106   DebugLoc DL = Op.getDebugLoc();
11107   unsigned Reg = 0;
11108   unsigned size = 0;
11109   switch(T.getSimpleVT().SimpleTy) {
11110   default: llvm_unreachable("Invalid value type!");
11111   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11112   case MVT::i16: Reg = X86::AX;  size = 2; break;
11113   case MVT::i32: Reg = X86::EAX; size = 4; break;
11114   case MVT::i64:
11115     assert(Subtarget->is64Bit() && "Node not type legal!");
11116     Reg = X86::RAX; size = 8;
11117     break;
11118   }
11119   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11120                                     Op.getOperand(2), SDValue());
11121   SDValue Ops[] = { cpIn.getValue(0),
11122                     Op.getOperand(1),
11123                     Op.getOperand(3),
11124                     DAG.getTargetConstant(size, MVT::i8),
11125                     cpIn.getValue(1) };
11126   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11127   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11128   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11129                                            Ops, 5, T, MMO);
11130   SDValue cpOut =
11131     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11132   return cpOut;
11133 }
11134
11135 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11136                                                  SelectionDAG &DAG) const {
11137   assert(Subtarget->is64Bit() && "Result not type legalized?");
11138   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11139   SDValue TheChain = Op.getOperand(0);
11140   DebugLoc dl = Op.getDebugLoc();
11141   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11142   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11143   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11144                                    rax.getValue(2));
11145   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11146                             DAG.getConstant(32, MVT::i8));
11147   SDValue Ops[] = {
11148     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11149     rdx.getValue(1)
11150   };
11151   return DAG.getMergeValues(Ops, 2, dl);
11152 }
11153
11154 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11155                                             SelectionDAG &DAG) const {
11156   EVT SrcVT = Op.getOperand(0).getValueType();
11157   EVT DstVT = Op.getValueType();
11158   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11159          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11160   assert((DstVT == MVT::i64 ||
11161           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11162          "Unexpected custom BITCAST");
11163   // i64 <=> MMX conversions are Legal.
11164   if (SrcVT==MVT::i64 && DstVT.isVector())
11165     return Op;
11166   if (DstVT==MVT::i64 && SrcVT.isVector())
11167     return Op;
11168   // MMX <=> MMX conversions are Legal.
11169   if (SrcVT.isVector() && DstVT.isVector())
11170     return Op;
11171   // All other conversions need to be expanded.
11172   return SDValue();
11173 }
11174
11175 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11176   SDNode *Node = Op.getNode();
11177   DebugLoc dl = Node->getDebugLoc();
11178   EVT T = Node->getValueType(0);
11179   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11180                               DAG.getConstant(0, T), Node->getOperand(2));
11181   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11182                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11183                        Node->getOperand(0),
11184                        Node->getOperand(1), negOp,
11185                        cast<AtomicSDNode>(Node)->getSrcValue(),
11186                        cast<AtomicSDNode>(Node)->getAlignment(),
11187                        cast<AtomicSDNode>(Node)->getOrdering(),
11188                        cast<AtomicSDNode>(Node)->getSynchScope());
11189 }
11190
11191 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11192   SDNode *Node = Op.getNode();
11193   DebugLoc dl = Node->getDebugLoc();
11194   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11195
11196   // Convert seq_cst store -> xchg
11197   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11198   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11199   //        (The only way to get a 16-byte store is cmpxchg16b)
11200   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11201   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11202       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11203     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11204                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11205                                  Node->getOperand(0),
11206                                  Node->getOperand(1), Node->getOperand(2),
11207                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11208                                  cast<AtomicSDNode>(Node)->getOrdering(),
11209                                  cast<AtomicSDNode>(Node)->getSynchScope());
11210     return Swap.getValue(1);
11211   }
11212   // Other atomic stores have a simple pattern.
11213   return Op;
11214 }
11215
11216 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11217   EVT VT = Op.getNode()->getValueType(0);
11218
11219   // Let legalize expand this if it isn't a legal type yet.
11220   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11221     return SDValue();
11222
11223   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11224
11225   unsigned Opc;
11226   bool ExtraOp = false;
11227   switch (Op.getOpcode()) {
11228   default: llvm_unreachable("Invalid code");
11229   case ISD::ADDC: Opc = X86ISD::ADD; break;
11230   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11231   case ISD::SUBC: Opc = X86ISD::SUB; break;
11232   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11233   }
11234
11235   if (!ExtraOp)
11236     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11237                        Op.getOperand(1));
11238   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11239                      Op.getOperand(1), Op.getOperand(2));
11240 }
11241
11242 /// LowerOperation - Provide custom lowering hooks for some operations.
11243 ///
11244 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11245   switch (Op.getOpcode()) {
11246   default: llvm_unreachable("Should not custom lower this!");
11247   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11248   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11249   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11250   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11251   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11252   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11253   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11254   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11255   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11256   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11257   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11258   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11259   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11260   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11261   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11262   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11263   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11264   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11265   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11266   case ISD::SHL_PARTS:
11267   case ISD::SRA_PARTS:
11268   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11269   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11270   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11271   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11272   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11273   case ISD::FABS:               return LowerFABS(Op, DAG);
11274   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11275   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11276   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11277   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11278   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11279   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11280   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11281   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11282   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11283   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11284   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11285   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11286   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11287   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11288   case ISD::FRAME_TO_ARGS_OFFSET:
11289                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11290   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11291   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11292   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11293   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11294   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11295   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11296   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11297   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11298   case ISD::MUL:                return LowerMUL(Op, DAG);
11299   case ISD::SRA:
11300   case ISD::SRL:
11301   case ISD::SHL:                return LowerShift(Op, DAG);
11302   case ISD::SADDO:
11303   case ISD::UADDO:
11304   case ISD::SSUBO:
11305   case ISD::USUBO:
11306   case ISD::SMULO:
11307   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11308   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11309   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11310   case ISD::ADDC:
11311   case ISD::ADDE:
11312   case ISD::SUBC:
11313   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11314   case ISD::ADD:                return LowerADD(Op, DAG);
11315   case ISD::SUB:                return LowerSUB(Op, DAG);
11316   }
11317 }
11318
11319 static void ReplaceATOMIC_LOAD(SDNode *Node,
11320                                   SmallVectorImpl<SDValue> &Results,
11321                                   SelectionDAG &DAG) {
11322   DebugLoc dl = Node->getDebugLoc();
11323   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11324
11325   // Convert wide load -> cmpxchg8b/cmpxchg16b
11326   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11327   //        (The only way to get a 16-byte load is cmpxchg16b)
11328   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11329   SDValue Zero = DAG.getConstant(0, VT);
11330   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11331                                Node->getOperand(0),
11332                                Node->getOperand(1), Zero, Zero,
11333                                cast<AtomicSDNode>(Node)->getMemOperand(),
11334                                cast<AtomicSDNode>(Node)->getOrdering(),
11335                                cast<AtomicSDNode>(Node)->getSynchScope());
11336   Results.push_back(Swap.getValue(0));
11337   Results.push_back(Swap.getValue(1));
11338 }
11339
11340 static void
11341 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11342                         SelectionDAG &DAG, unsigned NewOp) {
11343   DebugLoc dl = Node->getDebugLoc();
11344   assert (Node->getValueType(0) == MVT::i64 &&
11345           "Only know how to expand i64 atomics");
11346
11347   SDValue Chain = Node->getOperand(0);
11348   SDValue In1 = Node->getOperand(1);
11349   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11350                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11351   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11352                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11353   SDValue Ops[] = { Chain, In1, In2L, In2H };
11354   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11355   SDValue Result =
11356     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11357                             cast<MemSDNode>(Node)->getMemOperand());
11358   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11359   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11360   Results.push_back(Result.getValue(2));
11361 }
11362
11363 /// ReplaceNodeResults - Replace a node with an illegal result type
11364 /// with a new node built out of custom code.
11365 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11366                                            SmallVectorImpl<SDValue>&Results,
11367                                            SelectionDAG &DAG) const {
11368   DebugLoc dl = N->getDebugLoc();
11369   switch (N->getOpcode()) {
11370   default:
11371     llvm_unreachable("Do not know how to custom type legalize this operation!");
11372   case ISD::SIGN_EXTEND_INREG:
11373   case ISD::ADDC:
11374   case ISD::ADDE:
11375   case ISD::SUBC:
11376   case ISD::SUBE:
11377     // We don't want to expand or promote these.
11378     return;
11379   case ISD::FP_TO_SINT:
11380   case ISD::FP_TO_UINT: {
11381     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11382
11383     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11384       return;
11385
11386     std::pair<SDValue,SDValue> Vals =
11387         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11388     SDValue FIST = Vals.first, StackSlot = Vals.second;
11389     if (FIST.getNode() != 0) {
11390       EVT VT = N->getValueType(0);
11391       // Return a load from the stack slot.
11392       if (StackSlot.getNode() != 0)
11393         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11394                                       MachinePointerInfo(),
11395                                       false, false, false, 0));
11396       else
11397         Results.push_back(FIST);
11398     }
11399     return;
11400   }
11401   case ISD::READCYCLECOUNTER: {
11402     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11403     SDValue TheChain = N->getOperand(0);
11404     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11405     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11406                                      rd.getValue(1));
11407     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11408                                      eax.getValue(2));
11409     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11410     SDValue Ops[] = { eax, edx };
11411     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11412     Results.push_back(edx.getValue(1));
11413     return;
11414   }
11415   case ISD::ATOMIC_CMP_SWAP: {
11416     EVT T = N->getValueType(0);
11417     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11418     bool Regs64bit = T == MVT::i128;
11419     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11420     SDValue cpInL, cpInH;
11421     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11422                         DAG.getConstant(0, HalfT));
11423     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11424                         DAG.getConstant(1, HalfT));
11425     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11426                              Regs64bit ? X86::RAX : X86::EAX,
11427                              cpInL, SDValue());
11428     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11429                              Regs64bit ? X86::RDX : X86::EDX,
11430                              cpInH, cpInL.getValue(1));
11431     SDValue swapInL, swapInH;
11432     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11433                           DAG.getConstant(0, HalfT));
11434     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11435                           DAG.getConstant(1, HalfT));
11436     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11437                                Regs64bit ? X86::RBX : X86::EBX,
11438                                swapInL, cpInH.getValue(1));
11439     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11440                                Regs64bit ? X86::RCX : X86::ECX,
11441                                swapInH, swapInL.getValue(1));
11442     SDValue Ops[] = { swapInH.getValue(0),
11443                       N->getOperand(1),
11444                       swapInH.getValue(1) };
11445     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11446     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11447     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11448                                   X86ISD::LCMPXCHG8_DAG;
11449     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11450                                              Ops, 3, T, MMO);
11451     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11452                                         Regs64bit ? X86::RAX : X86::EAX,
11453                                         HalfT, Result.getValue(1));
11454     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11455                                         Regs64bit ? X86::RDX : X86::EDX,
11456                                         HalfT, cpOutL.getValue(2));
11457     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11458     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11459     Results.push_back(cpOutH.getValue(1));
11460     return;
11461   }
11462   case ISD::ATOMIC_LOAD_ADD:
11463   case ISD::ATOMIC_LOAD_AND:
11464   case ISD::ATOMIC_LOAD_NAND:
11465   case ISD::ATOMIC_LOAD_OR:
11466   case ISD::ATOMIC_LOAD_SUB:
11467   case ISD::ATOMIC_LOAD_XOR:
11468   case ISD::ATOMIC_SWAP: {
11469     unsigned Opc;
11470     switch (N->getOpcode()) {
11471     default: llvm_unreachable("Unexpected opcode");
11472     case ISD::ATOMIC_LOAD_ADD:
11473       Opc = X86ISD::ATOMADD64_DAG;
11474       break;
11475     case ISD::ATOMIC_LOAD_AND:
11476       Opc = X86ISD::ATOMAND64_DAG;
11477       break;
11478     case ISD::ATOMIC_LOAD_NAND:
11479       Opc = X86ISD::ATOMNAND64_DAG;
11480       break;
11481     case ISD::ATOMIC_LOAD_OR:
11482       Opc = X86ISD::ATOMOR64_DAG;
11483       break;
11484     case ISD::ATOMIC_LOAD_SUB:
11485       Opc = X86ISD::ATOMSUB64_DAG;
11486       break;
11487     case ISD::ATOMIC_LOAD_XOR:
11488       Opc = X86ISD::ATOMXOR64_DAG;
11489       break;
11490     case ISD::ATOMIC_SWAP:
11491       Opc = X86ISD::ATOMSWAP64_DAG;
11492       break;
11493     }
11494     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11495     return;
11496   }
11497   case ISD::ATOMIC_LOAD:
11498     ReplaceATOMIC_LOAD(N, Results, DAG);
11499   }
11500 }
11501
11502 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11503   switch (Opcode) {
11504   default: return NULL;
11505   case X86ISD::BSF:                return "X86ISD::BSF";
11506   case X86ISD::BSR:                return "X86ISD::BSR";
11507   case X86ISD::SHLD:               return "X86ISD::SHLD";
11508   case X86ISD::SHRD:               return "X86ISD::SHRD";
11509   case X86ISD::FAND:               return "X86ISD::FAND";
11510   case X86ISD::FOR:                return "X86ISD::FOR";
11511   case X86ISD::FXOR:               return "X86ISD::FXOR";
11512   case X86ISD::FSRL:               return "X86ISD::FSRL";
11513   case X86ISD::FILD:               return "X86ISD::FILD";
11514   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11515   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11516   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11517   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11518   case X86ISD::FLD:                return "X86ISD::FLD";
11519   case X86ISD::FST:                return "X86ISD::FST";
11520   case X86ISD::CALL:               return "X86ISD::CALL";
11521   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11522   case X86ISD::BT:                 return "X86ISD::BT";
11523   case X86ISD::CMP:                return "X86ISD::CMP";
11524   case X86ISD::COMI:               return "X86ISD::COMI";
11525   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11526   case X86ISD::SETCC:              return "X86ISD::SETCC";
11527   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11528   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11529   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11530   case X86ISD::CMOV:               return "X86ISD::CMOV";
11531   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11532   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11533   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11534   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11535   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11536   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11537   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11538   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11539   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11540   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11541   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11542   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11543   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11544   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11545   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11546   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11547   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11548   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11549   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11550   case X86ISD::HADD:               return "X86ISD::HADD";
11551   case X86ISD::HSUB:               return "X86ISD::HSUB";
11552   case X86ISD::FHADD:              return "X86ISD::FHADD";
11553   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11554   case X86ISD::FMAX:               return "X86ISD::FMAX";
11555   case X86ISD::FMIN:               return "X86ISD::FMIN";
11556   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11557   case X86ISD::FMINC:              return "X86ISD::FMINC";
11558   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11559   case X86ISD::FRCP:               return "X86ISD::FRCP";
11560   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11561   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11562   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11563   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11564   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11565   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11566   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11567   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11568   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11569   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11570   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11571   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11572   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11573   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11574   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11575   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11576   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11577   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11578   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11579   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11580   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11581   case X86ISD::VSHL:               return "X86ISD::VSHL";
11582   case X86ISD::VSRL:               return "X86ISD::VSRL";
11583   case X86ISD::VSRA:               return "X86ISD::VSRA";
11584   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11585   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11586   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11587   case X86ISD::CMPP:               return "X86ISD::CMPP";
11588   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11589   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11590   case X86ISD::ADD:                return "X86ISD::ADD";
11591   case X86ISD::SUB:                return "X86ISD::SUB";
11592   case X86ISD::ADC:                return "X86ISD::ADC";
11593   case X86ISD::SBB:                return "X86ISD::SBB";
11594   case X86ISD::SMUL:               return "X86ISD::SMUL";
11595   case X86ISD::UMUL:               return "X86ISD::UMUL";
11596   case X86ISD::INC:                return "X86ISD::INC";
11597   case X86ISD::DEC:                return "X86ISD::DEC";
11598   case X86ISD::OR:                 return "X86ISD::OR";
11599   case X86ISD::XOR:                return "X86ISD::XOR";
11600   case X86ISD::AND:                return "X86ISD::AND";
11601   case X86ISD::ANDN:               return "X86ISD::ANDN";
11602   case X86ISD::BLSI:               return "X86ISD::BLSI";
11603   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11604   case X86ISD::BLSR:               return "X86ISD::BLSR";
11605   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11606   case X86ISD::PTEST:              return "X86ISD::PTEST";
11607   case X86ISD::TESTP:              return "X86ISD::TESTP";
11608   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11609   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11610   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11611   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11612   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11613   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11614   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11615   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11616   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11617   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11618   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11619   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11620   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11621   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11622   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11623   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11624   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11625   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11626   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11627   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11628   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11629   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11630   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11631   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11632   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11633   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11634   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11635   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11636   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11637   case X86ISD::SAHF:               return "X86ISD::SAHF";
11638   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11639   case X86ISD::FMADD:              return "X86ISD::FMADD";
11640   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11641   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11642   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11643   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11644   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11645   }
11646 }
11647
11648 // isLegalAddressingMode - Return true if the addressing mode represented
11649 // by AM is legal for this target, for a load/store of the specified type.
11650 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11651                                               Type *Ty) const {
11652   // X86 supports extremely general addressing modes.
11653   CodeModel::Model M = getTargetMachine().getCodeModel();
11654   Reloc::Model R = getTargetMachine().getRelocationModel();
11655
11656   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11657   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11658     return false;
11659
11660   if (AM.BaseGV) {
11661     unsigned GVFlags =
11662       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11663
11664     // If a reference to this global requires an extra load, we can't fold it.
11665     if (isGlobalStubReference(GVFlags))
11666       return false;
11667
11668     // If BaseGV requires a register for the PIC base, we cannot also have a
11669     // BaseReg specified.
11670     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11671       return false;
11672
11673     // If lower 4G is not available, then we must use rip-relative addressing.
11674     if ((M != CodeModel::Small || R != Reloc::Static) &&
11675         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11676       return false;
11677   }
11678
11679   switch (AM.Scale) {
11680   case 0:
11681   case 1:
11682   case 2:
11683   case 4:
11684   case 8:
11685     // These scales always work.
11686     break;
11687   case 3:
11688   case 5:
11689   case 9:
11690     // These scales are formed with basereg+scalereg.  Only accept if there is
11691     // no basereg yet.
11692     if (AM.HasBaseReg)
11693       return false;
11694     break;
11695   default:  // Other stuff never works.
11696     return false;
11697   }
11698
11699   return true;
11700 }
11701
11702
11703 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11704   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11705     return false;
11706   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11707   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11708   if (NumBits1 <= NumBits2)
11709     return false;
11710   return true;
11711 }
11712
11713 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11714   return Imm == (int32_t)Imm;
11715 }
11716
11717 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11718   // Can also use sub to handle negated immediates.
11719   return Imm == (int32_t)Imm;
11720 }
11721
11722 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11723   if (!VT1.isInteger() || !VT2.isInteger())
11724     return false;
11725   unsigned NumBits1 = VT1.getSizeInBits();
11726   unsigned NumBits2 = VT2.getSizeInBits();
11727   if (NumBits1 <= NumBits2)
11728     return false;
11729   return true;
11730 }
11731
11732 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11733   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11734   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11735 }
11736
11737 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11738   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11739   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11740 }
11741
11742 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11743   // i16 instructions are longer (0x66 prefix) and potentially slower.
11744   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11745 }
11746
11747 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11748 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11749 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11750 /// are assumed to be legal.
11751 bool
11752 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11753                                       EVT VT) const {
11754   // Very little shuffling can be done for 64-bit vectors right now.
11755   if (VT.getSizeInBits() == 64)
11756     return false;
11757
11758   // FIXME: pshufb, blends, shifts.
11759   return (VT.getVectorNumElements() == 2 ||
11760           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11761           isMOVLMask(M, VT) ||
11762           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11763           isPSHUFDMask(M, VT) ||
11764           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11765           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11766           isPALIGNRMask(M, VT, Subtarget) ||
11767           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11768           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11769           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11770           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11771 }
11772
11773 bool
11774 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11775                                           EVT VT) const {
11776   unsigned NumElts = VT.getVectorNumElements();
11777   // FIXME: This collection of masks seems suspect.
11778   if (NumElts == 2)
11779     return true;
11780   if (NumElts == 4 && VT.is128BitVector()) {
11781     return (isMOVLMask(Mask, VT)  ||
11782             isCommutedMOVLMask(Mask, VT, true) ||
11783             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11784             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11785   }
11786   return false;
11787 }
11788
11789 //===----------------------------------------------------------------------===//
11790 //                           X86 Scheduler Hooks
11791 //===----------------------------------------------------------------------===//
11792
11793 // private utility function
11794 MachineBasicBlock *
11795 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11796                                                        MachineBasicBlock *MBB,
11797                                                        unsigned regOpc,
11798                                                        unsigned immOpc,
11799                                                        unsigned LoadOpc,
11800                                                        unsigned CXchgOpc,
11801                                                        unsigned notOpc,
11802                                                        unsigned EAXreg,
11803                                                  const TargetRegisterClass *RC,
11804                                                        bool Invert) const {
11805   // For the atomic bitwise operator, we generate
11806   //   thisMBB:
11807   //   newMBB:
11808   //     ld  t1 = [bitinstr.addr]
11809   //     op  t2 = t1, [bitinstr.val]
11810   //     not t3 = t2  (if Invert)
11811   //     mov EAX = t1
11812   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11813   //     bz  newMBB
11814   //     fallthrough -->nextMBB
11815   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11816   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11817   MachineFunction::iterator MBBIter = MBB;
11818   ++MBBIter;
11819
11820   /// First build the CFG
11821   MachineFunction *F = MBB->getParent();
11822   MachineBasicBlock *thisMBB = MBB;
11823   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11824   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11825   F->insert(MBBIter, newMBB);
11826   F->insert(MBBIter, nextMBB);
11827
11828   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11829   nextMBB->splice(nextMBB->begin(), thisMBB,
11830                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11831                   thisMBB->end());
11832   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11833
11834   // Update thisMBB to fall through to newMBB
11835   thisMBB->addSuccessor(newMBB);
11836
11837   // newMBB jumps to itself and fall through to nextMBB
11838   newMBB->addSuccessor(nextMBB);
11839   newMBB->addSuccessor(newMBB);
11840
11841   // Insert instructions into newMBB based on incoming instruction
11842   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11843          "unexpected number of operands");
11844   DebugLoc dl = bInstr->getDebugLoc();
11845   MachineOperand& destOper = bInstr->getOperand(0);
11846   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11847   int numArgs = bInstr->getNumOperands() - 1;
11848   for (int i=0; i < numArgs; ++i)
11849     argOpers[i] = &bInstr->getOperand(i+1);
11850
11851   // x86 address has 4 operands: base, index, scale, and displacement
11852   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11853   int valArgIndx = lastAddrIndx + 1;
11854
11855   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11856   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11857   for (int i=0; i <= lastAddrIndx; ++i)
11858     (*MIB).addOperand(*argOpers[i]);
11859
11860   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11861   assert((argOpers[valArgIndx]->isReg() ||
11862           argOpers[valArgIndx]->isImm()) &&
11863          "invalid operand");
11864   if (argOpers[valArgIndx]->isReg())
11865     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11866   else
11867     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11868   MIB.addReg(t1);
11869   (*MIB).addOperand(*argOpers[valArgIndx]);
11870
11871   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11872   if (Invert) {
11873     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11874   }
11875   else
11876     t3 = t2;
11877
11878   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11879   MIB.addReg(t1);
11880
11881   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11882   for (int i=0; i <= lastAddrIndx; ++i)
11883     (*MIB).addOperand(*argOpers[i]);
11884   MIB.addReg(t3);
11885   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11886   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11887                     bInstr->memoperands_end());
11888
11889   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11890   MIB.addReg(EAXreg);
11891
11892   // insert branch
11893   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11894
11895   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11896   return nextMBB;
11897 }
11898
11899 // private utility function:  64 bit atomics on 32 bit host.
11900 MachineBasicBlock *
11901 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11902                                                        MachineBasicBlock *MBB,
11903                                                        unsigned regOpcL,
11904                                                        unsigned regOpcH,
11905                                                        unsigned immOpcL,
11906                                                        unsigned immOpcH,
11907                                                        bool Invert) const {
11908   // For the atomic bitwise operator, we generate
11909   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11910   //     ld t1,t2 = [bitinstr.addr]
11911   //   newMBB:
11912   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11913   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11914   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11915   //     neg t7, t8 < t5, t6  (if Invert)
11916   //     mov ECX, EBX <- t5, t6
11917   //     mov EAX, EDX <- t1, t2
11918   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11919   //     mov t3, t4 <- EAX, EDX
11920   //     bz  newMBB
11921   //     result in out1, out2
11922   //     fallthrough -->nextMBB
11923
11924   const TargetRegisterClass *RC = &X86::GR32RegClass;
11925   const unsigned LoadOpc = X86::MOV32rm;
11926   const unsigned NotOpc = X86::NOT32r;
11927   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11928   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11929   MachineFunction::iterator MBBIter = MBB;
11930   ++MBBIter;
11931
11932   /// First build the CFG
11933   MachineFunction *F = MBB->getParent();
11934   MachineBasicBlock *thisMBB = MBB;
11935   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11936   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11937   F->insert(MBBIter, newMBB);
11938   F->insert(MBBIter, nextMBB);
11939
11940   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11941   nextMBB->splice(nextMBB->begin(), thisMBB,
11942                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11943                   thisMBB->end());
11944   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11945
11946   // Update thisMBB to fall through to newMBB
11947   thisMBB->addSuccessor(newMBB);
11948
11949   // newMBB jumps to itself and fall through to nextMBB
11950   newMBB->addSuccessor(nextMBB);
11951   newMBB->addSuccessor(newMBB);
11952
11953   DebugLoc dl = bInstr->getDebugLoc();
11954   // Insert instructions into newMBB based on incoming instruction
11955   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11956   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11957          "unexpected number of operands");
11958   MachineOperand& dest1Oper = bInstr->getOperand(0);
11959   MachineOperand& dest2Oper = bInstr->getOperand(1);
11960   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11961   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11962     argOpers[i] = &bInstr->getOperand(i+2);
11963
11964     // We use some of the operands multiple times, so conservatively just
11965     // clear any kill flags that might be present.
11966     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11967       argOpers[i]->setIsKill(false);
11968   }
11969
11970   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11971   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11972
11973   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11974   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11975   for (int i=0; i <= lastAddrIndx; ++i)
11976     (*MIB).addOperand(*argOpers[i]);
11977   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11978   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11979   // add 4 to displacement.
11980   for (int i=0; i <= lastAddrIndx-2; ++i)
11981     (*MIB).addOperand(*argOpers[i]);
11982   MachineOperand newOp3 = *(argOpers[3]);
11983   if (newOp3.isImm())
11984     newOp3.setImm(newOp3.getImm()+4);
11985   else
11986     newOp3.setOffset(newOp3.getOffset()+4);
11987   (*MIB).addOperand(newOp3);
11988   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11989
11990   // t3/4 are defined later, at the bottom of the loop
11991   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11992   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11993   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11994     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11995   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11996     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11997
11998   // The subsequent operations should be using the destination registers of
11999   // the PHI instructions.
12000   t1 = dest1Oper.getReg();
12001   t2 = dest2Oper.getReg();
12002
12003   int valArgIndx = lastAddrIndx + 1;
12004   assert((argOpers[valArgIndx]->isReg() ||
12005           argOpers[valArgIndx]->isImm()) &&
12006          "invalid operand");
12007   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12008   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12009   if (argOpers[valArgIndx]->isReg())
12010     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12011   else
12012     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12013   if (regOpcL != X86::MOV32rr)
12014     MIB.addReg(t1);
12015   (*MIB).addOperand(*argOpers[valArgIndx]);
12016   assert(argOpers[valArgIndx + 1]->isReg() ==
12017          argOpers[valArgIndx]->isReg());
12018   assert(argOpers[valArgIndx + 1]->isImm() ==
12019          argOpers[valArgIndx]->isImm());
12020   if (argOpers[valArgIndx + 1]->isReg())
12021     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12022   else
12023     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12024   if (regOpcH != X86::MOV32rr)
12025     MIB.addReg(t2);
12026   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12027
12028   unsigned t7, t8;
12029   if (Invert) {
12030     t7 = F->getRegInfo().createVirtualRegister(RC);
12031     t8 = F->getRegInfo().createVirtualRegister(RC);
12032     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12033     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12034   } else {
12035     t7 = t5;
12036     t8 = t6;
12037   }
12038
12039   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12040   MIB.addReg(t1);
12041   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12042   MIB.addReg(t2);
12043
12044   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12045   MIB.addReg(t7);
12046   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12047   MIB.addReg(t8);
12048
12049   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12050   for (int i=0; i <= lastAddrIndx; ++i)
12051     (*MIB).addOperand(*argOpers[i]);
12052
12053   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12054   (*MIB).setMemRefs(bInstr->memoperands_begin(),
12055                     bInstr->memoperands_end());
12056
12057   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12058   MIB.addReg(X86::EAX);
12059   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12060   MIB.addReg(X86::EDX);
12061
12062   // insert branch
12063   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12064
12065   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12066   return nextMBB;
12067 }
12068
12069 // private utility function
12070 MachineBasicBlock *
12071 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12072                                                       MachineBasicBlock *MBB,
12073                                                       unsigned cmovOpc) const {
12074   // For the atomic min/max operator, we generate
12075   //   thisMBB:
12076   //   newMBB:
12077   //     ld t1 = [min/max.addr]
12078   //     mov t2 = [min/max.val]
12079   //     cmp  t1, t2
12080   //     cmov[cond] t2 = t1
12081   //     mov EAX = t1
12082   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12083   //     bz   newMBB
12084   //     fallthrough -->nextMBB
12085   //
12086   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12087   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12088   MachineFunction::iterator MBBIter = MBB;
12089   ++MBBIter;
12090
12091   /// First build the CFG
12092   MachineFunction *F = MBB->getParent();
12093   MachineBasicBlock *thisMBB = MBB;
12094   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12095   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12096   F->insert(MBBIter, newMBB);
12097   F->insert(MBBIter, nextMBB);
12098
12099   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12100   nextMBB->splice(nextMBB->begin(), thisMBB,
12101                   llvm::next(MachineBasicBlock::iterator(mInstr)),
12102                   thisMBB->end());
12103   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12104
12105   // Update thisMBB to fall through to newMBB
12106   thisMBB->addSuccessor(newMBB);
12107
12108   // newMBB jumps to newMBB and fall through to nextMBB
12109   newMBB->addSuccessor(nextMBB);
12110   newMBB->addSuccessor(newMBB);
12111
12112   DebugLoc dl = mInstr->getDebugLoc();
12113   // Insert instructions into newMBB based on incoming instruction
12114   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12115          "unexpected number of operands");
12116   MachineOperand& destOper = mInstr->getOperand(0);
12117   MachineOperand* argOpers[2 + X86::AddrNumOperands];
12118   int numArgs = mInstr->getNumOperands() - 1;
12119   for (int i=0; i < numArgs; ++i)
12120     argOpers[i] = &mInstr->getOperand(i+1);
12121
12122   // x86 address has 4 operands: base, index, scale, and displacement
12123   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12124   int valArgIndx = lastAddrIndx + 1;
12125
12126   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12127   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12128   for (int i=0; i <= lastAddrIndx; ++i)
12129     (*MIB).addOperand(*argOpers[i]);
12130
12131   // We only support register and immediate values
12132   assert((argOpers[valArgIndx]->isReg() ||
12133           argOpers[valArgIndx]->isImm()) &&
12134          "invalid operand");
12135
12136   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12137   if (argOpers[valArgIndx]->isReg())
12138     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12139   else
12140     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12141   (*MIB).addOperand(*argOpers[valArgIndx]);
12142
12143   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12144   MIB.addReg(t1);
12145
12146   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12147   MIB.addReg(t1);
12148   MIB.addReg(t2);
12149
12150   // Generate movc
12151   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12152   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12153   MIB.addReg(t2);
12154   MIB.addReg(t1);
12155
12156   // Cmp and exchange if none has modified the memory location
12157   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12158   for (int i=0; i <= lastAddrIndx; ++i)
12159     (*MIB).addOperand(*argOpers[i]);
12160   MIB.addReg(t3);
12161   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12162   (*MIB).setMemRefs(mInstr->memoperands_begin(),
12163                     mInstr->memoperands_end());
12164
12165   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12166   MIB.addReg(X86::EAX);
12167
12168   // insert branch
12169   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12170
12171   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12172   return nextMBB;
12173 }
12174
12175 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12176 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12177 // in the .td file.
12178 MachineBasicBlock *
12179 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12180                             unsigned numArgs, bool memArg) const {
12181   assert(Subtarget->hasSSE42() &&
12182          "Target must have SSE4.2 or AVX features enabled");
12183
12184   DebugLoc dl = MI->getDebugLoc();
12185   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12186   unsigned Opc;
12187   if (!Subtarget->hasAVX()) {
12188     if (memArg)
12189       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12190     else
12191       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12192   } else {
12193     if (memArg)
12194       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12195     else
12196       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12197   }
12198
12199   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12200   for (unsigned i = 0; i < numArgs; ++i) {
12201     MachineOperand &Op = MI->getOperand(i+1);
12202     if (!(Op.isReg() && Op.isImplicit()))
12203       MIB.addOperand(Op);
12204   }
12205   BuildMI(*BB, MI, dl,
12206     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12207     .addReg(X86::XMM0);
12208
12209   MI->eraseFromParent();
12210   return BB;
12211 }
12212
12213 MachineBasicBlock *
12214 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12215   DebugLoc dl = MI->getDebugLoc();
12216   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12217
12218   // Address into RAX/EAX, other two args into ECX, EDX.
12219   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12220   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12221   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12222   for (int i = 0; i < X86::AddrNumOperands; ++i)
12223     MIB.addOperand(MI->getOperand(i));
12224
12225   unsigned ValOps = X86::AddrNumOperands;
12226   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12227     .addReg(MI->getOperand(ValOps).getReg());
12228   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12229     .addReg(MI->getOperand(ValOps+1).getReg());
12230
12231   // The instruction doesn't actually take any operands though.
12232   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12233
12234   MI->eraseFromParent(); // The pseudo is gone now.
12235   return BB;
12236 }
12237
12238 MachineBasicBlock *
12239 X86TargetLowering::EmitVAARG64WithCustomInserter(
12240                    MachineInstr *MI,
12241                    MachineBasicBlock *MBB) const {
12242   // Emit va_arg instruction on X86-64.
12243
12244   // Operands to this pseudo-instruction:
12245   // 0  ) Output        : destination address (reg)
12246   // 1-5) Input         : va_list address (addr, i64mem)
12247   // 6  ) ArgSize       : Size (in bytes) of vararg type
12248   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12249   // 8  ) Align         : Alignment of type
12250   // 9  ) EFLAGS (implicit-def)
12251
12252   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12253   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12254
12255   unsigned DestReg = MI->getOperand(0).getReg();
12256   MachineOperand &Base = MI->getOperand(1);
12257   MachineOperand &Scale = MI->getOperand(2);
12258   MachineOperand &Index = MI->getOperand(3);
12259   MachineOperand &Disp = MI->getOperand(4);
12260   MachineOperand &Segment = MI->getOperand(5);
12261   unsigned ArgSize = MI->getOperand(6).getImm();
12262   unsigned ArgMode = MI->getOperand(7).getImm();
12263   unsigned Align = MI->getOperand(8).getImm();
12264
12265   // Memory Reference
12266   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12267   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12268   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12269
12270   // Machine Information
12271   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12272   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12273   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12274   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12275   DebugLoc DL = MI->getDebugLoc();
12276
12277   // struct va_list {
12278   //   i32   gp_offset
12279   //   i32   fp_offset
12280   //   i64   overflow_area (address)
12281   //   i64   reg_save_area (address)
12282   // }
12283   // sizeof(va_list) = 24
12284   // alignment(va_list) = 8
12285
12286   unsigned TotalNumIntRegs = 6;
12287   unsigned TotalNumXMMRegs = 8;
12288   bool UseGPOffset = (ArgMode == 1);
12289   bool UseFPOffset = (ArgMode == 2);
12290   unsigned MaxOffset = TotalNumIntRegs * 8 +
12291                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12292
12293   /* Align ArgSize to a multiple of 8 */
12294   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12295   bool NeedsAlign = (Align > 8);
12296
12297   MachineBasicBlock *thisMBB = MBB;
12298   MachineBasicBlock *overflowMBB;
12299   MachineBasicBlock *offsetMBB;
12300   MachineBasicBlock *endMBB;
12301
12302   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12303   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12304   unsigned OffsetReg = 0;
12305
12306   if (!UseGPOffset && !UseFPOffset) {
12307     // If we only pull from the overflow region, we don't create a branch.
12308     // We don't need to alter control flow.
12309     OffsetDestReg = 0; // unused
12310     OverflowDestReg = DestReg;
12311
12312     offsetMBB = NULL;
12313     overflowMBB = thisMBB;
12314     endMBB = thisMBB;
12315   } else {
12316     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12317     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12318     // If not, pull from overflow_area. (branch to overflowMBB)
12319     //
12320     //       thisMBB
12321     //         |     .
12322     //         |        .
12323     //     offsetMBB   overflowMBB
12324     //         |        .
12325     //         |     .
12326     //        endMBB
12327
12328     // Registers for the PHI in endMBB
12329     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12330     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12331
12332     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12333     MachineFunction *MF = MBB->getParent();
12334     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12335     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12336     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12337
12338     MachineFunction::iterator MBBIter = MBB;
12339     ++MBBIter;
12340
12341     // Insert the new basic blocks
12342     MF->insert(MBBIter, offsetMBB);
12343     MF->insert(MBBIter, overflowMBB);
12344     MF->insert(MBBIter, endMBB);
12345
12346     // Transfer the remainder of MBB and its successor edges to endMBB.
12347     endMBB->splice(endMBB->begin(), thisMBB,
12348                     llvm::next(MachineBasicBlock::iterator(MI)),
12349                     thisMBB->end());
12350     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12351
12352     // Make offsetMBB and overflowMBB successors of thisMBB
12353     thisMBB->addSuccessor(offsetMBB);
12354     thisMBB->addSuccessor(overflowMBB);
12355
12356     // endMBB is a successor of both offsetMBB and overflowMBB
12357     offsetMBB->addSuccessor(endMBB);
12358     overflowMBB->addSuccessor(endMBB);
12359
12360     // Load the offset value into a register
12361     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12362     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12363       .addOperand(Base)
12364       .addOperand(Scale)
12365       .addOperand(Index)
12366       .addDisp(Disp, UseFPOffset ? 4 : 0)
12367       .addOperand(Segment)
12368       .setMemRefs(MMOBegin, MMOEnd);
12369
12370     // Check if there is enough room left to pull this argument.
12371     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12372       .addReg(OffsetReg)
12373       .addImm(MaxOffset + 8 - ArgSizeA8);
12374
12375     // Branch to "overflowMBB" if offset >= max
12376     // Fall through to "offsetMBB" otherwise
12377     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12378       .addMBB(overflowMBB);
12379   }
12380
12381   // In offsetMBB, emit code to use the reg_save_area.
12382   if (offsetMBB) {
12383     assert(OffsetReg != 0);
12384
12385     // Read the reg_save_area address.
12386     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12387     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12388       .addOperand(Base)
12389       .addOperand(Scale)
12390       .addOperand(Index)
12391       .addDisp(Disp, 16)
12392       .addOperand(Segment)
12393       .setMemRefs(MMOBegin, MMOEnd);
12394
12395     // Zero-extend the offset
12396     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12397       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12398         .addImm(0)
12399         .addReg(OffsetReg)
12400         .addImm(X86::sub_32bit);
12401
12402     // Add the offset to the reg_save_area to get the final address.
12403     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12404       .addReg(OffsetReg64)
12405       .addReg(RegSaveReg);
12406
12407     // Compute the offset for the next argument
12408     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12409     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12410       .addReg(OffsetReg)
12411       .addImm(UseFPOffset ? 16 : 8);
12412
12413     // Store it back into the va_list.
12414     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12415       .addOperand(Base)
12416       .addOperand(Scale)
12417       .addOperand(Index)
12418       .addDisp(Disp, UseFPOffset ? 4 : 0)
12419       .addOperand(Segment)
12420       .addReg(NextOffsetReg)
12421       .setMemRefs(MMOBegin, MMOEnd);
12422
12423     // Jump to endMBB
12424     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12425       .addMBB(endMBB);
12426   }
12427
12428   //
12429   // Emit code to use overflow area
12430   //
12431
12432   // Load the overflow_area address into a register.
12433   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12434   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12435     .addOperand(Base)
12436     .addOperand(Scale)
12437     .addOperand(Index)
12438     .addDisp(Disp, 8)
12439     .addOperand(Segment)
12440     .setMemRefs(MMOBegin, MMOEnd);
12441
12442   // If we need to align it, do so. Otherwise, just copy the address
12443   // to OverflowDestReg.
12444   if (NeedsAlign) {
12445     // Align the overflow address
12446     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12447     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12448
12449     // aligned_addr = (addr + (align-1)) & ~(align-1)
12450     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12451       .addReg(OverflowAddrReg)
12452       .addImm(Align-1);
12453
12454     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12455       .addReg(TmpReg)
12456       .addImm(~(uint64_t)(Align-1));
12457   } else {
12458     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12459       .addReg(OverflowAddrReg);
12460   }
12461
12462   // Compute the next overflow address after this argument.
12463   // (the overflow address should be kept 8-byte aligned)
12464   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12465   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12466     .addReg(OverflowDestReg)
12467     .addImm(ArgSizeA8);
12468
12469   // Store the new overflow address.
12470   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12471     .addOperand(Base)
12472     .addOperand(Scale)
12473     .addOperand(Index)
12474     .addDisp(Disp, 8)
12475     .addOperand(Segment)
12476     .addReg(NextAddrReg)
12477     .setMemRefs(MMOBegin, MMOEnd);
12478
12479   // If we branched, emit the PHI to the front of endMBB.
12480   if (offsetMBB) {
12481     BuildMI(*endMBB, endMBB->begin(), DL,
12482             TII->get(X86::PHI), DestReg)
12483       .addReg(OffsetDestReg).addMBB(offsetMBB)
12484       .addReg(OverflowDestReg).addMBB(overflowMBB);
12485   }
12486
12487   // Erase the pseudo instruction
12488   MI->eraseFromParent();
12489
12490   return endMBB;
12491 }
12492
12493 MachineBasicBlock *
12494 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12495                                                  MachineInstr *MI,
12496                                                  MachineBasicBlock *MBB) const {
12497   // Emit code to save XMM registers to the stack. The ABI says that the
12498   // number of registers to save is given in %al, so it's theoretically
12499   // possible to do an indirect jump trick to avoid saving all of them,
12500   // however this code takes a simpler approach and just executes all
12501   // of the stores if %al is non-zero. It's less code, and it's probably
12502   // easier on the hardware branch predictor, and stores aren't all that
12503   // expensive anyway.
12504
12505   // Create the new basic blocks. One block contains all the XMM stores,
12506   // and one block is the final destination regardless of whether any
12507   // stores were performed.
12508   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12509   MachineFunction *F = MBB->getParent();
12510   MachineFunction::iterator MBBIter = MBB;
12511   ++MBBIter;
12512   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12513   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12514   F->insert(MBBIter, XMMSaveMBB);
12515   F->insert(MBBIter, EndMBB);
12516
12517   // Transfer the remainder of MBB and its successor edges to EndMBB.
12518   EndMBB->splice(EndMBB->begin(), MBB,
12519                  llvm::next(MachineBasicBlock::iterator(MI)),
12520                  MBB->end());
12521   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12522
12523   // The original block will now fall through to the XMM save block.
12524   MBB->addSuccessor(XMMSaveMBB);
12525   // The XMMSaveMBB will fall through to the end block.
12526   XMMSaveMBB->addSuccessor(EndMBB);
12527
12528   // Now add the instructions.
12529   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12530   DebugLoc DL = MI->getDebugLoc();
12531
12532   unsigned CountReg = MI->getOperand(0).getReg();
12533   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12534   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12535
12536   if (!Subtarget->isTargetWin64()) {
12537     // If %al is 0, branch around the XMM save block.
12538     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12539     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12540     MBB->addSuccessor(EndMBB);
12541   }
12542
12543   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12544   // In the XMM save block, save all the XMM argument registers.
12545   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12546     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12547     MachineMemOperand *MMO =
12548       F->getMachineMemOperand(
12549           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12550         MachineMemOperand::MOStore,
12551         /*Size=*/16, /*Align=*/16);
12552     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12553       .addFrameIndex(RegSaveFrameIndex)
12554       .addImm(/*Scale=*/1)
12555       .addReg(/*IndexReg=*/0)
12556       .addImm(/*Disp=*/Offset)
12557       .addReg(/*Segment=*/0)
12558       .addReg(MI->getOperand(i).getReg())
12559       .addMemOperand(MMO);
12560   }
12561
12562   MI->eraseFromParent();   // The pseudo instruction is gone now.
12563
12564   return EndMBB;
12565 }
12566
12567 // The EFLAGS operand of SelectItr might be missing a kill marker
12568 // because there were multiple uses of EFLAGS, and ISel didn't know
12569 // which to mark. Figure out whether SelectItr should have had a
12570 // kill marker, and set it if it should. Returns the correct kill
12571 // marker value.
12572 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12573                                      MachineBasicBlock* BB,
12574                                      const TargetRegisterInfo* TRI) {
12575   // Scan forward through BB for a use/def of EFLAGS.
12576   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12577   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12578     const MachineInstr& mi = *miI;
12579     if (mi.readsRegister(X86::EFLAGS))
12580       return false;
12581     if (mi.definesRegister(X86::EFLAGS))
12582       break; // Should have kill-flag - update below.
12583   }
12584
12585   // If we hit the end of the block, check whether EFLAGS is live into a
12586   // successor.
12587   if (miI == BB->end()) {
12588     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12589                                           sEnd = BB->succ_end();
12590          sItr != sEnd; ++sItr) {
12591       MachineBasicBlock* succ = *sItr;
12592       if (succ->isLiveIn(X86::EFLAGS))
12593         return false;
12594     }
12595   }
12596
12597   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12598   // out. SelectMI should have a kill flag on EFLAGS.
12599   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12600   return true;
12601 }
12602
12603 MachineBasicBlock *
12604 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12605                                      MachineBasicBlock *BB) const {
12606   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12607   DebugLoc DL = MI->getDebugLoc();
12608
12609   // To "insert" a SELECT_CC instruction, we actually have to insert the
12610   // diamond control-flow pattern.  The incoming instruction knows the
12611   // destination vreg to set, the condition code register to branch on, the
12612   // true/false values to select between, and a branch opcode to use.
12613   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12614   MachineFunction::iterator It = BB;
12615   ++It;
12616
12617   //  thisMBB:
12618   //  ...
12619   //   TrueVal = ...
12620   //   cmpTY ccX, r1, r2
12621   //   bCC copy1MBB
12622   //   fallthrough --> copy0MBB
12623   MachineBasicBlock *thisMBB = BB;
12624   MachineFunction *F = BB->getParent();
12625   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12626   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12627   F->insert(It, copy0MBB);
12628   F->insert(It, sinkMBB);
12629
12630   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12631   // live into the sink and copy blocks.
12632   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12633   if (!MI->killsRegister(X86::EFLAGS) &&
12634       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12635     copy0MBB->addLiveIn(X86::EFLAGS);
12636     sinkMBB->addLiveIn(X86::EFLAGS);
12637   }
12638
12639   // Transfer the remainder of BB and its successor edges to sinkMBB.
12640   sinkMBB->splice(sinkMBB->begin(), BB,
12641                   llvm::next(MachineBasicBlock::iterator(MI)),
12642                   BB->end());
12643   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12644
12645   // Add the true and fallthrough blocks as its successors.
12646   BB->addSuccessor(copy0MBB);
12647   BB->addSuccessor(sinkMBB);
12648
12649   // Create the conditional branch instruction.
12650   unsigned Opc =
12651     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12652   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12653
12654   //  copy0MBB:
12655   //   %FalseValue = ...
12656   //   # fallthrough to sinkMBB
12657   copy0MBB->addSuccessor(sinkMBB);
12658
12659   //  sinkMBB:
12660   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12661   //  ...
12662   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12663           TII->get(X86::PHI), MI->getOperand(0).getReg())
12664     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12665     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12666
12667   MI->eraseFromParent();   // The pseudo instruction is gone now.
12668   return sinkMBB;
12669 }
12670
12671 MachineBasicBlock *
12672 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12673                                         bool Is64Bit) const {
12674   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12675   DebugLoc DL = MI->getDebugLoc();
12676   MachineFunction *MF = BB->getParent();
12677   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12678
12679   assert(getTargetMachine().Options.EnableSegmentedStacks);
12680
12681   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12682   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12683
12684   // BB:
12685   //  ... [Till the alloca]
12686   // If stacklet is not large enough, jump to mallocMBB
12687   //
12688   // bumpMBB:
12689   //  Allocate by subtracting from RSP
12690   //  Jump to continueMBB
12691   //
12692   // mallocMBB:
12693   //  Allocate by call to runtime
12694   //
12695   // continueMBB:
12696   //  ...
12697   //  [rest of original BB]
12698   //
12699
12700   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12701   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12702   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12703
12704   MachineRegisterInfo &MRI = MF->getRegInfo();
12705   const TargetRegisterClass *AddrRegClass =
12706     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12707
12708   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12709     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12710     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12711     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12712     sizeVReg = MI->getOperand(1).getReg(),
12713     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12714
12715   MachineFunction::iterator MBBIter = BB;
12716   ++MBBIter;
12717
12718   MF->insert(MBBIter, bumpMBB);
12719   MF->insert(MBBIter, mallocMBB);
12720   MF->insert(MBBIter, continueMBB);
12721
12722   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12723                       (MachineBasicBlock::iterator(MI)), BB->end());
12724   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12725
12726   // Add code to the main basic block to check if the stack limit has been hit,
12727   // and if so, jump to mallocMBB otherwise to bumpMBB.
12728   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12729   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12730     .addReg(tmpSPVReg).addReg(sizeVReg);
12731   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12732     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12733     .addReg(SPLimitVReg);
12734   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12735
12736   // bumpMBB simply decreases the stack pointer, since we know the current
12737   // stacklet has enough space.
12738   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12739     .addReg(SPLimitVReg);
12740   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12741     .addReg(SPLimitVReg);
12742   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12743
12744   // Calls into a routine in libgcc to allocate more space from the heap.
12745   const uint32_t *RegMask =
12746     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12747   if (Is64Bit) {
12748     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12749       .addReg(sizeVReg);
12750     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12751       .addExternalSymbol("__morestack_allocate_stack_space")
12752       .addRegMask(RegMask)
12753       .addReg(X86::RDI, RegState::Implicit)
12754       .addReg(X86::RAX, RegState::ImplicitDefine);
12755   } else {
12756     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12757       .addImm(12);
12758     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12759     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12760       .addExternalSymbol("__morestack_allocate_stack_space")
12761       .addRegMask(RegMask)
12762       .addReg(X86::EAX, RegState::ImplicitDefine);
12763   }
12764
12765   if (!Is64Bit)
12766     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12767       .addImm(16);
12768
12769   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12770     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12771   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12772
12773   // Set up the CFG correctly.
12774   BB->addSuccessor(bumpMBB);
12775   BB->addSuccessor(mallocMBB);
12776   mallocMBB->addSuccessor(continueMBB);
12777   bumpMBB->addSuccessor(continueMBB);
12778
12779   // Take care of the PHI nodes.
12780   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12781           MI->getOperand(0).getReg())
12782     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12783     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12784
12785   // Delete the original pseudo instruction.
12786   MI->eraseFromParent();
12787
12788   // And we're done.
12789   return continueMBB;
12790 }
12791
12792 MachineBasicBlock *
12793 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12794                                           MachineBasicBlock *BB) const {
12795   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12796   DebugLoc DL = MI->getDebugLoc();
12797
12798   assert(!Subtarget->isTargetEnvMacho());
12799
12800   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12801   // non-trivial part is impdef of ESP.
12802
12803   if (Subtarget->isTargetWin64()) {
12804     if (Subtarget->isTargetCygMing()) {
12805       // ___chkstk(Mingw64):
12806       // Clobbers R10, R11, RAX and EFLAGS.
12807       // Updates RSP.
12808       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12809         .addExternalSymbol("___chkstk")
12810         .addReg(X86::RAX, RegState::Implicit)
12811         .addReg(X86::RSP, RegState::Implicit)
12812         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12813         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12814         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12815     } else {
12816       // __chkstk(MSVCRT): does not update stack pointer.
12817       // Clobbers R10, R11 and EFLAGS.
12818       // FIXME: RAX(allocated size) might be reused and not killed.
12819       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12820         .addExternalSymbol("__chkstk")
12821         .addReg(X86::RAX, RegState::Implicit)
12822         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12823       // RAX has the offset to subtracted from RSP.
12824       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12825         .addReg(X86::RSP)
12826         .addReg(X86::RAX);
12827     }
12828   } else {
12829     const char *StackProbeSymbol =
12830       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12831
12832     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12833       .addExternalSymbol(StackProbeSymbol)
12834       .addReg(X86::EAX, RegState::Implicit)
12835       .addReg(X86::ESP, RegState::Implicit)
12836       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12837       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12838       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12839   }
12840
12841   MI->eraseFromParent();   // The pseudo instruction is gone now.
12842   return BB;
12843 }
12844
12845 MachineBasicBlock *
12846 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12847                                       MachineBasicBlock *BB) const {
12848   // This is pretty easy.  We're taking the value that we received from
12849   // our load from the relocation, sticking it in either RDI (x86-64)
12850   // or EAX and doing an indirect call.  The return value will then
12851   // be in the normal return register.
12852   const X86InstrInfo *TII
12853     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12854   DebugLoc DL = MI->getDebugLoc();
12855   MachineFunction *F = BB->getParent();
12856
12857   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12858   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12859
12860   // Get a register mask for the lowered call.
12861   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12862   // proper register mask.
12863   const uint32_t *RegMask =
12864     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12865   if (Subtarget->is64Bit()) {
12866     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12867                                       TII->get(X86::MOV64rm), X86::RDI)
12868     .addReg(X86::RIP)
12869     .addImm(0).addReg(0)
12870     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12871                       MI->getOperand(3).getTargetFlags())
12872     .addReg(0);
12873     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12874     addDirectMem(MIB, X86::RDI);
12875     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12876   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12877     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12878                                       TII->get(X86::MOV32rm), X86::EAX)
12879     .addReg(0)
12880     .addImm(0).addReg(0)
12881     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12882                       MI->getOperand(3).getTargetFlags())
12883     .addReg(0);
12884     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12885     addDirectMem(MIB, X86::EAX);
12886     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12887   } else {
12888     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12889                                       TII->get(X86::MOV32rm), X86::EAX)
12890     .addReg(TII->getGlobalBaseReg(F))
12891     .addImm(0).addReg(0)
12892     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12893                       MI->getOperand(3).getTargetFlags())
12894     .addReg(0);
12895     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12896     addDirectMem(MIB, X86::EAX);
12897     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12898   }
12899
12900   MI->eraseFromParent(); // The pseudo instruction is gone now.
12901   return BB;
12902 }
12903
12904 MachineBasicBlock *
12905 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12906                                                MachineBasicBlock *BB) const {
12907   switch (MI->getOpcode()) {
12908   default: llvm_unreachable("Unexpected instr type to insert");
12909   case X86::TAILJMPd64:
12910   case X86::TAILJMPr64:
12911   case X86::TAILJMPm64:
12912     llvm_unreachable("TAILJMP64 would not be touched here.");
12913   case X86::TCRETURNdi64:
12914   case X86::TCRETURNri64:
12915   case X86::TCRETURNmi64:
12916     return BB;
12917   case X86::WIN_ALLOCA:
12918     return EmitLoweredWinAlloca(MI, BB);
12919   case X86::SEG_ALLOCA_32:
12920     return EmitLoweredSegAlloca(MI, BB, false);
12921   case X86::SEG_ALLOCA_64:
12922     return EmitLoweredSegAlloca(MI, BB, true);
12923   case X86::TLSCall_32:
12924   case X86::TLSCall_64:
12925     return EmitLoweredTLSCall(MI, BB);
12926   case X86::CMOV_GR8:
12927   case X86::CMOV_FR32:
12928   case X86::CMOV_FR64:
12929   case X86::CMOV_V4F32:
12930   case X86::CMOV_V2F64:
12931   case X86::CMOV_V2I64:
12932   case X86::CMOV_V8F32:
12933   case X86::CMOV_V4F64:
12934   case X86::CMOV_V4I64:
12935   case X86::CMOV_GR16:
12936   case X86::CMOV_GR32:
12937   case X86::CMOV_RFP32:
12938   case X86::CMOV_RFP64:
12939   case X86::CMOV_RFP80:
12940     return EmitLoweredSelect(MI, BB);
12941
12942   case X86::FP32_TO_INT16_IN_MEM:
12943   case X86::FP32_TO_INT32_IN_MEM:
12944   case X86::FP32_TO_INT64_IN_MEM:
12945   case X86::FP64_TO_INT16_IN_MEM:
12946   case X86::FP64_TO_INT32_IN_MEM:
12947   case X86::FP64_TO_INT64_IN_MEM:
12948   case X86::FP80_TO_INT16_IN_MEM:
12949   case X86::FP80_TO_INT32_IN_MEM:
12950   case X86::FP80_TO_INT64_IN_MEM: {
12951     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12952     DebugLoc DL = MI->getDebugLoc();
12953
12954     // Change the floating point control register to use "round towards zero"
12955     // mode when truncating to an integer value.
12956     MachineFunction *F = BB->getParent();
12957     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12958     addFrameReference(BuildMI(*BB, MI, DL,
12959                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12960
12961     // Load the old value of the high byte of the control word...
12962     unsigned OldCW =
12963       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12964     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12965                       CWFrameIdx);
12966
12967     // Set the high part to be round to zero...
12968     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12969       .addImm(0xC7F);
12970
12971     // Reload the modified control word now...
12972     addFrameReference(BuildMI(*BB, MI, DL,
12973                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12974
12975     // Restore the memory image of control word to original value
12976     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12977       .addReg(OldCW);
12978
12979     // Get the X86 opcode to use.
12980     unsigned Opc;
12981     switch (MI->getOpcode()) {
12982     default: llvm_unreachable("illegal opcode!");
12983     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12984     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12985     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12986     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12987     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12988     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12989     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12990     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12991     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12992     }
12993
12994     X86AddressMode AM;
12995     MachineOperand &Op = MI->getOperand(0);
12996     if (Op.isReg()) {
12997       AM.BaseType = X86AddressMode::RegBase;
12998       AM.Base.Reg = Op.getReg();
12999     } else {
13000       AM.BaseType = X86AddressMode::FrameIndexBase;
13001       AM.Base.FrameIndex = Op.getIndex();
13002     }
13003     Op = MI->getOperand(1);
13004     if (Op.isImm())
13005       AM.Scale = Op.getImm();
13006     Op = MI->getOperand(2);
13007     if (Op.isImm())
13008       AM.IndexReg = Op.getImm();
13009     Op = MI->getOperand(3);
13010     if (Op.isGlobal()) {
13011       AM.GV = Op.getGlobal();
13012     } else {
13013       AM.Disp = Op.getImm();
13014     }
13015     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13016                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13017
13018     // Reload the original control word now.
13019     addFrameReference(BuildMI(*BB, MI, DL,
13020                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13021
13022     MI->eraseFromParent();   // The pseudo instruction is gone now.
13023     return BB;
13024   }
13025     // String/text processing lowering.
13026   case X86::PCMPISTRM128REG:
13027   case X86::VPCMPISTRM128REG:
13028   case X86::PCMPISTRM128MEM:
13029   case X86::VPCMPISTRM128MEM:
13030   case X86::PCMPESTRM128REG:
13031   case X86::VPCMPESTRM128REG:
13032   case X86::PCMPESTRM128MEM:
13033   case X86::VPCMPESTRM128MEM: {
13034     unsigned NumArgs;
13035     bool MemArg;
13036     switch (MI->getOpcode()) {
13037     default: llvm_unreachable("illegal opcode!");
13038     case X86::PCMPISTRM128REG:
13039     case X86::VPCMPISTRM128REG:
13040       NumArgs = 3; MemArg = false; break;
13041     case X86::PCMPISTRM128MEM:
13042     case X86::VPCMPISTRM128MEM:
13043       NumArgs = 3; MemArg = true; break;
13044     case X86::PCMPESTRM128REG:
13045     case X86::VPCMPESTRM128REG:
13046       NumArgs = 5; MemArg = false; break;
13047     case X86::PCMPESTRM128MEM:
13048     case X86::VPCMPESTRM128MEM:
13049       NumArgs = 5; MemArg = true; break;
13050     }
13051     return EmitPCMP(MI, BB, NumArgs, MemArg);
13052   }
13053
13054     // Thread synchronization.
13055   case X86::MONITOR:
13056     return EmitMonitor(MI, BB);
13057
13058     // Atomic Lowering.
13059   case X86::ATOMMIN32:
13060   case X86::ATOMMAX32:
13061   case X86::ATOMUMIN32:
13062   case X86::ATOMUMAX32:
13063   case X86::ATOMMIN16:
13064   case X86::ATOMMAX16:
13065   case X86::ATOMUMIN16:
13066   case X86::ATOMUMAX16:
13067   case X86::ATOMMIN64:
13068   case X86::ATOMMAX64:
13069   case X86::ATOMUMIN64:
13070   case X86::ATOMUMAX64: {
13071     unsigned Opc;
13072     switch (MI->getOpcode()) {
13073     default: llvm_unreachable("illegal opcode!");
13074     case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13075     case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13076     case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13077     case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13078     case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13079     case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13080     case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13081     case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13082     case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13083     case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13084     case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13085     case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13086     // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13087     }
13088     return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13089   }
13090
13091   case X86::ATOMAND32:
13092   case X86::ATOMOR32:
13093   case X86::ATOMXOR32:
13094   case X86::ATOMNAND32: {
13095     bool Invert = false;
13096     unsigned RegOpc, ImmOpc;
13097     switch (MI->getOpcode()) {
13098     default: llvm_unreachable("illegal opcode!");
13099     case X86::ATOMAND32:
13100       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13101     case X86::ATOMOR32:
13102       RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13103     case X86::ATOMXOR32:
13104       RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13105     case X86::ATOMNAND32:
13106       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13107     }
13108     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13109                                                X86::MOV32rm, X86::LCMPXCHG32,
13110                                                X86::NOT32r, X86::EAX,
13111                                                &X86::GR32RegClass, Invert);
13112   }
13113
13114   case X86::ATOMAND16:
13115   case X86::ATOMOR16:
13116   case X86::ATOMXOR16:
13117   case X86::ATOMNAND16: {
13118     bool Invert = false;
13119     unsigned RegOpc, ImmOpc;
13120     switch (MI->getOpcode()) {
13121     default: llvm_unreachable("illegal opcode!");
13122     case X86::ATOMAND16:
13123       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13124     case X86::ATOMOR16:
13125       RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13126     case X86::ATOMXOR16:
13127       RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13128     case X86::ATOMNAND16:
13129       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13130     }
13131     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13132                                                X86::MOV16rm, X86::LCMPXCHG16,
13133                                                X86::NOT16r, X86::AX,
13134                                                &X86::GR16RegClass, Invert);
13135   }
13136
13137   case X86::ATOMAND8:
13138   case X86::ATOMOR8:
13139   case X86::ATOMXOR8:
13140   case X86::ATOMNAND8: {
13141     bool Invert = false;
13142     unsigned RegOpc, ImmOpc;
13143     switch (MI->getOpcode()) {
13144     default: llvm_unreachable("illegal opcode!");
13145     case X86::ATOMAND8:
13146       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13147     case X86::ATOMOR8:
13148       RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13149     case X86::ATOMXOR8:
13150       RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13151     case X86::ATOMNAND8:
13152       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13153     }
13154     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13155                                                X86::MOV8rm, X86::LCMPXCHG8,
13156                                                X86::NOT8r, X86::AL,
13157                                                &X86::GR8RegClass, Invert);
13158   }
13159
13160   // This group is for 64-bit host.
13161   case X86::ATOMAND64:
13162   case X86::ATOMOR64:
13163   case X86::ATOMXOR64:
13164   case X86::ATOMNAND64: {
13165     bool Invert = false;
13166     unsigned RegOpc, ImmOpc;
13167     switch (MI->getOpcode()) {
13168     default: llvm_unreachable("illegal opcode!");
13169     case X86::ATOMAND64:
13170       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13171     case X86::ATOMOR64:
13172       RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13173     case X86::ATOMXOR64:
13174       RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13175     case X86::ATOMNAND64:
13176       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13177     }
13178     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13179                                                X86::MOV64rm, X86::LCMPXCHG64,
13180                                                X86::NOT64r, X86::RAX,
13181                                                &X86::GR64RegClass, Invert);
13182   }
13183
13184   // This group does 64-bit operations on a 32-bit host.
13185   case X86::ATOMAND6432:
13186   case X86::ATOMOR6432:
13187   case X86::ATOMXOR6432:
13188   case X86::ATOMNAND6432:
13189   case X86::ATOMADD6432:
13190   case X86::ATOMSUB6432:
13191   case X86::ATOMSWAP6432: {
13192     bool Invert = false;
13193     unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13194     switch (MI->getOpcode()) {
13195     default: llvm_unreachable("illegal opcode!");
13196     case X86::ATOMAND6432:
13197       RegOpcL = RegOpcH = X86::AND32rr;
13198       ImmOpcL = ImmOpcH = X86::AND32ri;
13199       break;
13200     case X86::ATOMOR6432:
13201       RegOpcL = RegOpcH = X86::OR32rr;
13202       ImmOpcL = ImmOpcH = X86::OR32ri;
13203       break;
13204     case X86::ATOMXOR6432:
13205       RegOpcL = RegOpcH = X86::XOR32rr;
13206       ImmOpcL = ImmOpcH = X86::XOR32ri;
13207       break;
13208     case X86::ATOMNAND6432:
13209       RegOpcL = RegOpcH = X86::AND32rr;
13210       ImmOpcL = ImmOpcH = X86::AND32ri;
13211       Invert = true;
13212       break;
13213     case X86::ATOMADD6432:
13214       RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13215       ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13216       break;
13217     case X86::ATOMSUB6432:
13218       RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13219       ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13220       break;
13221     case X86::ATOMSWAP6432:
13222       RegOpcL = RegOpcH = X86::MOV32rr;
13223       ImmOpcL = ImmOpcH = X86::MOV32ri;
13224       break;
13225     }
13226     return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13227                                                ImmOpcL, ImmOpcH, Invert);
13228   }
13229
13230   case X86::VASTART_SAVE_XMM_REGS:
13231     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13232
13233   case X86::VAARG_64:
13234     return EmitVAARG64WithCustomInserter(MI, BB);
13235   }
13236 }
13237
13238 //===----------------------------------------------------------------------===//
13239 //                           X86 Optimization Hooks
13240 //===----------------------------------------------------------------------===//
13241
13242 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13243                                                        APInt &KnownZero,
13244                                                        APInt &KnownOne,
13245                                                        const SelectionDAG &DAG,
13246                                                        unsigned Depth) const {
13247   unsigned BitWidth = KnownZero.getBitWidth();
13248   unsigned Opc = Op.getOpcode();
13249   assert((Opc >= ISD::BUILTIN_OP_END ||
13250           Opc == ISD::INTRINSIC_WO_CHAIN ||
13251           Opc == ISD::INTRINSIC_W_CHAIN ||
13252           Opc == ISD::INTRINSIC_VOID) &&
13253          "Should use MaskedValueIsZero if you don't know whether Op"
13254          " is a target node!");
13255
13256   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13257   switch (Opc) {
13258   default: break;
13259   case X86ISD::ADD:
13260   case X86ISD::SUB:
13261   case X86ISD::ADC:
13262   case X86ISD::SBB:
13263   case X86ISD::SMUL:
13264   case X86ISD::UMUL:
13265   case X86ISD::INC:
13266   case X86ISD::DEC:
13267   case X86ISD::OR:
13268   case X86ISD::XOR:
13269   case X86ISD::AND:
13270     // These nodes' second result is a boolean.
13271     if (Op.getResNo() == 0)
13272       break;
13273     // Fallthrough
13274   case X86ISD::SETCC:
13275     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13276     break;
13277   case ISD::INTRINSIC_WO_CHAIN: {
13278     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13279     unsigned NumLoBits = 0;
13280     switch (IntId) {
13281     default: break;
13282     case Intrinsic::x86_sse_movmsk_ps:
13283     case Intrinsic::x86_avx_movmsk_ps_256:
13284     case Intrinsic::x86_sse2_movmsk_pd:
13285     case Intrinsic::x86_avx_movmsk_pd_256:
13286     case Intrinsic::x86_mmx_pmovmskb:
13287     case Intrinsic::x86_sse2_pmovmskb_128:
13288     case Intrinsic::x86_avx2_pmovmskb: {
13289       // High bits of movmskp{s|d}, pmovmskb are known zero.
13290       switch (IntId) {
13291         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13292         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13293         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13294         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13295         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13296         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13297         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13298         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13299       }
13300       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13301       break;
13302     }
13303     }
13304     break;
13305   }
13306   }
13307 }
13308
13309 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13310                                                          unsigned Depth) const {
13311   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13312   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13313     return Op.getValueType().getScalarType().getSizeInBits();
13314
13315   // Fallback case.
13316   return 1;
13317 }
13318
13319 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13320 /// node is a GlobalAddress + offset.
13321 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13322                                        const GlobalValue* &GA,
13323                                        int64_t &Offset) const {
13324   if (N->getOpcode() == X86ISD::Wrapper) {
13325     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13326       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13327       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13328       return true;
13329     }
13330   }
13331   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13332 }
13333
13334 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13335 /// same as extracting the high 128-bit part of 256-bit vector and then
13336 /// inserting the result into the low part of a new 256-bit vector
13337 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13338   EVT VT = SVOp->getValueType(0);
13339   unsigned NumElems = VT.getVectorNumElements();
13340
13341   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13342   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13343     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13344         SVOp->getMaskElt(j) >= 0)
13345       return false;
13346
13347   return true;
13348 }
13349
13350 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13351 /// same as extracting the low 128-bit part of 256-bit vector and then
13352 /// inserting the result into the high part of a new 256-bit vector
13353 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13354   EVT VT = SVOp->getValueType(0);
13355   unsigned NumElems = VT.getVectorNumElements();
13356
13357   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13358   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13359     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13360         SVOp->getMaskElt(j) >= 0)
13361       return false;
13362
13363   return true;
13364 }
13365
13366 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13367 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13368                                         TargetLowering::DAGCombinerInfo &DCI,
13369                                         const X86Subtarget* Subtarget) {
13370   DebugLoc dl = N->getDebugLoc();
13371   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13372   SDValue V1 = SVOp->getOperand(0);
13373   SDValue V2 = SVOp->getOperand(1);
13374   EVT VT = SVOp->getValueType(0);
13375   unsigned NumElems = VT.getVectorNumElements();
13376
13377   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13378       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13379     //
13380     //                   0,0,0,...
13381     //                      |
13382     //    V      UNDEF    BUILD_VECTOR    UNDEF
13383     //     \      /           \           /
13384     //  CONCAT_VECTOR         CONCAT_VECTOR
13385     //         \                  /
13386     //          \                /
13387     //          RESULT: V + zero extended
13388     //
13389     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13390         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13391         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13392       return SDValue();
13393
13394     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13395       return SDValue();
13396
13397     // To match the shuffle mask, the first half of the mask should
13398     // be exactly the first vector, and all the rest a splat with the
13399     // first element of the second one.
13400     for (unsigned i = 0; i != NumElems/2; ++i)
13401       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13402           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13403         return SDValue();
13404
13405     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13406     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13407       if (Ld->hasNUsesOfValue(1, 0)) {
13408         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13409         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13410         SDValue ResNode =
13411           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13412                                   Ld->getMemoryVT(),
13413                                   Ld->getPointerInfo(),
13414                                   Ld->getAlignment(),
13415                                   false/*isVolatile*/, true/*ReadMem*/,
13416                                   false/*WriteMem*/);
13417         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13418       }
13419     }
13420
13421     // Emit a zeroed vector and insert the desired subvector on its
13422     // first half.
13423     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13424     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13425     return DCI.CombineTo(N, InsV);
13426   }
13427
13428   //===--------------------------------------------------------------------===//
13429   // Combine some shuffles into subvector extracts and inserts:
13430   //
13431
13432   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13433   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13434     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13435     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13436     return DCI.CombineTo(N, InsV);
13437   }
13438
13439   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13440   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13441     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13442     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13443     return DCI.CombineTo(N, InsV);
13444   }
13445
13446   return SDValue();
13447 }
13448
13449 /// PerformShuffleCombine - Performs several different shuffle combines.
13450 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13451                                      TargetLowering::DAGCombinerInfo &DCI,
13452                                      const X86Subtarget *Subtarget) {
13453   DebugLoc dl = N->getDebugLoc();
13454   EVT VT = N->getValueType(0);
13455
13456   // Don't create instructions with illegal types after legalize types has run.
13457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13458   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13459     return SDValue();
13460
13461   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13462   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13463       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13464     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13465
13466   // Only handle 128 wide vector from here on.
13467   if (!VT.is128BitVector())
13468     return SDValue();
13469
13470   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13471   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13472   // consecutive, non-overlapping, and in the right order.
13473   SmallVector<SDValue, 16> Elts;
13474   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13475     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13476
13477   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13478 }
13479
13480
13481 /// DCI, PerformTruncateCombine - Converts truncate operation to
13482 /// a sequence of vector shuffle operations.
13483 /// It is possible when we truncate 256-bit vector to 128-bit vector
13484
13485 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13486                                                   DAGCombinerInfo &DCI) const {
13487   if (!DCI.isBeforeLegalizeOps())
13488     return SDValue();
13489
13490   if (!Subtarget->hasAVX())
13491     return SDValue();
13492
13493   EVT VT = N->getValueType(0);
13494   SDValue Op = N->getOperand(0);
13495   EVT OpVT = Op.getValueType();
13496   DebugLoc dl = N->getDebugLoc();
13497
13498   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13499
13500     if (Subtarget->hasAVX2()) {
13501       // AVX2: v4i64 -> v4i32
13502
13503       // VPERMD
13504       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13505
13506       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13507       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13508                                 ShufMask);
13509
13510       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13511                          DAG.getIntPtrConstant(0));
13512     }
13513
13514     // AVX: v4i64 -> v4i32
13515     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13516                                DAG.getIntPtrConstant(0));
13517
13518     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13519                                DAG.getIntPtrConstant(2));
13520
13521     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13522     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13523
13524     // PSHUFD
13525     static const int ShufMask1[] = {0, 2, 0, 0};
13526
13527     SDValue Undef = DAG.getUNDEF(VT);
13528     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13529     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13530
13531     // MOVLHPS
13532     static const int ShufMask2[] = {0, 1, 4, 5};
13533
13534     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13535   }
13536
13537   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13538
13539     if (Subtarget->hasAVX2()) {
13540       // AVX2: v8i32 -> v8i16
13541
13542       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13543
13544       // PSHUFB
13545       SmallVector<SDValue,32> pshufbMask;
13546       for (unsigned i = 0; i < 2; ++i) {
13547         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13548         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13549         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13550         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13551         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13552         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13553         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13554         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13555         for (unsigned j = 0; j < 8; ++j)
13556           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13557       }
13558       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13559                                &pshufbMask[0], 32);
13560       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13561
13562       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13563
13564       static const int ShufMask[] = {0,  2,  -1,  -1};
13565       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13566                                 &ShufMask[0]);
13567
13568       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13569                        DAG.getIntPtrConstant(0));
13570
13571       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13572     }
13573
13574     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13575                                DAG.getIntPtrConstant(0));
13576
13577     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13578                                DAG.getIntPtrConstant(4));
13579
13580     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13581     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13582
13583     // PSHUFB
13584     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13585                                    -1, -1, -1, -1, -1, -1, -1, -1};
13586
13587     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13588     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13589     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13590
13591     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13592     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13593
13594     // MOVLHPS
13595     static const int ShufMask2[] = {0, 1, 4, 5};
13596
13597     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13598     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13599   }
13600
13601   return SDValue();
13602 }
13603
13604 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13605 /// specific shuffle of a load can be folded into a single element load.
13606 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13607 /// shuffles have been customed lowered so we need to handle those here.
13608 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13609                                          TargetLowering::DAGCombinerInfo &DCI) {
13610   if (DCI.isBeforeLegalizeOps())
13611     return SDValue();
13612
13613   SDValue InVec = N->getOperand(0);
13614   SDValue EltNo = N->getOperand(1);
13615
13616   if (!isa<ConstantSDNode>(EltNo))
13617     return SDValue();
13618
13619   EVT VT = InVec.getValueType();
13620
13621   bool HasShuffleIntoBitcast = false;
13622   if (InVec.getOpcode() == ISD::BITCAST) {
13623     // Don't duplicate a load with other uses.
13624     if (!InVec.hasOneUse())
13625       return SDValue();
13626     EVT BCVT = InVec.getOperand(0).getValueType();
13627     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13628       return SDValue();
13629     InVec = InVec.getOperand(0);
13630     HasShuffleIntoBitcast = true;
13631   }
13632
13633   if (!isTargetShuffle(InVec.getOpcode()))
13634     return SDValue();
13635
13636   // Don't duplicate a load with other uses.
13637   if (!InVec.hasOneUse())
13638     return SDValue();
13639
13640   SmallVector<int, 16> ShuffleMask;
13641   bool UnaryShuffle;
13642   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13643                             UnaryShuffle))
13644     return SDValue();
13645
13646   // Select the input vector, guarding against out of range extract vector.
13647   unsigned NumElems = VT.getVectorNumElements();
13648   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13649   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13650   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13651                                          : InVec.getOperand(1);
13652
13653   // If inputs to shuffle are the same for both ops, then allow 2 uses
13654   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13655
13656   if (LdNode.getOpcode() == ISD::BITCAST) {
13657     // Don't duplicate a load with other uses.
13658     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13659       return SDValue();
13660
13661     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13662     LdNode = LdNode.getOperand(0);
13663   }
13664
13665   if (!ISD::isNormalLoad(LdNode.getNode()))
13666     return SDValue();
13667
13668   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13669
13670   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13671     return SDValue();
13672
13673   if (HasShuffleIntoBitcast) {
13674     // If there's a bitcast before the shuffle, check if the load type and
13675     // alignment is valid.
13676     unsigned Align = LN0->getAlignment();
13677     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13678     unsigned NewAlign = TLI.getTargetData()->
13679       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13680
13681     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13682       return SDValue();
13683   }
13684
13685   // All checks match so transform back to vector_shuffle so that DAG combiner
13686   // can finish the job
13687   DebugLoc dl = N->getDebugLoc();
13688
13689   // Create shuffle node taking into account the case that its a unary shuffle
13690   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13691   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13692                                  InVec.getOperand(0), Shuffle,
13693                                  &ShuffleMask[0]);
13694   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13695   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13696                      EltNo);
13697 }
13698
13699 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13700 /// generation and convert it from being a bunch of shuffles and extracts
13701 /// to a simple store and scalar loads to extract the elements.
13702 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13703                                          TargetLowering::DAGCombinerInfo &DCI) {
13704   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13705   if (NewOp.getNode())
13706     return NewOp;
13707
13708   SDValue InputVector = N->getOperand(0);
13709
13710   // Only operate on vectors of 4 elements, where the alternative shuffling
13711   // gets to be more expensive.
13712   if (InputVector.getValueType() != MVT::v4i32)
13713     return SDValue();
13714
13715   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13716   // single use which is a sign-extend or zero-extend, and all elements are
13717   // used.
13718   SmallVector<SDNode *, 4> Uses;
13719   unsigned ExtractedElements = 0;
13720   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13721        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13722     if (UI.getUse().getResNo() != InputVector.getResNo())
13723       return SDValue();
13724
13725     SDNode *Extract = *UI;
13726     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13727       return SDValue();
13728
13729     if (Extract->getValueType(0) != MVT::i32)
13730       return SDValue();
13731     if (!Extract->hasOneUse())
13732       return SDValue();
13733     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13734         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13735       return SDValue();
13736     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13737       return SDValue();
13738
13739     // Record which element was extracted.
13740     ExtractedElements |=
13741       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13742
13743     Uses.push_back(Extract);
13744   }
13745
13746   // If not all the elements were used, this may not be worthwhile.
13747   if (ExtractedElements != 15)
13748     return SDValue();
13749
13750   // Ok, we've now decided to do the transformation.
13751   DebugLoc dl = InputVector.getDebugLoc();
13752
13753   // Store the value to a temporary stack slot.
13754   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13755   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13756                             MachinePointerInfo(), false, false, 0);
13757
13758   // Replace each use (extract) with a load of the appropriate element.
13759   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13760        UE = Uses.end(); UI != UE; ++UI) {
13761     SDNode *Extract = *UI;
13762
13763     // cOMpute the element's address.
13764     SDValue Idx = Extract->getOperand(1);
13765     unsigned EltSize =
13766         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13767     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13768     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13769     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13770
13771     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13772                                      StackPtr, OffsetVal);
13773
13774     // Load the scalar.
13775     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13776                                      ScalarAddr, MachinePointerInfo(),
13777                                      false, false, false, 0);
13778
13779     // Replace the exact with the load.
13780     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13781   }
13782
13783   // The replacement was made in place; don't return anything.
13784   return SDValue();
13785 }
13786
13787 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13788 /// nodes.
13789 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13790                                     TargetLowering::DAGCombinerInfo &DCI,
13791                                     const X86Subtarget *Subtarget) {
13792   DebugLoc DL = N->getDebugLoc();
13793   SDValue Cond = N->getOperand(0);
13794   // Get the LHS/RHS of the select.
13795   SDValue LHS = N->getOperand(1);
13796   SDValue RHS = N->getOperand(2);
13797   EVT VT = LHS.getValueType();
13798
13799   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13800   // instructions match the semantics of the common C idiom x<y?x:y but not
13801   // x<=y?x:y, because of how they handle negative zero (which can be
13802   // ignored in unsafe-math mode).
13803   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13804       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13805       (Subtarget->hasSSE2() ||
13806        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13807     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13808
13809     unsigned Opcode = 0;
13810     // Check for x CC y ? x : y.
13811     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13812         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13813       switch (CC) {
13814       default: break;
13815       case ISD::SETULT:
13816         // Converting this to a min would handle NaNs incorrectly, and swapping
13817         // the operands would cause it to handle comparisons between positive
13818         // and negative zero incorrectly.
13819         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13820           if (!DAG.getTarget().Options.UnsafeFPMath &&
13821               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13822             break;
13823           std::swap(LHS, RHS);
13824         }
13825         Opcode = X86ISD::FMIN;
13826         break;
13827       case ISD::SETOLE:
13828         // Converting this to a min would handle comparisons between positive
13829         // and negative zero incorrectly.
13830         if (!DAG.getTarget().Options.UnsafeFPMath &&
13831             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13832           break;
13833         Opcode = X86ISD::FMIN;
13834         break;
13835       case ISD::SETULE:
13836         // Converting this to a min would handle both negative zeros and NaNs
13837         // incorrectly, but we can swap the operands to fix both.
13838         std::swap(LHS, RHS);
13839       case ISD::SETOLT:
13840       case ISD::SETLT:
13841       case ISD::SETLE:
13842         Opcode = X86ISD::FMIN;
13843         break;
13844
13845       case ISD::SETOGE:
13846         // Converting this to a max would handle comparisons between positive
13847         // and negative zero incorrectly.
13848         if (!DAG.getTarget().Options.UnsafeFPMath &&
13849             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13850           break;
13851         Opcode = X86ISD::FMAX;
13852         break;
13853       case ISD::SETUGT:
13854         // Converting this to a max would handle NaNs incorrectly, and swapping
13855         // the operands would cause it to handle comparisons between positive
13856         // and negative zero incorrectly.
13857         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13858           if (!DAG.getTarget().Options.UnsafeFPMath &&
13859               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13860             break;
13861           std::swap(LHS, RHS);
13862         }
13863         Opcode = X86ISD::FMAX;
13864         break;
13865       case ISD::SETUGE:
13866         // Converting this to a max would handle both negative zeros and NaNs
13867         // incorrectly, but we can swap the operands to fix both.
13868         std::swap(LHS, RHS);
13869       case ISD::SETOGT:
13870       case ISD::SETGT:
13871       case ISD::SETGE:
13872         Opcode = X86ISD::FMAX;
13873         break;
13874       }
13875     // Check for x CC y ? y : x -- a min/max with reversed arms.
13876     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13877                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13878       switch (CC) {
13879       default: break;
13880       case ISD::SETOGE:
13881         // Converting this to a min would handle comparisons between positive
13882         // and negative zero incorrectly, and swapping the operands would
13883         // cause it to handle NaNs incorrectly.
13884         if (!DAG.getTarget().Options.UnsafeFPMath &&
13885             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13886           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13887             break;
13888           std::swap(LHS, RHS);
13889         }
13890         Opcode = X86ISD::FMIN;
13891         break;
13892       case ISD::SETUGT:
13893         // Converting this to a min would handle NaNs incorrectly.
13894         if (!DAG.getTarget().Options.UnsafeFPMath &&
13895             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13896           break;
13897         Opcode = X86ISD::FMIN;
13898         break;
13899       case ISD::SETUGE:
13900         // Converting this to a min would handle both negative zeros and NaNs
13901         // incorrectly, but we can swap the operands to fix both.
13902         std::swap(LHS, RHS);
13903       case ISD::SETOGT:
13904       case ISD::SETGT:
13905       case ISD::SETGE:
13906         Opcode = X86ISD::FMIN;
13907         break;
13908
13909       case ISD::SETULT:
13910         // Converting this to a max would handle NaNs incorrectly.
13911         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13912           break;
13913         Opcode = X86ISD::FMAX;
13914         break;
13915       case ISD::SETOLE:
13916         // Converting this to a max would handle comparisons between positive
13917         // and negative zero incorrectly, and swapping the operands would
13918         // cause it to handle NaNs incorrectly.
13919         if (!DAG.getTarget().Options.UnsafeFPMath &&
13920             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13921           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13922             break;
13923           std::swap(LHS, RHS);
13924         }
13925         Opcode = X86ISD::FMAX;
13926         break;
13927       case ISD::SETULE:
13928         // Converting this to a max would handle both negative zeros and NaNs
13929         // incorrectly, but we can swap the operands to fix both.
13930         std::swap(LHS, RHS);
13931       case ISD::SETOLT:
13932       case ISD::SETLT:
13933       case ISD::SETLE:
13934         Opcode = X86ISD::FMAX;
13935         break;
13936       }
13937     }
13938
13939     if (Opcode)
13940       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13941   }
13942
13943   // If this is a select between two integer constants, try to do some
13944   // optimizations.
13945   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13946     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13947       // Don't do this for crazy integer types.
13948       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13949         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13950         // so that TrueC (the true value) is larger than FalseC.
13951         bool NeedsCondInvert = false;
13952
13953         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13954             // Efficiently invertible.
13955             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13956              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13957               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13958           NeedsCondInvert = true;
13959           std::swap(TrueC, FalseC);
13960         }
13961
13962         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13963         if (FalseC->getAPIntValue() == 0 &&
13964             TrueC->getAPIntValue().isPowerOf2()) {
13965           if (NeedsCondInvert) // Invert the condition if needed.
13966             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13967                                DAG.getConstant(1, Cond.getValueType()));
13968
13969           // Zero extend the condition if needed.
13970           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13971
13972           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13973           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13974                              DAG.getConstant(ShAmt, MVT::i8));
13975         }
13976
13977         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13978         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13979           if (NeedsCondInvert) // Invert the condition if needed.
13980             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13981                                DAG.getConstant(1, Cond.getValueType()));
13982
13983           // Zero extend the condition if needed.
13984           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13985                              FalseC->getValueType(0), Cond);
13986           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13987                              SDValue(FalseC, 0));
13988         }
13989
13990         // Optimize cases that will turn into an LEA instruction.  This requires
13991         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13992         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13993           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13994           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13995
13996           bool isFastMultiplier = false;
13997           if (Diff < 10) {
13998             switch ((unsigned char)Diff) {
13999               default: break;
14000               case 1:  // result = add base, cond
14001               case 2:  // result = lea base(    , cond*2)
14002               case 3:  // result = lea base(cond, cond*2)
14003               case 4:  // result = lea base(    , cond*4)
14004               case 5:  // result = lea base(cond, cond*4)
14005               case 8:  // result = lea base(    , cond*8)
14006               case 9:  // result = lea base(cond, cond*8)
14007                 isFastMultiplier = true;
14008                 break;
14009             }
14010           }
14011
14012           if (isFastMultiplier) {
14013             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14014             if (NeedsCondInvert) // Invert the condition if needed.
14015               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14016                                  DAG.getConstant(1, Cond.getValueType()));
14017
14018             // Zero extend the condition if needed.
14019             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14020                                Cond);
14021             // Scale the condition by the difference.
14022             if (Diff != 1)
14023               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14024                                  DAG.getConstant(Diff, Cond.getValueType()));
14025
14026             // Add the base if non-zero.
14027             if (FalseC->getAPIntValue() != 0)
14028               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14029                                  SDValue(FalseC, 0));
14030             return Cond;
14031           }
14032         }
14033       }
14034   }
14035
14036   // Canonicalize max and min:
14037   // (x > y) ? x : y -> (x >= y) ? x : y
14038   // (x < y) ? x : y -> (x <= y) ? x : y
14039   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14040   // the need for an extra compare
14041   // against zero. e.g.
14042   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14043   // subl   %esi, %edi
14044   // testl  %edi, %edi
14045   // movl   $0, %eax
14046   // cmovgl %edi, %eax
14047   // =>
14048   // xorl   %eax, %eax
14049   // subl   %esi, $edi
14050   // cmovsl %eax, %edi
14051   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14052       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14053       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14054     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14055     switch (CC) {
14056     default: break;
14057     case ISD::SETLT:
14058     case ISD::SETGT: {
14059       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14060       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14061                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14062       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14063     }
14064     }
14065   }
14066
14067   // If we know that this node is legal then we know that it is going to be
14068   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14069   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14070   // to simplify previous instructions.
14071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14072   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14073       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14074     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14075
14076     // Don't optimize vector selects that map to mask-registers.
14077     if (BitWidth == 1)
14078       return SDValue();
14079
14080     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14081     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14082
14083     APInt KnownZero, KnownOne;
14084     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14085                                           DCI.isBeforeLegalizeOps());
14086     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14087         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14088       DCI.CommitTargetLoweringOpt(TLO);
14089   }
14090
14091   return SDValue();
14092 }
14093
14094 // Check whether a boolean test is testing a boolean value generated by
14095 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14096 // code.
14097 //
14098 // Simplify the following patterns:
14099 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14100 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14101 // to (Op EFLAGS Cond)
14102 //
14103 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14104 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14105 // to (Op EFLAGS !Cond)
14106 //
14107 // where Op could be BRCOND or CMOV.
14108 //
14109 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14110   // Quit if not CMP and SUB with its value result used.
14111   if (Cmp.getOpcode() != X86ISD::CMP &&
14112       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14113       return SDValue();
14114
14115   // Quit if not used as a boolean value.
14116   if (CC != X86::COND_E && CC != X86::COND_NE)
14117     return SDValue();
14118
14119   // Check CMP operands. One of them should be 0 or 1 and the other should be
14120   // an SetCC or extended from it.
14121   SDValue Op1 = Cmp.getOperand(0);
14122   SDValue Op2 = Cmp.getOperand(1);
14123
14124   SDValue SetCC;
14125   const ConstantSDNode* C = 0;
14126   bool needOppositeCond = (CC == X86::COND_E);
14127
14128   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14129     SetCC = Op2;
14130   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14131     SetCC = Op1;
14132   else // Quit if all operands are not constants.
14133     return SDValue();
14134
14135   if (C->getZExtValue() == 1)
14136     needOppositeCond = !needOppositeCond;
14137   else if (C->getZExtValue() != 0)
14138     // Quit if the constant is neither 0 or 1.
14139     return SDValue();
14140
14141   // Skip 'zext' node.
14142   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14143     SetCC = SetCC.getOperand(0);
14144
14145   // Quit if not SETCC.
14146   // FIXME: So far we only handle the boolean value generated from SETCC. If
14147   // there is other ways to generate boolean values, we need handle them here
14148   // as well.
14149   if (SetCC.getOpcode() != X86ISD::SETCC)
14150     return SDValue();
14151
14152   // Set the condition code or opposite one if necessary.
14153   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14154   if (needOppositeCond)
14155     CC = X86::GetOppositeBranchCondition(CC);
14156
14157   return SetCC.getOperand(1);
14158 }
14159
14160 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14161 /// updated. If only flag result is used and the result is evaluated from a
14162 /// series of element extraction, try to combine it into a PTEST.
14163 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14164                                      SelectionDAG &DAG,
14165                                      const X86Subtarget *Subtarget) {
14166   SDNode *N = Or.getNode();
14167   DebugLoc DL = N->getDebugLoc();
14168
14169   // Only SSE4.1 and beyond supports PTEST or like.
14170   if (!Subtarget->hasSSE41())
14171     return SDValue();
14172
14173   if (N->getOpcode() != X86ISD::OR)
14174     return SDValue();
14175
14176   // Quit if the value result of OR is used.
14177   if (N->hasAnyUseOfValue(0))
14178     return SDValue();
14179
14180   // Quit if not used as a boolean value.
14181   if (CC != X86::COND_E && CC != X86::COND_NE)
14182     return SDValue();
14183
14184   SmallVector<SDValue, 8> Opnds;
14185   SDValue VecIn;
14186   EVT VT = MVT::Other;
14187   unsigned Mask = 0;
14188
14189   // Recognize a special case where a vector is casted into wide integer to
14190   // test all 0s.
14191   Opnds.push_back(N->getOperand(0));
14192   Opnds.push_back(N->getOperand(1));
14193
14194   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14195     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14196     // BFS traverse all OR'd operands.
14197     if (I->getOpcode() == ISD::OR) {
14198       Opnds.push_back(I->getOperand(0));
14199       Opnds.push_back(I->getOperand(1));
14200       // Re-evaluate the number of nodes to be traversed.
14201       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14202       continue;
14203     }
14204
14205     // Quit if a non-EXTRACT_VECTOR_ELT
14206     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14207       return SDValue();
14208
14209     // Quit if without a constant index.
14210     SDValue Idx = I->getOperand(1);
14211     if (!isa<ConstantSDNode>(Idx))
14212       return SDValue();
14213
14214     // Check if all elements are extracted from the same vector.
14215     SDValue ExtractedFromVec = I->getOperand(0);
14216     if (VecIn.getNode() == 0) {
14217       VT = ExtractedFromVec.getValueType();
14218       // FIXME: only 128-bit vector is supported so far.
14219       if (!VT.is128BitVector())
14220         return SDValue();
14221       VecIn = ExtractedFromVec;
14222     } else if (VecIn != ExtractedFromVec)
14223       return SDValue();
14224
14225     // Record the constant index.
14226     Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14227   }
14228
14229   assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14230
14231   // Quit if not all elements are used.
14232   if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14233     return SDValue();
14234
14235   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14236 }
14237
14238 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14239 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14240                                   TargetLowering::DAGCombinerInfo &DCI,
14241                                   const X86Subtarget *Subtarget) {
14242   DebugLoc DL = N->getDebugLoc();
14243
14244   // If the flag operand isn't dead, don't touch this CMOV.
14245   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14246     return SDValue();
14247
14248   SDValue FalseOp = N->getOperand(0);
14249   SDValue TrueOp = N->getOperand(1);
14250   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14251   SDValue Cond = N->getOperand(3);
14252
14253   if (CC == X86::COND_E || CC == X86::COND_NE) {
14254     switch (Cond.getOpcode()) {
14255     default: break;
14256     case X86ISD::BSR:
14257     case X86ISD::BSF:
14258       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14259       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14260         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14261     }
14262   }
14263
14264   SDValue Flags;
14265
14266   Flags = checkBoolTestSetCCCombine(Cond, CC);
14267   if (Flags.getNode() &&
14268       // Extra check as FCMOV only supports a subset of X86 cond.
14269       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14270     SDValue Ops[] = { FalseOp, TrueOp,
14271                       DAG.getConstant(CC, MVT::i8), Flags };
14272     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14273                        Ops, array_lengthof(Ops));
14274   }
14275
14276   Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14277   if (Flags.getNode()) {
14278     SDValue Ops[] = { FalseOp, TrueOp,
14279                       DAG.getConstant(CC, MVT::i8), Flags };
14280     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14281                        Ops, array_lengthof(Ops));
14282   }
14283
14284   // If this is a select between two integer constants, try to do some
14285   // optimizations.  Note that the operands are ordered the opposite of SELECT
14286   // operands.
14287   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14288     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14289       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14290       // larger than FalseC (the false value).
14291       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14292         CC = X86::GetOppositeBranchCondition(CC);
14293         std::swap(TrueC, FalseC);
14294       }
14295
14296       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14297       // This is efficient for any integer data type (including i8/i16) and
14298       // shift amount.
14299       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14300         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14301                            DAG.getConstant(CC, MVT::i8), Cond);
14302
14303         // Zero extend the condition if needed.
14304         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14305
14306         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14307         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14308                            DAG.getConstant(ShAmt, MVT::i8));
14309         if (N->getNumValues() == 2)  // Dead flag value?
14310           return DCI.CombineTo(N, Cond, SDValue());
14311         return Cond;
14312       }
14313
14314       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14315       // for any integer data type, including i8/i16.
14316       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14317         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14318                            DAG.getConstant(CC, MVT::i8), Cond);
14319
14320         // Zero extend the condition if needed.
14321         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14322                            FalseC->getValueType(0), Cond);
14323         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14324                            SDValue(FalseC, 0));
14325
14326         if (N->getNumValues() == 2)  // Dead flag value?
14327           return DCI.CombineTo(N, Cond, SDValue());
14328         return Cond;
14329       }
14330
14331       // Optimize cases that will turn into an LEA instruction.  This requires
14332       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14333       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14334         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14335         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14336
14337         bool isFastMultiplier = false;
14338         if (Diff < 10) {
14339           switch ((unsigned char)Diff) {
14340           default: break;
14341           case 1:  // result = add base, cond
14342           case 2:  // result = lea base(    , cond*2)
14343           case 3:  // result = lea base(cond, cond*2)
14344           case 4:  // result = lea base(    , cond*4)
14345           case 5:  // result = lea base(cond, cond*4)
14346           case 8:  // result = lea base(    , cond*8)
14347           case 9:  // result = lea base(cond, cond*8)
14348             isFastMultiplier = true;
14349             break;
14350           }
14351         }
14352
14353         if (isFastMultiplier) {
14354           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14355           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14356                              DAG.getConstant(CC, MVT::i8), Cond);
14357           // Zero extend the condition if needed.
14358           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14359                              Cond);
14360           // Scale the condition by the difference.
14361           if (Diff != 1)
14362             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14363                                DAG.getConstant(Diff, Cond.getValueType()));
14364
14365           // Add the base if non-zero.
14366           if (FalseC->getAPIntValue() != 0)
14367             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14368                                SDValue(FalseC, 0));
14369           if (N->getNumValues() == 2)  // Dead flag value?
14370             return DCI.CombineTo(N, Cond, SDValue());
14371           return Cond;
14372         }
14373       }
14374     }
14375   }
14376   return SDValue();
14377 }
14378
14379
14380 /// PerformMulCombine - Optimize a single multiply with constant into two
14381 /// in order to implement it with two cheaper instructions, e.g.
14382 /// LEA + SHL, LEA + LEA.
14383 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14384                                  TargetLowering::DAGCombinerInfo &DCI) {
14385   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14386     return SDValue();
14387
14388   EVT VT = N->getValueType(0);
14389   if (VT != MVT::i64)
14390     return SDValue();
14391
14392   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14393   if (!C)
14394     return SDValue();
14395   uint64_t MulAmt = C->getZExtValue();
14396   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14397     return SDValue();
14398
14399   uint64_t MulAmt1 = 0;
14400   uint64_t MulAmt2 = 0;
14401   if ((MulAmt % 9) == 0) {
14402     MulAmt1 = 9;
14403     MulAmt2 = MulAmt / 9;
14404   } else if ((MulAmt % 5) == 0) {
14405     MulAmt1 = 5;
14406     MulAmt2 = MulAmt / 5;
14407   } else if ((MulAmt % 3) == 0) {
14408     MulAmt1 = 3;
14409     MulAmt2 = MulAmt / 3;
14410   }
14411   if (MulAmt2 &&
14412       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14413     DebugLoc DL = N->getDebugLoc();
14414
14415     if (isPowerOf2_64(MulAmt2) &&
14416         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14417       // If second multiplifer is pow2, issue it first. We want the multiply by
14418       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14419       // is an add.
14420       std::swap(MulAmt1, MulAmt2);
14421
14422     SDValue NewMul;
14423     if (isPowerOf2_64(MulAmt1))
14424       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14425                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14426     else
14427       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14428                            DAG.getConstant(MulAmt1, VT));
14429
14430     if (isPowerOf2_64(MulAmt2))
14431       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14432                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14433     else
14434       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14435                            DAG.getConstant(MulAmt2, VT));
14436
14437     // Do not add new nodes to DAG combiner worklist.
14438     DCI.CombineTo(N, NewMul, false);
14439   }
14440   return SDValue();
14441 }
14442
14443 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14444   SDValue N0 = N->getOperand(0);
14445   SDValue N1 = N->getOperand(1);
14446   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14447   EVT VT = N0.getValueType();
14448
14449   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14450   // since the result of setcc_c is all zero's or all ones.
14451   if (VT.isInteger() && !VT.isVector() &&
14452       N1C && N0.getOpcode() == ISD::AND &&
14453       N0.getOperand(1).getOpcode() == ISD::Constant) {
14454     SDValue N00 = N0.getOperand(0);
14455     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14456         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14457           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14458          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14459       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14460       APInt ShAmt = N1C->getAPIntValue();
14461       Mask = Mask.shl(ShAmt);
14462       if (Mask != 0)
14463         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14464                            N00, DAG.getConstant(Mask, VT));
14465     }
14466   }
14467
14468
14469   // Hardware support for vector shifts is sparse which makes us scalarize the
14470   // vector operations in many cases. Also, on sandybridge ADD is faster than
14471   // shl.
14472   // (shl V, 1) -> add V,V
14473   if (isSplatVector(N1.getNode())) {
14474     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14475     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14476     // We shift all of the values by one. In many cases we do not have
14477     // hardware support for this operation. This is better expressed as an ADD
14478     // of two values.
14479     if (N1C && (1 == N1C->getZExtValue())) {
14480       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14481     }
14482   }
14483
14484   return SDValue();
14485 }
14486
14487 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14488 ///                       when possible.
14489 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14490                                    TargetLowering::DAGCombinerInfo &DCI,
14491                                    const X86Subtarget *Subtarget) {
14492   EVT VT = N->getValueType(0);
14493   if (N->getOpcode() == ISD::SHL) {
14494     SDValue V = PerformSHLCombine(N, DAG);
14495     if (V.getNode()) return V;
14496   }
14497
14498   // On X86 with SSE2 support, we can transform this to a vector shift if
14499   // all elements are shifted by the same amount.  We can't do this in legalize
14500   // because the a constant vector is typically transformed to a constant pool
14501   // so we have no knowledge of the shift amount.
14502   if (!Subtarget->hasSSE2())
14503     return SDValue();
14504
14505   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14506       (!Subtarget->hasAVX2() ||
14507        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14508     return SDValue();
14509
14510   SDValue ShAmtOp = N->getOperand(1);
14511   EVT EltVT = VT.getVectorElementType();
14512   DebugLoc DL = N->getDebugLoc();
14513   SDValue BaseShAmt = SDValue();
14514   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14515     unsigned NumElts = VT.getVectorNumElements();
14516     unsigned i = 0;
14517     for (; i != NumElts; ++i) {
14518       SDValue Arg = ShAmtOp.getOperand(i);
14519       if (Arg.getOpcode() == ISD::UNDEF) continue;
14520       BaseShAmt = Arg;
14521       break;
14522     }
14523     // Handle the case where the build_vector is all undef
14524     // FIXME: Should DAG allow this?
14525     if (i == NumElts)
14526       return SDValue();
14527
14528     for (; i != NumElts; ++i) {
14529       SDValue Arg = ShAmtOp.getOperand(i);
14530       if (Arg.getOpcode() == ISD::UNDEF) continue;
14531       if (Arg != BaseShAmt) {
14532         return SDValue();
14533       }
14534     }
14535   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14536              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14537     SDValue InVec = ShAmtOp.getOperand(0);
14538     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14539       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14540       unsigned i = 0;
14541       for (; i != NumElts; ++i) {
14542         SDValue Arg = InVec.getOperand(i);
14543         if (Arg.getOpcode() == ISD::UNDEF) continue;
14544         BaseShAmt = Arg;
14545         break;
14546       }
14547     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14548        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14549          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14550          if (C->getZExtValue() == SplatIdx)
14551            BaseShAmt = InVec.getOperand(1);
14552        }
14553     }
14554     if (BaseShAmt.getNode() == 0) {
14555       // Don't create instructions with illegal types after legalize
14556       // types has run.
14557       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14558           !DCI.isBeforeLegalize())
14559         return SDValue();
14560
14561       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14562                               DAG.getIntPtrConstant(0));
14563     }
14564   } else
14565     return SDValue();
14566
14567   // The shift amount is an i32.
14568   if (EltVT.bitsGT(MVT::i32))
14569     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14570   else if (EltVT.bitsLT(MVT::i32))
14571     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14572
14573   // The shift amount is identical so we can do a vector shift.
14574   SDValue  ValOp = N->getOperand(0);
14575   switch (N->getOpcode()) {
14576   default:
14577     llvm_unreachable("Unknown shift opcode!");
14578   case ISD::SHL:
14579     switch (VT.getSimpleVT().SimpleTy) {
14580     default: return SDValue();
14581     case MVT::v2i64:
14582     case MVT::v4i32:
14583     case MVT::v8i16:
14584     case MVT::v4i64:
14585     case MVT::v8i32:
14586     case MVT::v16i16:
14587       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14588     }
14589   case ISD::SRA:
14590     switch (VT.getSimpleVT().SimpleTy) {
14591     default: return SDValue();
14592     case MVT::v4i32:
14593     case MVT::v8i16:
14594     case MVT::v8i32:
14595     case MVT::v16i16:
14596       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14597     }
14598   case ISD::SRL:
14599     switch (VT.getSimpleVT().SimpleTy) {
14600     default: return SDValue();
14601     case MVT::v2i64:
14602     case MVT::v4i32:
14603     case MVT::v8i16:
14604     case MVT::v4i64:
14605     case MVT::v8i32:
14606     case MVT::v16i16:
14607       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14608     }
14609   }
14610 }
14611
14612
14613 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14614 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14615 // and friends.  Likewise for OR -> CMPNEQSS.
14616 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14617                             TargetLowering::DAGCombinerInfo &DCI,
14618                             const X86Subtarget *Subtarget) {
14619   unsigned opcode;
14620
14621   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14622   // we're requiring SSE2 for both.
14623   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14624     SDValue N0 = N->getOperand(0);
14625     SDValue N1 = N->getOperand(1);
14626     SDValue CMP0 = N0->getOperand(1);
14627     SDValue CMP1 = N1->getOperand(1);
14628     DebugLoc DL = N->getDebugLoc();
14629
14630     // The SETCCs should both refer to the same CMP.
14631     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14632       return SDValue();
14633
14634     SDValue CMP00 = CMP0->getOperand(0);
14635     SDValue CMP01 = CMP0->getOperand(1);
14636     EVT     VT    = CMP00.getValueType();
14637
14638     if (VT == MVT::f32 || VT == MVT::f64) {
14639       bool ExpectingFlags = false;
14640       // Check for any users that want flags:
14641       for (SDNode::use_iterator UI = N->use_begin(),
14642              UE = N->use_end();
14643            !ExpectingFlags && UI != UE; ++UI)
14644         switch (UI->getOpcode()) {
14645         default:
14646         case ISD::BR_CC:
14647         case ISD::BRCOND:
14648         case ISD::SELECT:
14649           ExpectingFlags = true;
14650           break;
14651         case ISD::CopyToReg:
14652         case ISD::SIGN_EXTEND:
14653         case ISD::ZERO_EXTEND:
14654         case ISD::ANY_EXTEND:
14655           break;
14656         }
14657
14658       if (!ExpectingFlags) {
14659         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14660         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14661
14662         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14663           X86::CondCode tmp = cc0;
14664           cc0 = cc1;
14665           cc1 = tmp;
14666         }
14667
14668         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14669             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14670           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14671           X86ISD::NodeType NTOperator = is64BitFP ?
14672             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14673           // FIXME: need symbolic constants for these magic numbers.
14674           // See X86ATTInstPrinter.cpp:printSSECC().
14675           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14676           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14677                                               DAG.getConstant(x86cc, MVT::i8));
14678           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14679                                               OnesOrZeroesF);
14680           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14681                                       DAG.getConstant(1, MVT::i32));
14682           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14683           return OneBitOfTruth;
14684         }
14685       }
14686     }
14687   }
14688   return SDValue();
14689 }
14690
14691 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14692 /// so it can be folded inside ANDNP.
14693 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14694   EVT VT = N->getValueType(0);
14695
14696   // Match direct AllOnes for 128 and 256-bit vectors
14697   if (ISD::isBuildVectorAllOnes(N))
14698     return true;
14699
14700   // Look through a bit convert.
14701   if (N->getOpcode() == ISD::BITCAST)
14702     N = N->getOperand(0).getNode();
14703
14704   // Sometimes the operand may come from a insert_subvector building a 256-bit
14705   // allones vector
14706   if (VT.is256BitVector() &&
14707       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14708     SDValue V1 = N->getOperand(0);
14709     SDValue V2 = N->getOperand(1);
14710
14711     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14712         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14713         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14714         ISD::isBuildVectorAllOnes(V2.getNode()))
14715       return true;
14716   }
14717
14718   return false;
14719 }
14720
14721 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14722                                  TargetLowering::DAGCombinerInfo &DCI,
14723                                  const X86Subtarget *Subtarget) {
14724   if (DCI.isBeforeLegalizeOps())
14725     return SDValue();
14726
14727   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14728   if (R.getNode())
14729     return R;
14730
14731   EVT VT = N->getValueType(0);
14732
14733   // Create ANDN, BLSI, and BLSR instructions
14734   // BLSI is X & (-X)
14735   // BLSR is X & (X-1)
14736   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14737     SDValue N0 = N->getOperand(0);
14738     SDValue N1 = N->getOperand(1);
14739     DebugLoc DL = N->getDebugLoc();
14740
14741     // Check LHS for not
14742     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14743       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14744     // Check RHS for not
14745     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14746       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14747
14748     // Check LHS for neg
14749     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14750         isZero(N0.getOperand(0)))
14751       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14752
14753     // Check RHS for neg
14754     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14755         isZero(N1.getOperand(0)))
14756       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14757
14758     // Check LHS for X-1
14759     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14760         isAllOnes(N0.getOperand(1)))
14761       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14762
14763     // Check RHS for X-1
14764     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14765         isAllOnes(N1.getOperand(1)))
14766       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14767
14768     return SDValue();
14769   }
14770
14771   // Want to form ANDNP nodes:
14772   // 1) In the hopes of then easily combining them with OR and AND nodes
14773   //    to form PBLEND/PSIGN.
14774   // 2) To match ANDN packed intrinsics
14775   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14776     return SDValue();
14777
14778   SDValue N0 = N->getOperand(0);
14779   SDValue N1 = N->getOperand(1);
14780   DebugLoc DL = N->getDebugLoc();
14781
14782   // Check LHS for vnot
14783   if (N0.getOpcode() == ISD::XOR &&
14784       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14785       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14786     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14787
14788   // Check RHS for vnot
14789   if (N1.getOpcode() == ISD::XOR &&
14790       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14791       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14792     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14793
14794   return SDValue();
14795 }
14796
14797 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14798                                 TargetLowering::DAGCombinerInfo &DCI,
14799                                 const X86Subtarget *Subtarget) {
14800   if (DCI.isBeforeLegalizeOps())
14801     return SDValue();
14802
14803   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14804   if (R.getNode())
14805     return R;
14806
14807   EVT VT = N->getValueType(0);
14808
14809   SDValue N0 = N->getOperand(0);
14810   SDValue N1 = N->getOperand(1);
14811
14812   // look for psign/blend
14813   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14814     if (!Subtarget->hasSSSE3() ||
14815         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14816       return SDValue();
14817
14818     // Canonicalize pandn to RHS
14819     if (N0.getOpcode() == X86ISD::ANDNP)
14820       std::swap(N0, N1);
14821     // or (and (m, y), (pandn m, x))
14822     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14823       SDValue Mask = N1.getOperand(0);
14824       SDValue X    = N1.getOperand(1);
14825       SDValue Y;
14826       if (N0.getOperand(0) == Mask)
14827         Y = N0.getOperand(1);
14828       if (N0.getOperand(1) == Mask)
14829         Y = N0.getOperand(0);
14830
14831       // Check to see if the mask appeared in both the AND and ANDNP and
14832       if (!Y.getNode())
14833         return SDValue();
14834
14835       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14836       // Look through mask bitcast.
14837       if (Mask.getOpcode() == ISD::BITCAST)
14838         Mask = Mask.getOperand(0);
14839       if (X.getOpcode() == ISD::BITCAST)
14840         X = X.getOperand(0);
14841       if (Y.getOpcode() == ISD::BITCAST)
14842         Y = Y.getOperand(0);
14843
14844       EVT MaskVT = Mask.getValueType();
14845
14846       // Validate that the Mask operand is a vector sra node.
14847       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14848       // there is no psrai.b
14849       if (Mask.getOpcode() != X86ISD::VSRAI)
14850         return SDValue();
14851
14852       // Check that the SRA is all signbits.
14853       SDValue SraC = Mask.getOperand(1);
14854       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14855       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14856       if ((SraAmt + 1) != EltBits)
14857         return SDValue();
14858
14859       DebugLoc DL = N->getDebugLoc();
14860
14861       // Now we know we at least have a plendvb with the mask val.  See if
14862       // we can form a psignb/w/d.
14863       // psign = x.type == y.type == mask.type && y = sub(0, x);
14864       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14865           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14866           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14867         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14868                "Unsupported VT for PSIGN");
14869         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14870         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14871       }
14872       // PBLENDVB only available on SSE 4.1
14873       if (!Subtarget->hasSSE41())
14874         return SDValue();
14875
14876       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14877
14878       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14879       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14880       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14881       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14882       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14883     }
14884   }
14885
14886   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14887     return SDValue();
14888
14889   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14890   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14891     std::swap(N0, N1);
14892   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14893     return SDValue();
14894   if (!N0.hasOneUse() || !N1.hasOneUse())
14895     return SDValue();
14896
14897   SDValue ShAmt0 = N0.getOperand(1);
14898   if (ShAmt0.getValueType() != MVT::i8)
14899     return SDValue();
14900   SDValue ShAmt1 = N1.getOperand(1);
14901   if (ShAmt1.getValueType() != MVT::i8)
14902     return SDValue();
14903   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14904     ShAmt0 = ShAmt0.getOperand(0);
14905   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14906     ShAmt1 = ShAmt1.getOperand(0);
14907
14908   DebugLoc DL = N->getDebugLoc();
14909   unsigned Opc = X86ISD::SHLD;
14910   SDValue Op0 = N0.getOperand(0);
14911   SDValue Op1 = N1.getOperand(0);
14912   if (ShAmt0.getOpcode() == ISD::SUB) {
14913     Opc = X86ISD::SHRD;
14914     std::swap(Op0, Op1);
14915     std::swap(ShAmt0, ShAmt1);
14916   }
14917
14918   unsigned Bits = VT.getSizeInBits();
14919   if (ShAmt1.getOpcode() == ISD::SUB) {
14920     SDValue Sum = ShAmt1.getOperand(0);
14921     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14922       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14923       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14924         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14925       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14926         return DAG.getNode(Opc, DL, VT,
14927                            Op0, Op1,
14928                            DAG.getNode(ISD::TRUNCATE, DL,
14929                                        MVT::i8, ShAmt0));
14930     }
14931   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14932     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14933     if (ShAmt0C &&
14934         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14935       return DAG.getNode(Opc, DL, VT,
14936                          N0.getOperand(0), N1.getOperand(0),
14937                          DAG.getNode(ISD::TRUNCATE, DL,
14938                                        MVT::i8, ShAmt0));
14939   }
14940
14941   return SDValue();
14942 }
14943
14944 // Generate NEG and CMOV for integer abs.
14945 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14946   EVT VT = N->getValueType(0);
14947
14948   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14949   // 8-bit integer abs to NEG and CMOV.
14950   if (VT.isInteger() && VT.getSizeInBits() == 8)
14951     return SDValue();
14952
14953   SDValue N0 = N->getOperand(0);
14954   SDValue N1 = N->getOperand(1);
14955   DebugLoc DL = N->getDebugLoc();
14956
14957   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14958   // and change it to SUB and CMOV.
14959   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14960       N0.getOpcode() == ISD::ADD &&
14961       N0.getOperand(1) == N1 &&
14962       N1.getOpcode() == ISD::SRA &&
14963       N1.getOperand(0) == N0.getOperand(0))
14964     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14965       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14966         // Generate SUB & CMOV.
14967         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14968                                   DAG.getConstant(0, VT), N0.getOperand(0));
14969
14970         SDValue Ops[] = { N0.getOperand(0), Neg,
14971                           DAG.getConstant(X86::COND_GE, MVT::i8),
14972                           SDValue(Neg.getNode(), 1) };
14973         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14974                            Ops, array_lengthof(Ops));
14975       }
14976   return SDValue();
14977 }
14978
14979 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14980 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14981                                  TargetLowering::DAGCombinerInfo &DCI,
14982                                  const X86Subtarget *Subtarget) {
14983   if (DCI.isBeforeLegalizeOps())
14984     return SDValue();
14985
14986   if (Subtarget->hasCMov()) {
14987     SDValue RV = performIntegerAbsCombine(N, DAG);
14988     if (RV.getNode())
14989       return RV;
14990   }
14991
14992   // Try forming BMI if it is available.
14993   if (!Subtarget->hasBMI())
14994     return SDValue();
14995
14996   EVT VT = N->getValueType(0);
14997
14998   if (VT != MVT::i32 && VT != MVT::i64)
14999     return SDValue();
15000
15001   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15002
15003   // Create BLSMSK instructions by finding X ^ (X-1)
15004   SDValue N0 = N->getOperand(0);
15005   SDValue N1 = N->getOperand(1);
15006   DebugLoc DL = N->getDebugLoc();
15007
15008   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15009       isAllOnes(N0.getOperand(1)))
15010     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15011
15012   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15013       isAllOnes(N1.getOperand(1)))
15014     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15015
15016   return SDValue();
15017 }
15018
15019 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15020 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15021                                   TargetLowering::DAGCombinerInfo &DCI,
15022                                   const X86Subtarget *Subtarget) {
15023   LoadSDNode *Ld = cast<LoadSDNode>(N);
15024   EVT RegVT = Ld->getValueType(0);
15025   EVT MemVT = Ld->getMemoryVT();
15026   DebugLoc dl = Ld->getDebugLoc();
15027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15028
15029   ISD::LoadExtType Ext = Ld->getExtensionType();
15030
15031   // If this is a vector EXT Load then attempt to optimize it using a
15032   // shuffle. We need SSE4 for the shuffles.
15033   // TODO: It is possible to support ZExt by zeroing the undef values
15034   // during the shuffle phase or after the shuffle.
15035   if (RegVT.isVector() && RegVT.isInteger() &&
15036       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15037     assert(MemVT != RegVT && "Cannot extend to the same type");
15038     assert(MemVT.isVector() && "Must load a vector from memory");
15039
15040     unsigned NumElems = RegVT.getVectorNumElements();
15041     unsigned RegSz = RegVT.getSizeInBits();
15042     unsigned MemSz = MemVT.getSizeInBits();
15043     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15044
15045     // All sizes must be a power of two.
15046     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15047       return SDValue();
15048
15049     // Attempt to load the original value using scalar loads.
15050     // Find the largest scalar type that divides the total loaded size.
15051     MVT SclrLoadTy = MVT::i8;
15052     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15053          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15054       MVT Tp = (MVT::SimpleValueType)tp;
15055       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15056         SclrLoadTy = Tp;
15057       }
15058     }
15059
15060     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15061     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15062         (64 <= MemSz))
15063       SclrLoadTy = MVT::f64;
15064
15065     // Calculate the number of scalar loads that we need to perform
15066     // in order to load our vector from memory.
15067     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15068
15069     // Represent our vector as a sequence of elements which are the
15070     // largest scalar that we can load.
15071     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15072       RegSz/SclrLoadTy.getSizeInBits());
15073
15074     // Represent the data using the same element type that is stored in
15075     // memory. In practice, we ''widen'' MemVT.
15076     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15077                                   RegSz/MemVT.getScalarType().getSizeInBits());
15078
15079     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15080       "Invalid vector type");
15081
15082     // We can't shuffle using an illegal type.
15083     if (!TLI.isTypeLegal(WideVecVT))
15084       return SDValue();
15085
15086     SmallVector<SDValue, 8> Chains;
15087     SDValue Ptr = Ld->getBasePtr();
15088     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15089                                         TLI.getPointerTy());
15090     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15091
15092     for (unsigned i = 0; i < NumLoads; ++i) {
15093       // Perform a single load.
15094       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15095                                        Ptr, Ld->getPointerInfo(),
15096                                        Ld->isVolatile(), Ld->isNonTemporal(),
15097                                        Ld->isInvariant(), Ld->getAlignment());
15098       Chains.push_back(ScalarLoad.getValue(1));
15099       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15100       // another round of DAGCombining.
15101       if (i == 0)
15102         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15103       else
15104         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15105                           ScalarLoad, DAG.getIntPtrConstant(i));
15106
15107       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15108     }
15109
15110     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15111                                Chains.size());
15112
15113     // Bitcast the loaded value to a vector of the original element type, in
15114     // the size of the target vector type.
15115     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15116     unsigned SizeRatio = RegSz/MemSz;
15117
15118     // Redistribute the loaded elements into the different locations.
15119     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15120     for (unsigned i = 0; i != NumElems; ++i)
15121       ShuffleVec[i*SizeRatio] = i;
15122
15123     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15124                                          DAG.getUNDEF(WideVecVT),
15125                                          &ShuffleVec[0]);
15126
15127     // Bitcast to the requested type.
15128     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15129     // Replace the original load with the new sequence
15130     // and return the new chain.
15131     return DCI.CombineTo(N, Shuff, TF, true);
15132   }
15133
15134   return SDValue();
15135 }
15136
15137 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15138 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15139                                    const X86Subtarget *Subtarget) {
15140   StoreSDNode *St = cast<StoreSDNode>(N);
15141   EVT VT = St->getValue().getValueType();
15142   EVT StVT = St->getMemoryVT();
15143   DebugLoc dl = St->getDebugLoc();
15144   SDValue StoredVal = St->getOperand(1);
15145   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15146
15147   // If we are saving a concatenation of two XMM registers, perform two stores.
15148   // On Sandy Bridge, 256-bit memory operations are executed by two
15149   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15150   // memory  operation.
15151   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15152       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15153       StoredVal.getNumOperands() == 2) {
15154     SDValue Value0 = StoredVal.getOperand(0);
15155     SDValue Value1 = StoredVal.getOperand(1);
15156
15157     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15158     SDValue Ptr0 = St->getBasePtr();
15159     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15160
15161     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15162                                 St->getPointerInfo(), St->isVolatile(),
15163                                 St->isNonTemporal(), St->getAlignment());
15164     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15165                                 St->getPointerInfo(), St->isVolatile(),
15166                                 St->isNonTemporal(), St->getAlignment());
15167     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15168   }
15169
15170   // Optimize trunc store (of multiple scalars) to shuffle and store.
15171   // First, pack all of the elements in one place. Next, store to memory
15172   // in fewer chunks.
15173   if (St->isTruncatingStore() && VT.isVector()) {
15174     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15175     unsigned NumElems = VT.getVectorNumElements();
15176     assert(StVT != VT && "Cannot truncate to the same type");
15177     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15178     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15179
15180     // From, To sizes and ElemCount must be pow of two
15181     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15182     // We are going to use the original vector elt for storing.
15183     // Accumulated smaller vector elements must be a multiple of the store size.
15184     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15185
15186     unsigned SizeRatio  = FromSz / ToSz;
15187
15188     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15189
15190     // Create a type on which we perform the shuffle
15191     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15192             StVT.getScalarType(), NumElems*SizeRatio);
15193
15194     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15195
15196     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15197     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15198     for (unsigned i = 0; i != NumElems; ++i)
15199       ShuffleVec[i] = i * SizeRatio;
15200
15201     // Can't shuffle using an illegal type.
15202     if (!TLI.isTypeLegal(WideVecVT))
15203       return SDValue();
15204
15205     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15206                                          DAG.getUNDEF(WideVecVT),
15207                                          &ShuffleVec[0]);
15208     // At this point all of the data is stored at the bottom of the
15209     // register. We now need to save it to mem.
15210
15211     // Find the largest store unit
15212     MVT StoreType = MVT::i8;
15213     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15214          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15215       MVT Tp = (MVT::SimpleValueType)tp;
15216       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15217         StoreType = Tp;
15218     }
15219
15220     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15221     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15222         (64 <= NumElems * ToSz))
15223       StoreType = MVT::f64;
15224
15225     // Bitcast the original vector into a vector of store-size units
15226     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15227             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15228     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15229     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15230     SmallVector<SDValue, 8> Chains;
15231     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15232                                         TLI.getPointerTy());
15233     SDValue Ptr = St->getBasePtr();
15234
15235     // Perform one or more big stores into memory.
15236     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15237       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15238                                    StoreType, ShuffWide,
15239                                    DAG.getIntPtrConstant(i));
15240       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15241                                 St->getPointerInfo(), St->isVolatile(),
15242                                 St->isNonTemporal(), St->getAlignment());
15243       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15244       Chains.push_back(Ch);
15245     }
15246
15247     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15248                                Chains.size());
15249   }
15250
15251
15252   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15253   // the FP state in cases where an emms may be missing.
15254   // A preferable solution to the general problem is to figure out the right
15255   // places to insert EMMS.  This qualifies as a quick hack.
15256
15257   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15258   if (VT.getSizeInBits() != 64)
15259     return SDValue();
15260
15261   const Function *F = DAG.getMachineFunction().getFunction();
15262   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15263   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15264                      && Subtarget->hasSSE2();
15265   if ((VT.isVector() ||
15266        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15267       isa<LoadSDNode>(St->getValue()) &&
15268       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15269       St->getChain().hasOneUse() && !St->isVolatile()) {
15270     SDNode* LdVal = St->getValue().getNode();
15271     LoadSDNode *Ld = 0;
15272     int TokenFactorIndex = -1;
15273     SmallVector<SDValue, 8> Ops;
15274     SDNode* ChainVal = St->getChain().getNode();
15275     // Must be a store of a load.  We currently handle two cases:  the load
15276     // is a direct child, and it's under an intervening TokenFactor.  It is
15277     // possible to dig deeper under nested TokenFactors.
15278     if (ChainVal == LdVal)
15279       Ld = cast<LoadSDNode>(St->getChain());
15280     else if (St->getValue().hasOneUse() &&
15281              ChainVal->getOpcode() == ISD::TokenFactor) {
15282       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15283         if (ChainVal->getOperand(i).getNode() == LdVal) {
15284           TokenFactorIndex = i;
15285           Ld = cast<LoadSDNode>(St->getValue());
15286         } else
15287           Ops.push_back(ChainVal->getOperand(i));
15288       }
15289     }
15290
15291     if (!Ld || !ISD::isNormalLoad(Ld))
15292       return SDValue();
15293
15294     // If this is not the MMX case, i.e. we are just turning i64 load/store
15295     // into f64 load/store, avoid the transformation if there are multiple
15296     // uses of the loaded value.
15297     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15298       return SDValue();
15299
15300     DebugLoc LdDL = Ld->getDebugLoc();
15301     DebugLoc StDL = N->getDebugLoc();
15302     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15303     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15304     // pair instead.
15305     if (Subtarget->is64Bit() || F64IsLegal) {
15306       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15307       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15308                                   Ld->getPointerInfo(), Ld->isVolatile(),
15309                                   Ld->isNonTemporal(), Ld->isInvariant(),
15310                                   Ld->getAlignment());
15311       SDValue NewChain = NewLd.getValue(1);
15312       if (TokenFactorIndex != -1) {
15313         Ops.push_back(NewChain);
15314         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15315                                Ops.size());
15316       }
15317       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15318                           St->getPointerInfo(),
15319                           St->isVolatile(), St->isNonTemporal(),
15320                           St->getAlignment());
15321     }
15322
15323     // Otherwise, lower to two pairs of 32-bit loads / stores.
15324     SDValue LoAddr = Ld->getBasePtr();
15325     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15326                                  DAG.getConstant(4, MVT::i32));
15327
15328     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15329                                Ld->getPointerInfo(),
15330                                Ld->isVolatile(), Ld->isNonTemporal(),
15331                                Ld->isInvariant(), Ld->getAlignment());
15332     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15333                                Ld->getPointerInfo().getWithOffset(4),
15334                                Ld->isVolatile(), Ld->isNonTemporal(),
15335                                Ld->isInvariant(),
15336                                MinAlign(Ld->getAlignment(), 4));
15337
15338     SDValue NewChain = LoLd.getValue(1);
15339     if (TokenFactorIndex != -1) {
15340       Ops.push_back(LoLd);
15341       Ops.push_back(HiLd);
15342       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15343                              Ops.size());
15344     }
15345
15346     LoAddr = St->getBasePtr();
15347     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15348                          DAG.getConstant(4, MVT::i32));
15349
15350     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15351                                 St->getPointerInfo(),
15352                                 St->isVolatile(), St->isNonTemporal(),
15353                                 St->getAlignment());
15354     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15355                                 St->getPointerInfo().getWithOffset(4),
15356                                 St->isVolatile(),
15357                                 St->isNonTemporal(),
15358                                 MinAlign(St->getAlignment(), 4));
15359     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15360   }
15361   return SDValue();
15362 }
15363
15364 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15365 /// and return the operands for the horizontal operation in LHS and RHS.  A
15366 /// horizontal operation performs the binary operation on successive elements
15367 /// of its first operand, then on successive elements of its second operand,
15368 /// returning the resulting values in a vector.  For example, if
15369 ///   A = < float a0, float a1, float a2, float a3 >
15370 /// and
15371 ///   B = < float b0, float b1, float b2, float b3 >
15372 /// then the result of doing a horizontal operation on A and B is
15373 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15374 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15375 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15376 /// set to A, RHS to B, and the routine returns 'true'.
15377 /// Note that the binary operation should have the property that if one of the
15378 /// operands is UNDEF then the result is UNDEF.
15379 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15380   // Look for the following pattern: if
15381   //   A = < float a0, float a1, float a2, float a3 >
15382   //   B = < float b0, float b1, float b2, float b3 >
15383   // and
15384   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15385   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15386   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15387   // which is A horizontal-op B.
15388
15389   // At least one of the operands should be a vector shuffle.
15390   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15391       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15392     return false;
15393
15394   EVT VT = LHS.getValueType();
15395
15396   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15397          "Unsupported vector type for horizontal add/sub");
15398
15399   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15400   // operate independently on 128-bit lanes.
15401   unsigned NumElts = VT.getVectorNumElements();
15402   unsigned NumLanes = VT.getSizeInBits()/128;
15403   unsigned NumLaneElts = NumElts / NumLanes;
15404   assert((NumLaneElts % 2 == 0) &&
15405          "Vector type should have an even number of elements in each lane");
15406   unsigned HalfLaneElts = NumLaneElts/2;
15407
15408   // View LHS in the form
15409   //   LHS = VECTOR_SHUFFLE A, B, LMask
15410   // If LHS is not a shuffle then pretend it is the shuffle
15411   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15412   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15413   // type VT.
15414   SDValue A, B;
15415   SmallVector<int, 16> LMask(NumElts);
15416   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15417     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15418       A = LHS.getOperand(0);
15419     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15420       B = LHS.getOperand(1);
15421     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15422     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15423   } else {
15424     if (LHS.getOpcode() != ISD::UNDEF)
15425       A = LHS;
15426     for (unsigned i = 0; i != NumElts; ++i)
15427       LMask[i] = i;
15428   }
15429
15430   // Likewise, view RHS in the form
15431   //   RHS = VECTOR_SHUFFLE C, D, RMask
15432   SDValue C, D;
15433   SmallVector<int, 16> RMask(NumElts);
15434   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15435     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15436       C = RHS.getOperand(0);
15437     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15438       D = RHS.getOperand(1);
15439     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15440     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15441   } else {
15442     if (RHS.getOpcode() != ISD::UNDEF)
15443       C = RHS;
15444     for (unsigned i = 0; i != NumElts; ++i)
15445       RMask[i] = i;
15446   }
15447
15448   // Check that the shuffles are both shuffling the same vectors.
15449   if (!(A == C && B == D) && !(A == D && B == C))
15450     return false;
15451
15452   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15453   if (!A.getNode() && !B.getNode())
15454     return false;
15455
15456   // If A and B occur in reverse order in RHS, then "swap" them (which means
15457   // rewriting the mask).
15458   if (A != C)
15459     CommuteVectorShuffleMask(RMask, NumElts);
15460
15461   // At this point LHS and RHS are equivalent to
15462   //   LHS = VECTOR_SHUFFLE A, B, LMask
15463   //   RHS = VECTOR_SHUFFLE A, B, RMask
15464   // Check that the masks correspond to performing a horizontal operation.
15465   for (unsigned i = 0; i != NumElts; ++i) {
15466     int LIdx = LMask[i], RIdx = RMask[i];
15467
15468     // Ignore any UNDEF components.
15469     if (LIdx < 0 || RIdx < 0 ||
15470         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15471         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15472       continue;
15473
15474     // Check that successive elements are being operated on.  If not, this is
15475     // not a horizontal operation.
15476     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15477     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15478     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15479     if (!(LIdx == Index && RIdx == Index + 1) &&
15480         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15481       return false;
15482   }
15483
15484   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15485   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15486   return true;
15487 }
15488
15489 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15490 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15491                                   const X86Subtarget *Subtarget) {
15492   EVT VT = N->getValueType(0);
15493   SDValue LHS = N->getOperand(0);
15494   SDValue RHS = N->getOperand(1);
15495
15496   // Try to synthesize horizontal adds from adds of shuffles.
15497   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15498        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15499       isHorizontalBinOp(LHS, RHS, true))
15500     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15501   return SDValue();
15502 }
15503
15504 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15505 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15506                                   const X86Subtarget *Subtarget) {
15507   EVT VT = N->getValueType(0);
15508   SDValue LHS = N->getOperand(0);
15509   SDValue RHS = N->getOperand(1);
15510
15511   // Try to synthesize horizontal subs from subs of shuffles.
15512   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15513        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15514       isHorizontalBinOp(LHS, RHS, false))
15515     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15516   return SDValue();
15517 }
15518
15519 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15520 /// X86ISD::FXOR nodes.
15521 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15522   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15523   // F[X]OR(0.0, x) -> x
15524   // F[X]OR(x, 0.0) -> x
15525   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15526     if (C->getValueAPF().isPosZero())
15527       return N->getOperand(1);
15528   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15529     if (C->getValueAPF().isPosZero())
15530       return N->getOperand(0);
15531   return SDValue();
15532 }
15533
15534 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15535 /// X86ISD::FMAX nodes.
15536 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15537   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15538
15539   // Only perform optimizations if UnsafeMath is used.
15540   if (!DAG.getTarget().Options.UnsafeFPMath)
15541     return SDValue();
15542
15543   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15544   // into FMINC and FMAXC, which are Commutative operations.
15545   unsigned NewOp = 0;
15546   switch (N->getOpcode()) {
15547     default: llvm_unreachable("unknown opcode");
15548     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15549     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15550   }
15551
15552   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15553                      N->getOperand(0), N->getOperand(1));
15554 }
15555
15556
15557 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15558 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15559   // FAND(0.0, x) -> 0.0
15560   // FAND(x, 0.0) -> 0.0
15561   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15562     if (C->getValueAPF().isPosZero())
15563       return N->getOperand(0);
15564   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15565     if (C->getValueAPF().isPosZero())
15566       return N->getOperand(1);
15567   return SDValue();
15568 }
15569
15570 static SDValue PerformBTCombine(SDNode *N,
15571                                 SelectionDAG &DAG,
15572                                 TargetLowering::DAGCombinerInfo &DCI) {
15573   // BT ignores high bits in the bit index operand.
15574   SDValue Op1 = N->getOperand(1);
15575   if (Op1.hasOneUse()) {
15576     unsigned BitWidth = Op1.getValueSizeInBits();
15577     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15578     APInt KnownZero, KnownOne;
15579     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15580                                           !DCI.isBeforeLegalizeOps());
15581     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15582     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15583         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15584       DCI.CommitTargetLoweringOpt(TLO);
15585   }
15586   return SDValue();
15587 }
15588
15589 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15590   SDValue Op = N->getOperand(0);
15591   if (Op.getOpcode() == ISD::BITCAST)
15592     Op = Op.getOperand(0);
15593   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15594   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15595       VT.getVectorElementType().getSizeInBits() ==
15596       OpVT.getVectorElementType().getSizeInBits()) {
15597     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15598   }
15599   return SDValue();
15600 }
15601
15602 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15603                                   TargetLowering::DAGCombinerInfo &DCI,
15604                                   const X86Subtarget *Subtarget) {
15605   if (!DCI.isBeforeLegalizeOps())
15606     return SDValue();
15607
15608   if (!Subtarget->hasAVX())
15609     return SDValue();
15610
15611   EVT VT = N->getValueType(0);
15612   SDValue Op = N->getOperand(0);
15613   EVT OpVT = Op.getValueType();
15614   DebugLoc dl = N->getDebugLoc();
15615
15616   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15617       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15618
15619     if (Subtarget->hasAVX2())
15620       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15621
15622     // Optimize vectors in AVX mode
15623     // Sign extend  v8i16 to v8i32 and
15624     //              v4i32 to v4i64
15625     //
15626     // Divide input vector into two parts
15627     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15628     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15629     // concat the vectors to original VT
15630
15631     unsigned NumElems = OpVT.getVectorNumElements();
15632     SDValue Undef = DAG.getUNDEF(OpVT);
15633
15634     SmallVector<int,8> ShufMask1(NumElems, -1);
15635     for (unsigned i = 0; i != NumElems/2; ++i)
15636       ShufMask1[i] = i;
15637
15638     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15639
15640     SmallVector<int,8> ShufMask2(NumElems, -1);
15641     for (unsigned i = 0; i != NumElems/2; ++i)
15642       ShufMask2[i] = i + NumElems/2;
15643
15644     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15645
15646     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15647                                   VT.getVectorNumElements()/2);
15648
15649     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15650     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15651
15652     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15653   }
15654   return SDValue();
15655 }
15656
15657 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15658                                  const X86Subtarget* Subtarget) {
15659   DebugLoc dl = N->getDebugLoc();
15660   EVT VT = N->getValueType(0);
15661
15662   // Let legalize expand this if it isn't a legal type yet.
15663   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15664     return SDValue();
15665
15666   EVT ScalarVT = VT.getScalarType();
15667   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15668       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15669     return SDValue();
15670
15671   SDValue A = N->getOperand(0);
15672   SDValue B = N->getOperand(1);
15673   SDValue C = N->getOperand(2);
15674
15675   bool NegA = (A.getOpcode() == ISD::FNEG);
15676   bool NegB = (B.getOpcode() == ISD::FNEG);
15677   bool NegC = (C.getOpcode() == ISD::FNEG);
15678
15679   // Negative multiplication when NegA xor NegB
15680   bool NegMul = (NegA != NegB);
15681   if (NegA)
15682     A = A.getOperand(0);
15683   if (NegB)
15684     B = B.getOperand(0);
15685   if (NegC)
15686     C = C.getOperand(0);
15687
15688   unsigned Opcode;
15689   if (!NegMul)
15690     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15691   else
15692     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15693
15694   return DAG.getNode(Opcode, dl, VT, A, B, C);
15695 }
15696
15697 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15698                                   TargetLowering::DAGCombinerInfo &DCI,
15699                                   const X86Subtarget *Subtarget) {
15700   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15701   //           (and (i32 x86isd::setcc_carry), 1)
15702   // This eliminates the zext. This transformation is necessary because
15703   // ISD::SETCC is always legalized to i8.
15704   DebugLoc dl = N->getDebugLoc();
15705   SDValue N0 = N->getOperand(0);
15706   EVT VT = N->getValueType(0);
15707   EVT OpVT = N0.getValueType();
15708
15709   if (N0.getOpcode() == ISD::AND &&
15710       N0.hasOneUse() &&
15711       N0.getOperand(0).hasOneUse()) {
15712     SDValue N00 = N0.getOperand(0);
15713     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15714       return SDValue();
15715     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15716     if (!C || C->getZExtValue() != 1)
15717       return SDValue();
15718     return DAG.getNode(ISD::AND, dl, VT,
15719                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15720                                    N00.getOperand(0), N00.getOperand(1)),
15721                        DAG.getConstant(1, VT));
15722   }
15723
15724   // Optimize vectors in AVX mode:
15725   //
15726   //   v8i16 -> v8i32
15727   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15728   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15729   //   Concat upper and lower parts.
15730   //
15731   //   v4i32 -> v4i64
15732   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15733   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15734   //   Concat upper and lower parts.
15735   //
15736   if (!DCI.isBeforeLegalizeOps())
15737     return SDValue();
15738
15739   if (!Subtarget->hasAVX())
15740     return SDValue();
15741
15742   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15743       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15744
15745     if (Subtarget->hasAVX2())
15746       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15747
15748     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15749     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15750     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15751
15752     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15753                                VT.getVectorNumElements()/2);
15754
15755     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15756     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15757
15758     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15759   }
15760
15761   return SDValue();
15762 }
15763
15764 // Optimize x == -y --> x+y == 0
15765 //          x != -y --> x+y != 0
15766 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15767   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15768   SDValue LHS = N->getOperand(0);
15769   SDValue RHS = N->getOperand(1);
15770
15771   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15772     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15773       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15774         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15775                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15776         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15777                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15778       }
15779   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15781       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15782         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15783                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15784         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15785                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15786       }
15787   return SDValue();
15788 }
15789
15790 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15791 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15792                                    TargetLowering::DAGCombinerInfo &DCI,
15793                                    const X86Subtarget *Subtarget) {
15794   DebugLoc DL = N->getDebugLoc();
15795   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15796   SDValue EFLAGS = N->getOperand(1);
15797
15798   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15799   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15800   // cases.
15801   if (CC == X86::COND_B)
15802     return DAG.getNode(ISD::AND, DL, MVT::i8,
15803                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15804                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15805                        DAG.getConstant(1, MVT::i8));
15806
15807   SDValue Flags;
15808
15809   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15810   if (Flags.getNode()) {
15811     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15812     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15813   }
15814
15815   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15816   if (Flags.getNode()) {
15817     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15818     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15819   }
15820
15821   return SDValue();
15822 }
15823
15824 // Optimize branch condition evaluation.
15825 //
15826 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15827                                     TargetLowering::DAGCombinerInfo &DCI,
15828                                     const X86Subtarget *Subtarget) {
15829   DebugLoc DL = N->getDebugLoc();
15830   SDValue Chain = N->getOperand(0);
15831   SDValue Dest = N->getOperand(1);
15832   SDValue EFLAGS = N->getOperand(3);
15833   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15834
15835   SDValue Flags;
15836
15837   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15838   if (Flags.getNode()) {
15839     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15840     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15841                        Flags);
15842   }
15843
15844   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15845   if (Flags.getNode()) {
15846     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15847     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15848                        Flags);
15849   }
15850
15851   return SDValue();
15852 }
15853
15854 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15855   SDValue Op0 = N->getOperand(0);
15856   EVT InVT = Op0->getValueType(0);
15857
15858   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15859   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15860     DebugLoc dl = N->getDebugLoc();
15861     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15862     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15863     // Notice that we use SINT_TO_FP because we know that the high bits
15864     // are zero and SINT_TO_FP is better supported by the hardware.
15865     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15866   }
15867
15868   return SDValue();
15869 }
15870
15871 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15872                                         const X86TargetLowering *XTLI) {
15873   SDValue Op0 = N->getOperand(0);
15874   EVT InVT = Op0->getValueType(0);
15875
15876   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15877   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15878     DebugLoc dl = N->getDebugLoc();
15879     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15880     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15881     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15882   }
15883
15884   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15885   // a 32-bit target where SSE doesn't support i64->FP operations.
15886   if (Op0.getOpcode() == ISD::LOAD) {
15887     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15888     EVT VT = Ld->getValueType(0);
15889     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15890         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15891         !XTLI->getSubtarget()->is64Bit() &&
15892         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15893       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15894                                           Ld->getChain(), Op0, DAG);
15895       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15896       return FILDChain;
15897     }
15898   }
15899   return SDValue();
15900 }
15901
15902 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15903   EVT VT = N->getValueType(0);
15904
15905   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15906   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15907     DebugLoc dl = N->getDebugLoc();
15908     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15909     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15910     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15911   }
15912
15913   return SDValue();
15914 }
15915
15916 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15917 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15918                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15919   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15920   // the result is either zero or one (depending on the input carry bit).
15921   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15922   if (X86::isZeroNode(N->getOperand(0)) &&
15923       X86::isZeroNode(N->getOperand(1)) &&
15924       // We don't have a good way to replace an EFLAGS use, so only do this when
15925       // dead right now.
15926       SDValue(N, 1).use_empty()) {
15927     DebugLoc DL = N->getDebugLoc();
15928     EVT VT = N->getValueType(0);
15929     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15930     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15931                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15932                                            DAG.getConstant(X86::COND_B,MVT::i8),
15933                                            N->getOperand(2)),
15934                                DAG.getConstant(1, VT));
15935     return DCI.CombineTo(N, Res1, CarryOut);
15936   }
15937
15938   return SDValue();
15939 }
15940
15941 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15942 //      (add Y, (setne X, 0)) -> sbb -1, Y
15943 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15944 //      (sub (setne X, 0), Y) -> adc -1, Y
15945 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15946   DebugLoc DL = N->getDebugLoc();
15947
15948   // Look through ZExts.
15949   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15950   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15951     return SDValue();
15952
15953   SDValue SetCC = Ext.getOperand(0);
15954   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15955     return SDValue();
15956
15957   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15958   if (CC != X86::COND_E && CC != X86::COND_NE)
15959     return SDValue();
15960
15961   SDValue Cmp = SetCC.getOperand(1);
15962   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15963       !X86::isZeroNode(Cmp.getOperand(1)) ||
15964       !Cmp.getOperand(0).getValueType().isInteger())
15965     return SDValue();
15966
15967   SDValue CmpOp0 = Cmp.getOperand(0);
15968   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15969                                DAG.getConstant(1, CmpOp0.getValueType()));
15970
15971   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15972   if (CC == X86::COND_NE)
15973     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15974                        DL, OtherVal.getValueType(), OtherVal,
15975                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15976   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15977                      DL, OtherVal.getValueType(), OtherVal,
15978                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15979 }
15980
15981 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15982 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15983                                  const X86Subtarget *Subtarget) {
15984   EVT VT = N->getValueType(0);
15985   SDValue Op0 = N->getOperand(0);
15986   SDValue Op1 = N->getOperand(1);
15987
15988   // Try to synthesize horizontal adds from adds of shuffles.
15989   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15990        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15991       isHorizontalBinOp(Op0, Op1, true))
15992     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15993
15994   return OptimizeConditionalInDecrement(N, DAG);
15995 }
15996
15997 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15998                                  const X86Subtarget *Subtarget) {
15999   SDValue Op0 = N->getOperand(0);
16000   SDValue Op1 = N->getOperand(1);
16001
16002   // X86 can't encode an immediate LHS of a sub. See if we can push the
16003   // negation into a preceding instruction.
16004   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16005     // If the RHS of the sub is a XOR with one use and a constant, invert the
16006     // immediate. Then add one to the LHS of the sub so we can turn
16007     // X-Y -> X+~Y+1, saving one register.
16008     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16009         isa<ConstantSDNode>(Op1.getOperand(1))) {
16010       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16011       EVT VT = Op0.getValueType();
16012       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16013                                    Op1.getOperand(0),
16014                                    DAG.getConstant(~XorC, VT));
16015       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16016                          DAG.getConstant(C->getAPIntValue()+1, VT));
16017     }
16018   }
16019
16020   // Try to synthesize horizontal adds from adds of shuffles.
16021   EVT VT = N->getValueType(0);
16022   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16023        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16024       isHorizontalBinOp(Op0, Op1, true))
16025     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16026
16027   return OptimizeConditionalInDecrement(N, DAG);
16028 }
16029
16030 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16031                                              DAGCombinerInfo &DCI) const {
16032   SelectionDAG &DAG = DCI.DAG;
16033   switch (N->getOpcode()) {
16034   default: break;
16035   case ISD::EXTRACT_VECTOR_ELT:
16036     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16037   case ISD::VSELECT:
16038   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16039   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16040   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16041   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16042   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16043   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16044   case ISD::SHL:
16045   case ISD::SRA:
16046   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16047   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16048   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16049   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16050   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16051   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16052   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16053   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16054   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16055   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16056   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16057   case X86ISD::FXOR:
16058   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16059   case X86ISD::FMIN:
16060   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16061   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16062   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16063   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16064   case ISD::ANY_EXTEND:
16065   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16066   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16067   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16068   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16069   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16070   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16071   case X86ISD::SHUFP:       // Handle all target specific shuffles
16072   case X86ISD::PALIGN:
16073   case X86ISD::UNPCKH:
16074   case X86ISD::UNPCKL:
16075   case X86ISD::MOVHLPS:
16076   case X86ISD::MOVLHPS:
16077   case X86ISD::PSHUFD:
16078   case X86ISD::PSHUFHW:
16079   case X86ISD::PSHUFLW:
16080   case X86ISD::MOVSS:
16081   case X86ISD::MOVSD:
16082   case X86ISD::VPERMILP:
16083   case X86ISD::VPERM2X128:
16084   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16085   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16086   }
16087
16088   return SDValue();
16089 }
16090
16091 /// isTypeDesirableForOp - Return true if the target has native support for
16092 /// the specified value type and it is 'desirable' to use the type for the
16093 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16094 /// instruction encodings are longer and some i16 instructions are slow.
16095 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16096   if (!isTypeLegal(VT))
16097     return false;
16098   if (VT != MVT::i16)
16099     return true;
16100
16101   switch (Opc) {
16102   default:
16103     return true;
16104   case ISD::LOAD:
16105   case ISD::SIGN_EXTEND:
16106   case ISD::ZERO_EXTEND:
16107   case ISD::ANY_EXTEND:
16108   case ISD::SHL:
16109   case ISD::SRL:
16110   case ISD::SUB:
16111   case ISD::ADD:
16112   case ISD::MUL:
16113   case ISD::AND:
16114   case ISD::OR:
16115   case ISD::XOR:
16116     return false;
16117   }
16118 }
16119
16120 /// IsDesirableToPromoteOp - This method query the target whether it is
16121 /// beneficial for dag combiner to promote the specified node. If true, it
16122 /// should return the desired promotion type by reference.
16123 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16124   EVT VT = Op.getValueType();
16125   if (VT != MVT::i16)
16126     return false;
16127
16128   bool Promote = false;
16129   bool Commute = false;
16130   switch (Op.getOpcode()) {
16131   default: break;
16132   case ISD::LOAD: {
16133     LoadSDNode *LD = cast<LoadSDNode>(Op);
16134     // If the non-extending load has a single use and it's not live out, then it
16135     // might be folded.
16136     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16137                                                      Op.hasOneUse()*/) {
16138       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16139              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16140         // The only case where we'd want to promote LOAD (rather then it being
16141         // promoted as an operand is when it's only use is liveout.
16142         if (UI->getOpcode() != ISD::CopyToReg)
16143           return false;
16144       }
16145     }
16146     Promote = true;
16147     break;
16148   }
16149   case ISD::SIGN_EXTEND:
16150   case ISD::ZERO_EXTEND:
16151   case ISD::ANY_EXTEND:
16152     Promote = true;
16153     break;
16154   case ISD::SHL:
16155   case ISD::SRL: {
16156     SDValue N0 = Op.getOperand(0);
16157     // Look out for (store (shl (load), x)).
16158     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16159       return false;
16160     Promote = true;
16161     break;
16162   }
16163   case ISD::ADD:
16164   case ISD::MUL:
16165   case ISD::AND:
16166   case ISD::OR:
16167   case ISD::XOR:
16168     Commute = true;
16169     // fallthrough
16170   case ISD::SUB: {
16171     SDValue N0 = Op.getOperand(0);
16172     SDValue N1 = Op.getOperand(1);
16173     if (!Commute && MayFoldLoad(N1))
16174       return false;
16175     // Avoid disabling potential load folding opportunities.
16176     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16177       return false;
16178     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16179       return false;
16180     Promote = true;
16181   }
16182   }
16183
16184   PVT = MVT::i32;
16185   return Promote;
16186 }
16187
16188 //===----------------------------------------------------------------------===//
16189 //                           X86 Inline Assembly Support
16190 //===----------------------------------------------------------------------===//
16191
16192 namespace {
16193   // Helper to match a string separated by whitespace.
16194   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16195     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16196
16197     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16198       StringRef piece(*args[i]);
16199       if (!s.startswith(piece)) // Check if the piece matches.
16200         return false;
16201
16202       s = s.substr(piece.size());
16203       StringRef::size_type pos = s.find_first_not_of(" \t");
16204       if (pos == 0) // We matched a prefix.
16205         return false;
16206
16207       s = s.substr(pos);
16208     }
16209
16210     return s.empty();
16211   }
16212   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16213 }
16214
16215 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16216   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16217
16218   std::string AsmStr = IA->getAsmString();
16219
16220   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16221   if (!Ty || Ty->getBitWidth() % 16 != 0)
16222     return false;
16223
16224   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16225   SmallVector<StringRef, 4> AsmPieces;
16226   SplitString(AsmStr, AsmPieces, ";\n");
16227
16228   switch (AsmPieces.size()) {
16229   default: return false;
16230   case 1:
16231     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16232     // we will turn this bswap into something that will be lowered to logical
16233     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16234     // lower so don't worry about this.
16235     // bswap $0
16236     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16237         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16238         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16239         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16240         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16241         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16242       // No need to check constraints, nothing other than the equivalent of
16243       // "=r,0" would be valid here.
16244       return IntrinsicLowering::LowerToByteSwap(CI);
16245     }
16246
16247     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16248     if (CI->getType()->isIntegerTy(16) &&
16249         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16250         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16251          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16252       AsmPieces.clear();
16253       const std::string &ConstraintsStr = IA->getConstraintString();
16254       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16255       std::sort(AsmPieces.begin(), AsmPieces.end());
16256       if (AsmPieces.size() == 4 &&
16257           AsmPieces[0] == "~{cc}" &&
16258           AsmPieces[1] == "~{dirflag}" &&
16259           AsmPieces[2] == "~{flags}" &&
16260           AsmPieces[3] == "~{fpsr}")
16261       return IntrinsicLowering::LowerToByteSwap(CI);
16262     }
16263     break;
16264   case 3:
16265     if (CI->getType()->isIntegerTy(32) &&
16266         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16267         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16268         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16269         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16270       AsmPieces.clear();
16271       const std::string &ConstraintsStr = IA->getConstraintString();
16272       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16273       std::sort(AsmPieces.begin(), AsmPieces.end());
16274       if (AsmPieces.size() == 4 &&
16275           AsmPieces[0] == "~{cc}" &&
16276           AsmPieces[1] == "~{dirflag}" &&
16277           AsmPieces[2] == "~{flags}" &&
16278           AsmPieces[3] == "~{fpsr}")
16279         return IntrinsicLowering::LowerToByteSwap(CI);
16280     }
16281
16282     if (CI->getType()->isIntegerTy(64)) {
16283       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16284       if (Constraints.size() >= 2 &&
16285           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16286           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16287         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16288         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16289             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16290             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16291           return IntrinsicLowering::LowerToByteSwap(CI);
16292       }
16293     }
16294     break;
16295   }
16296   return false;
16297 }
16298
16299
16300
16301 /// getConstraintType - Given a constraint letter, return the type of
16302 /// constraint it is for this target.
16303 X86TargetLowering::ConstraintType
16304 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16305   if (Constraint.size() == 1) {
16306     switch (Constraint[0]) {
16307     case 'R':
16308     case 'q':
16309     case 'Q':
16310     case 'f':
16311     case 't':
16312     case 'u':
16313     case 'y':
16314     case 'x':
16315     case 'Y':
16316     case 'l':
16317       return C_RegisterClass;
16318     case 'a':
16319     case 'b':
16320     case 'c':
16321     case 'd':
16322     case 'S':
16323     case 'D':
16324     case 'A':
16325       return C_Register;
16326     case 'I':
16327     case 'J':
16328     case 'K':
16329     case 'L':
16330     case 'M':
16331     case 'N':
16332     case 'G':
16333     case 'C':
16334     case 'e':
16335     case 'Z':
16336       return C_Other;
16337     default:
16338       break;
16339     }
16340   }
16341   return TargetLowering::getConstraintType(Constraint);
16342 }
16343
16344 /// Examine constraint type and operand type and determine a weight value.
16345 /// This object must already have been set up with the operand type
16346 /// and the current alternative constraint selected.
16347 TargetLowering::ConstraintWeight
16348   X86TargetLowering::getSingleConstraintMatchWeight(
16349     AsmOperandInfo &info, const char *constraint) const {
16350   ConstraintWeight weight = CW_Invalid;
16351   Value *CallOperandVal = info.CallOperandVal;
16352     // If we don't have a value, we can't do a match,
16353     // but allow it at the lowest weight.
16354   if (CallOperandVal == NULL)
16355     return CW_Default;
16356   Type *type = CallOperandVal->getType();
16357   // Look at the constraint type.
16358   switch (*constraint) {
16359   default:
16360     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16361   case 'R':
16362   case 'q':
16363   case 'Q':
16364   case 'a':
16365   case 'b':
16366   case 'c':
16367   case 'd':
16368   case 'S':
16369   case 'D':
16370   case 'A':
16371     if (CallOperandVal->getType()->isIntegerTy())
16372       weight = CW_SpecificReg;
16373     break;
16374   case 'f':
16375   case 't':
16376   case 'u':
16377       if (type->isFloatingPointTy())
16378         weight = CW_SpecificReg;
16379       break;
16380   case 'y':
16381       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16382         weight = CW_SpecificReg;
16383       break;
16384   case 'x':
16385   case 'Y':
16386     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16387         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16388       weight = CW_Register;
16389     break;
16390   case 'I':
16391     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16392       if (C->getZExtValue() <= 31)
16393         weight = CW_Constant;
16394     }
16395     break;
16396   case 'J':
16397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16398       if (C->getZExtValue() <= 63)
16399         weight = CW_Constant;
16400     }
16401     break;
16402   case 'K':
16403     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16404       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16405         weight = CW_Constant;
16406     }
16407     break;
16408   case 'L':
16409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16410       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16411         weight = CW_Constant;
16412     }
16413     break;
16414   case 'M':
16415     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16416       if (C->getZExtValue() <= 3)
16417         weight = CW_Constant;
16418     }
16419     break;
16420   case 'N':
16421     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16422       if (C->getZExtValue() <= 0xff)
16423         weight = CW_Constant;
16424     }
16425     break;
16426   case 'G':
16427   case 'C':
16428     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16429       weight = CW_Constant;
16430     }
16431     break;
16432   case 'e':
16433     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16434       if ((C->getSExtValue() >= -0x80000000LL) &&
16435           (C->getSExtValue() <= 0x7fffffffLL))
16436         weight = CW_Constant;
16437     }
16438     break;
16439   case 'Z':
16440     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16441       if (C->getZExtValue() <= 0xffffffff)
16442         weight = CW_Constant;
16443     }
16444     break;
16445   }
16446   return weight;
16447 }
16448
16449 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16450 /// with another that has more specific requirements based on the type of the
16451 /// corresponding operand.
16452 const char *X86TargetLowering::
16453 LowerXConstraint(EVT ConstraintVT) const {
16454   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16455   // 'f' like normal targets.
16456   if (ConstraintVT.isFloatingPoint()) {
16457     if (Subtarget->hasSSE2())
16458       return "Y";
16459     if (Subtarget->hasSSE1())
16460       return "x";
16461   }
16462
16463   return TargetLowering::LowerXConstraint(ConstraintVT);
16464 }
16465
16466 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16467 /// vector.  If it is invalid, don't add anything to Ops.
16468 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16469                                                      std::string &Constraint,
16470                                                      std::vector<SDValue>&Ops,
16471                                                      SelectionDAG &DAG) const {
16472   SDValue Result(0, 0);
16473
16474   // Only support length 1 constraints for now.
16475   if (Constraint.length() > 1) return;
16476
16477   char ConstraintLetter = Constraint[0];
16478   switch (ConstraintLetter) {
16479   default: break;
16480   case 'I':
16481     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16482       if (C->getZExtValue() <= 31) {
16483         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16484         break;
16485       }
16486     }
16487     return;
16488   case 'J':
16489     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16490       if (C->getZExtValue() <= 63) {
16491         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16492         break;
16493       }
16494     }
16495     return;
16496   case 'K':
16497     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16498       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16499         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16500         break;
16501       }
16502     }
16503     return;
16504   case 'N':
16505     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16506       if (C->getZExtValue() <= 255) {
16507         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16508         break;
16509       }
16510     }
16511     return;
16512   case 'e': {
16513     // 32-bit signed value
16514     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16515       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16516                                            C->getSExtValue())) {
16517         // Widen to 64 bits here to get it sign extended.
16518         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16519         break;
16520       }
16521     // FIXME gcc accepts some relocatable values here too, but only in certain
16522     // memory models; it's complicated.
16523     }
16524     return;
16525   }
16526   case 'Z': {
16527     // 32-bit unsigned value
16528     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16529       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16530                                            C->getZExtValue())) {
16531         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16532         break;
16533       }
16534     }
16535     // FIXME gcc accepts some relocatable values here too, but only in certain
16536     // memory models; it's complicated.
16537     return;
16538   }
16539   case 'i': {
16540     // Literal immediates are always ok.
16541     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16542       // Widen to 64 bits here to get it sign extended.
16543       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16544       break;
16545     }
16546
16547     // In any sort of PIC mode addresses need to be computed at runtime by
16548     // adding in a register or some sort of table lookup.  These can't
16549     // be used as immediates.
16550     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16551       return;
16552
16553     // If we are in non-pic codegen mode, we allow the address of a global (with
16554     // an optional displacement) to be used with 'i'.
16555     GlobalAddressSDNode *GA = 0;
16556     int64_t Offset = 0;
16557
16558     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16559     while (1) {
16560       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16561         Offset += GA->getOffset();
16562         break;
16563       } else if (Op.getOpcode() == ISD::ADD) {
16564         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16565           Offset += C->getZExtValue();
16566           Op = Op.getOperand(0);
16567           continue;
16568         }
16569       } else if (Op.getOpcode() == ISD::SUB) {
16570         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16571           Offset += -C->getZExtValue();
16572           Op = Op.getOperand(0);
16573           continue;
16574         }
16575       }
16576
16577       // Otherwise, this isn't something we can handle, reject it.
16578       return;
16579     }
16580
16581     const GlobalValue *GV = GA->getGlobal();
16582     // If we require an extra load to get this address, as in PIC mode, we
16583     // can't accept it.
16584     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16585                                                         getTargetMachine())))
16586       return;
16587
16588     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16589                                         GA->getValueType(0), Offset);
16590     break;
16591   }
16592   }
16593
16594   if (Result.getNode()) {
16595     Ops.push_back(Result);
16596     return;
16597   }
16598   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16599 }
16600
16601 std::pair<unsigned, const TargetRegisterClass*>
16602 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16603                                                 EVT VT) const {
16604   // First, see if this is a constraint that directly corresponds to an LLVM
16605   // register class.
16606   if (Constraint.size() == 1) {
16607     // GCC Constraint Letters
16608     switch (Constraint[0]) {
16609     default: break;
16610       // TODO: Slight differences here in allocation order and leaving
16611       // RIP in the class. Do they matter any more here than they do
16612       // in the normal allocation?
16613     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16614       if (Subtarget->is64Bit()) {
16615         if (VT == MVT::i32 || VT == MVT::f32)
16616           return std::make_pair(0U, &X86::GR32RegClass);
16617         if (VT == MVT::i16)
16618           return std::make_pair(0U, &X86::GR16RegClass);
16619         if (VT == MVT::i8 || VT == MVT::i1)
16620           return std::make_pair(0U, &X86::GR8RegClass);
16621         if (VT == MVT::i64 || VT == MVT::f64)
16622           return std::make_pair(0U, &X86::GR64RegClass);
16623         break;
16624       }
16625       // 32-bit fallthrough
16626     case 'Q':   // Q_REGS
16627       if (VT == MVT::i32 || VT == MVT::f32)
16628         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16629       if (VT == MVT::i16)
16630         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16631       if (VT == MVT::i8 || VT == MVT::i1)
16632         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16633       if (VT == MVT::i64)
16634         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16635       break;
16636     case 'r':   // GENERAL_REGS
16637     case 'l':   // INDEX_REGS
16638       if (VT == MVT::i8 || VT == MVT::i1)
16639         return std::make_pair(0U, &X86::GR8RegClass);
16640       if (VT == MVT::i16)
16641         return std::make_pair(0U, &X86::GR16RegClass);
16642       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16643         return std::make_pair(0U, &X86::GR32RegClass);
16644       return std::make_pair(0U, &X86::GR64RegClass);
16645     case 'R':   // LEGACY_REGS
16646       if (VT == MVT::i8 || VT == MVT::i1)
16647         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16648       if (VT == MVT::i16)
16649         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16650       if (VT == MVT::i32 || !Subtarget->is64Bit())
16651         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16652       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16653     case 'f':  // FP Stack registers.
16654       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16655       // value to the correct fpstack register class.
16656       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16657         return std::make_pair(0U, &X86::RFP32RegClass);
16658       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16659         return std::make_pair(0U, &X86::RFP64RegClass);
16660       return std::make_pair(0U, &X86::RFP80RegClass);
16661     case 'y':   // MMX_REGS if MMX allowed.
16662       if (!Subtarget->hasMMX()) break;
16663       return std::make_pair(0U, &X86::VR64RegClass);
16664     case 'Y':   // SSE_REGS if SSE2 allowed
16665       if (!Subtarget->hasSSE2()) break;
16666       // FALL THROUGH.
16667     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16668       if (!Subtarget->hasSSE1()) break;
16669
16670       switch (VT.getSimpleVT().SimpleTy) {
16671       default: break;
16672       // Scalar SSE types.
16673       case MVT::f32:
16674       case MVT::i32:
16675         return std::make_pair(0U, &X86::FR32RegClass);
16676       case MVT::f64:
16677       case MVT::i64:
16678         return std::make_pair(0U, &X86::FR64RegClass);
16679       // Vector types.
16680       case MVT::v16i8:
16681       case MVT::v8i16:
16682       case MVT::v4i32:
16683       case MVT::v2i64:
16684       case MVT::v4f32:
16685       case MVT::v2f64:
16686         return std::make_pair(0U, &X86::VR128RegClass);
16687       // AVX types.
16688       case MVT::v32i8:
16689       case MVT::v16i16:
16690       case MVT::v8i32:
16691       case MVT::v4i64:
16692       case MVT::v8f32:
16693       case MVT::v4f64:
16694         return std::make_pair(0U, &X86::VR256RegClass);
16695       }
16696       break;
16697     }
16698   }
16699
16700   // Use the default implementation in TargetLowering to convert the register
16701   // constraint into a member of a register class.
16702   std::pair<unsigned, const TargetRegisterClass*> Res;
16703   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16704
16705   // Not found as a standard register?
16706   if (Res.second == 0) {
16707     // Map st(0) -> st(7) -> ST0
16708     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16709         tolower(Constraint[1]) == 's' &&
16710         tolower(Constraint[2]) == 't' &&
16711         Constraint[3] == '(' &&
16712         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16713         Constraint[5] == ')' &&
16714         Constraint[6] == '}') {
16715
16716       Res.first = X86::ST0+Constraint[4]-'0';
16717       Res.second = &X86::RFP80RegClass;
16718       return Res;
16719     }
16720
16721     // GCC allows "st(0)" to be called just plain "st".
16722     if (StringRef("{st}").equals_lower(Constraint)) {
16723       Res.first = X86::ST0;
16724       Res.second = &X86::RFP80RegClass;
16725       return Res;
16726     }
16727
16728     // flags -> EFLAGS
16729     if (StringRef("{flags}").equals_lower(Constraint)) {
16730       Res.first = X86::EFLAGS;
16731       Res.second = &X86::CCRRegClass;
16732       return Res;
16733     }
16734
16735     // 'A' means EAX + EDX.
16736     if (Constraint == "A") {
16737       Res.first = X86::EAX;
16738       Res.second = &X86::GR32_ADRegClass;
16739       return Res;
16740     }
16741     return Res;
16742   }
16743
16744   // Otherwise, check to see if this is a register class of the wrong value
16745   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16746   // turn into {ax},{dx}.
16747   if (Res.second->hasType(VT))
16748     return Res;   // Correct type already, nothing to do.
16749
16750   // All of the single-register GCC register classes map their values onto
16751   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16752   // really want an 8-bit or 32-bit register, map to the appropriate register
16753   // class and return the appropriate register.
16754   if (Res.second == &X86::GR16RegClass) {
16755     if (VT == MVT::i8) {
16756       unsigned DestReg = 0;
16757       switch (Res.first) {
16758       default: break;
16759       case X86::AX: DestReg = X86::AL; break;
16760       case X86::DX: DestReg = X86::DL; break;
16761       case X86::CX: DestReg = X86::CL; break;
16762       case X86::BX: DestReg = X86::BL; break;
16763       }
16764       if (DestReg) {
16765         Res.first = DestReg;
16766         Res.second = &X86::GR8RegClass;
16767       }
16768     } else if (VT == MVT::i32) {
16769       unsigned DestReg = 0;
16770       switch (Res.first) {
16771       default: break;
16772       case X86::AX: DestReg = X86::EAX; break;
16773       case X86::DX: DestReg = X86::EDX; break;
16774       case X86::CX: DestReg = X86::ECX; break;
16775       case X86::BX: DestReg = X86::EBX; break;
16776       case X86::SI: DestReg = X86::ESI; break;
16777       case X86::DI: DestReg = X86::EDI; break;
16778       case X86::BP: DestReg = X86::EBP; break;
16779       case X86::SP: DestReg = X86::ESP; break;
16780       }
16781       if (DestReg) {
16782         Res.first = DestReg;
16783         Res.second = &X86::GR32RegClass;
16784       }
16785     } else if (VT == MVT::i64) {
16786       unsigned DestReg = 0;
16787       switch (Res.first) {
16788       default: break;
16789       case X86::AX: DestReg = X86::RAX; break;
16790       case X86::DX: DestReg = X86::RDX; break;
16791       case X86::CX: DestReg = X86::RCX; break;
16792       case X86::BX: DestReg = X86::RBX; break;
16793       case X86::SI: DestReg = X86::RSI; break;
16794       case X86::DI: DestReg = X86::RDI; break;
16795       case X86::BP: DestReg = X86::RBP; break;
16796       case X86::SP: DestReg = X86::RSP; break;
16797       }
16798       if (DestReg) {
16799         Res.first = DestReg;
16800         Res.second = &X86::GR64RegClass;
16801       }
16802     }
16803   } else if (Res.second == &X86::FR32RegClass ||
16804              Res.second == &X86::FR64RegClass ||
16805              Res.second == &X86::VR128RegClass) {
16806     // Handle references to XMM physical registers that got mapped into the
16807     // wrong class.  This can happen with constraints like {xmm0} where the
16808     // target independent register mapper will just pick the first match it can
16809     // find, ignoring the required type.
16810
16811     if (VT == MVT::f32 || VT == MVT::i32)
16812       Res.second = &X86::FR32RegClass;
16813     else if (VT == MVT::f64 || VT == MVT::i64)
16814       Res.second = &X86::FR64RegClass;
16815     else if (X86::VR128RegClass.hasType(VT))
16816       Res.second = &X86::VR128RegClass;
16817     else if (X86::VR256RegClass.hasType(VT))
16818       Res.second = &X86::VR256RegClass;
16819   }
16820
16821   return Res;
16822 }