Remove the `hasFnAttr' method from Function.
[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     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
521   }
522
523   if (Subtarget->hasCmpxchg16b()) {
524     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
525   }
526
527   // FIXME - use subtarget debug flags
528   if (!Subtarget->isTargetDarwin() &&
529       !Subtarget->isTargetELF() &&
530       !Subtarget->isTargetCygMing()) {
531     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
532   }
533
534   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
535   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
536   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
537   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
538   if (Subtarget->is64Bit()) {
539     setExceptionPointerRegister(X86::RAX);
540     setExceptionSelectorRegister(X86::RDX);
541   } else {
542     setExceptionPointerRegister(X86::EAX);
543     setExceptionSelectorRegister(X86::EDX);
544   }
545   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
546   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
547
548   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
549   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
550
551   setOperationAction(ISD::TRAP, MVT::Other, Legal);
552
553   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
554   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
555   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
558     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
559   } else {
560     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
561     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
562   }
563
564   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
565   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
566
567   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
568     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
569                        MVT::i64 : MVT::i32, Custom);
570   else if (TM.Options.EnableSegmentedStacks)
571     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
572                        MVT::i64 : MVT::i32, Custom);
573   else
574     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
575                        MVT::i64 : MVT::i32, Expand);
576
577   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
578     // f32 and f64 use SSE.
579     // Set up the FP register classes.
580     addRegisterClass(MVT::f32, &X86::FR32RegClass);
581     addRegisterClass(MVT::f64, &X86::FR64RegClass);
582
583     // Use ANDPD to simulate FABS.
584     setOperationAction(ISD::FABS , MVT::f64, Custom);
585     setOperationAction(ISD::FABS , MVT::f32, Custom);
586
587     // Use XORP to simulate FNEG.
588     setOperationAction(ISD::FNEG , MVT::f64, Custom);
589     setOperationAction(ISD::FNEG , MVT::f32, Custom);
590
591     // Use ANDPD and ORPD to simulate FCOPYSIGN.
592     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
593     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
594
595     // Lower this to FGETSIGNx86 plus an AND.
596     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
597     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
598
599     // We don't support sin/cos/fmod
600     setOperationAction(ISD::FSIN , MVT::f64, Expand);
601     setOperationAction(ISD::FCOS , MVT::f64, Expand);
602     setOperationAction(ISD::FSIN , MVT::f32, Expand);
603     setOperationAction(ISD::FCOS , MVT::f32, Expand);
604
605     // Expand FP immediates into loads from the stack, except for the special
606     // cases we handle.
607     addLegalFPImmediate(APFloat(+0.0)); // xorpd
608     addLegalFPImmediate(APFloat(+0.0f)); // xorps
609   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
610     // Use SSE for f32, x87 for f64.
611     // Set up the FP register classes.
612     addRegisterClass(MVT::f32, &X86::FR32RegClass);
613     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
614
615     // Use ANDPS to simulate FABS.
616     setOperationAction(ISD::FABS , MVT::f32, Custom);
617
618     // Use XORP to simulate FNEG.
619     setOperationAction(ISD::FNEG , MVT::f32, Custom);
620
621     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
622
623     // Use ANDPS and ORPS to simulate FCOPYSIGN.
624     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
626
627     // We don't support sin/cos/fmod
628     setOperationAction(ISD::FSIN , MVT::f32, Expand);
629     setOperationAction(ISD::FCOS , MVT::f32, Expand);
630
631     // Special cases we handle for FP constants.
632     addLegalFPImmediate(APFloat(+0.0f)); // xorps
633     addLegalFPImmediate(APFloat(+0.0)); // FLD0
634     addLegalFPImmediate(APFloat(+1.0)); // FLD1
635     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
636     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
637
638     if (!TM.Options.UnsafeFPMath) {
639       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
640       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
641     }
642   } else if (!TM.Options.UseSoftFloat) {
643     // f32 and f64 in x87.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
646     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
647
648     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
649     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
650     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
651     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
652
653     if (!TM.Options.UnsafeFPMath) {
654       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
655       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
656       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
657       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
658     }
659     addLegalFPImmediate(APFloat(+0.0)); // FLD0
660     addLegalFPImmediate(APFloat(+1.0)); // FLD1
661     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
662     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
663     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
664     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
665     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
666     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
667   }
668
669   // We don't support FMA.
670   setOperationAction(ISD::FMA, MVT::f64, Expand);
671   setOperationAction(ISD::FMA, MVT::f32, Expand);
672
673   // Long double always uses X87.
674   if (!TM.Options.UseSoftFloat) {
675     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
676     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
677     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
678     {
679       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
680       addLegalFPImmediate(TmpFlt);  // FLD0
681       TmpFlt.changeSign();
682       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
683
684       bool ignored;
685       APFloat TmpFlt2(+1.0);
686       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
687                       &ignored);
688       addLegalFPImmediate(TmpFlt2);  // FLD1
689       TmpFlt2.changeSign();
690       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
691     }
692
693     if (!TM.Options.UnsafeFPMath) {
694       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
695       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
696     }
697
698     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
699     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
700     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
701     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
702     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
703     setOperationAction(ISD::FMA, MVT::f80, Expand);
704   }
705
706   // Always use a library call for pow.
707   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
708   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
709   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
710
711   setOperationAction(ISD::FLOG, MVT::f80, Expand);
712   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
713   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
714   setOperationAction(ISD::FEXP, MVT::f80, Expand);
715   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
716
717   // First set operation action for all vector types to either promote
718   // (for widening) or expand (for scalarization). Then we will selectively
719   // turn on ones that can be effectively codegen'd.
720   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
721            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
722     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
737     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
739     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
740     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
776     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
781     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
782              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
783       setTruncStoreAction((MVT::SimpleValueType)VT,
784                           (MVT::SimpleValueType)InnerVT, Expand);
785     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
786     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
787     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
788   }
789
790   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
791   // with -msoft-float, disable use of MMX as well.
792   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
793     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
794     // No operations on x86mmx supported, everything uses intrinsics.
795   }
796
797   // MMX-sized vectors (other than x86mmx) are expected to be expanded
798   // into smaller operations.
799   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
800   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
801   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
802   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
803   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
804   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
805   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
806   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
807   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
808   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
809   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
810   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
811   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
812   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
813   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
814   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
815   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
816   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
817   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
818   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
819   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
820   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
821   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
822   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
823   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
824   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
825   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
826   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
827   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
828
829   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
830     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
831
832     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
833     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
834     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
835     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
836     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
837     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
838     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
839     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
840     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
841     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
842     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
843     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
844   }
845
846   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
847     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
848
849     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
850     // registers cannot be used even for integer operations.
851     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
852     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
853     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
854     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
855
856     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
857     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
858     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
859     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
860     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
861     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
862     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
863     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
864     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
865     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
866     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
867     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
868     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
869     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
870     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
871     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
872     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
873
874     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
875     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
876     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
877     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
878
879     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
880     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
883     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
884
885     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
886     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
887       MVT VT = (MVT::SimpleValueType)i;
888       // Do not attempt to custom lower non-power-of-2 vectors
889       if (!isPowerOf2_32(VT.getVectorNumElements()))
890         continue;
891       // Do not attempt to custom lower non-128-bit vectors
892       if (!VT.is128BitVector())
893         continue;
894       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
895       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
896       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
897     }
898
899     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
900     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
901     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
902     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
903     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
904     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
905
906     if (Subtarget->is64Bit()) {
907       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
908       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
909     }
910
911     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
912     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
913       MVT VT = (MVT::SimpleValueType)i;
914
915       // Do not attempt to promote non-128-bit vectors
916       if (!VT.is128BitVector())
917         continue;
918
919       setOperationAction(ISD::AND,    VT, Promote);
920       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
921       setOperationAction(ISD::OR,     VT, Promote);
922       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
923       setOperationAction(ISD::XOR,    VT, Promote);
924       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
925       setOperationAction(ISD::LOAD,   VT, Promote);
926       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
927       setOperationAction(ISD::SELECT, VT, Promote);
928       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
929     }
930
931     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
932
933     // Custom lower v2i64 and v2f64 selects.
934     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
935     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
936     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
937     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
938
939     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
940     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
941
942     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
943   }
944
945   if (Subtarget->hasSSE41()) {
946     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
947     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
948     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
949     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
950     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
951     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
952     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
953     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
954     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
955     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
956
957     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
958     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
959
960     // FIXME: Do we need to handle scalar-to-vector here?
961     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
962
963     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
964     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
965     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
966     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
967     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
968
969     // i8 and i16 vectors are custom , because the source register and source
970     // source memory operand types are not the same width.  f32 vectors are
971     // custom since the immediate controlling the insert encodes additional
972     // information.
973     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
974     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
976     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
977
978     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
979     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
980     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
981     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
982
983     // FIXME: these should be Legal but thats only for the case where
984     // the index is constant.  For now custom expand to deal with that.
985     if (Subtarget->is64Bit()) {
986       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
987       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
988     }
989   }
990
991   if (Subtarget->hasSSE2()) {
992     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
993     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
994
995     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
996     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
997
998     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
999     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1000
1001     if (Subtarget->hasAVX2()) {
1002       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1003       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1004
1005       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1006       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1007
1008       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1009     } else {
1010       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1011       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1012
1013       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1014       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1015
1016       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1017     }
1018   }
1019
1020   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1021     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1022     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1023     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1024     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1025     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1026     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1027
1028     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1029     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1031
1032     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1033     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1034     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1035     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1036     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1037     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1038     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1039     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1040
1041     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1042     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1043     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1044     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1046     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1047     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1048     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1049
1050     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1051     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1052     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1053
1054     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1055
1056     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1057     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1058
1059     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1060     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1061
1062     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1063     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1064
1065     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1066     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1067     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1068     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1069
1070     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1071     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1072     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1073
1074     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1075     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1076     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1077     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1078
1079     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1080       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1081       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1082       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1083       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1084       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1085       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1086     }
1087
1088     if (Subtarget->hasAVX2()) {
1089       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1090       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1091       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1092       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1093
1094       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1095       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1096       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1097       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1098
1099       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1100       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1101       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1102       // Don't lower v32i8 because there is no 128-bit byte mul
1103
1104       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1105
1106       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1107       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1108
1109       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1110       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1111
1112       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1113     } else {
1114       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1116       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1117       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1118
1119       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1120       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1121       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1122       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1123
1124       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1125       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1126       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1127       // Don't lower v32i8 because there is no 128-bit byte mul
1128
1129       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1130       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1131
1132       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1133       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1134
1135       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1136     }
1137
1138     // Custom lower several nodes for 256-bit types.
1139     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1140              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1141       MVT VT = (MVT::SimpleValueType)i;
1142
1143       // Extract subvector is special because the value type
1144       // (result) is 128-bit but the source is 256-bit wide.
1145       if (VT.is128BitVector())
1146         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1147
1148       // Do not attempt to custom lower other non-256-bit vectors
1149       if (!VT.is256BitVector())
1150         continue;
1151
1152       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1153       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1154       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1155       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1156       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1157       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1158       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1159     }
1160
1161     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1162     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1163       MVT VT = (MVT::SimpleValueType)i;
1164
1165       // Do not attempt to promote non-256-bit vectors
1166       if (!VT.is256BitVector())
1167         continue;
1168
1169       setOperationAction(ISD::AND,    VT, Promote);
1170       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1171       setOperationAction(ISD::OR,     VT, Promote);
1172       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1173       setOperationAction(ISD::XOR,    VT, Promote);
1174       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1175       setOperationAction(ISD::LOAD,   VT, Promote);
1176       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1177       setOperationAction(ISD::SELECT, VT, Promote);
1178       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1179     }
1180   }
1181
1182   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1183   // of this type with custom code.
1184   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1185            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1186     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1187                        Custom);
1188   }
1189
1190   // We want to custom lower some of our intrinsics.
1191   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1192   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1193
1194
1195   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1196   // handle type legalization for these operations here.
1197   //
1198   // FIXME: We really should do custom legalization for addition and
1199   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1200   // than generic legalization for 64-bit multiplication-with-overflow, though.
1201   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1202     // Add/Sub/Mul with overflow operations are custom lowered.
1203     MVT VT = IntVTs[i];
1204     setOperationAction(ISD::SADDO, VT, Custom);
1205     setOperationAction(ISD::UADDO, VT, Custom);
1206     setOperationAction(ISD::SSUBO, VT, Custom);
1207     setOperationAction(ISD::USUBO, VT, Custom);
1208     setOperationAction(ISD::SMULO, VT, Custom);
1209     setOperationAction(ISD::UMULO, VT, Custom);
1210   }
1211
1212   // There are no 8-bit 3-address imul/mul instructions
1213   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1214   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1215
1216   if (!Subtarget->is64Bit()) {
1217     // These libcalls are not available in 32-bit.
1218     setLibcallName(RTLIB::SHL_I128, 0);
1219     setLibcallName(RTLIB::SRL_I128, 0);
1220     setLibcallName(RTLIB::SRA_I128, 0);
1221   }
1222
1223   // We have target-specific dag combine patterns for the following nodes:
1224   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1225   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1226   setTargetDAGCombine(ISD::VSELECT);
1227   setTargetDAGCombine(ISD::SELECT);
1228   setTargetDAGCombine(ISD::SHL);
1229   setTargetDAGCombine(ISD::SRA);
1230   setTargetDAGCombine(ISD::SRL);
1231   setTargetDAGCombine(ISD::OR);
1232   setTargetDAGCombine(ISD::AND);
1233   setTargetDAGCombine(ISD::ADD);
1234   setTargetDAGCombine(ISD::FADD);
1235   setTargetDAGCombine(ISD::FSUB);
1236   setTargetDAGCombine(ISD::FMA);
1237   setTargetDAGCombine(ISD::SUB);
1238   setTargetDAGCombine(ISD::LOAD);
1239   setTargetDAGCombine(ISD::STORE);
1240   setTargetDAGCombine(ISD::ZERO_EXTEND);
1241   setTargetDAGCombine(ISD::ANY_EXTEND);
1242   setTargetDAGCombine(ISD::SIGN_EXTEND);
1243   setTargetDAGCombine(ISD::TRUNCATE);
1244   setTargetDAGCombine(ISD::UINT_TO_FP);
1245   setTargetDAGCombine(ISD::SINT_TO_FP);
1246   setTargetDAGCombine(ISD::SETCC);
1247   setTargetDAGCombine(ISD::FP_TO_SINT);
1248   if (Subtarget->is64Bit())
1249     setTargetDAGCombine(ISD::MUL);
1250   setTargetDAGCombine(ISD::XOR);
1251
1252   computeRegisterProperties();
1253
1254   // On Darwin, -Os means optimize for size without hurting performance,
1255   // do not reduce the limit.
1256   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1257   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1258   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1259   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1260   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1261   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1262   setPrefLoopAlignment(4); // 2^4 bytes.
1263   benefitFromCodePlacementOpt = true;
1264
1265   // Predictable cmov don't hurt on atom because it's in-order.
1266   predictableSelectIsExpensive = !Subtarget->isAtom();
1267
1268   setPrefFunctionAlignment(4); // 2^4 bytes.
1269 }
1270
1271
1272 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1273   if (!VT.isVector()) return MVT::i8;
1274   return VT.changeVectorElementTypeToInteger();
1275 }
1276
1277
1278 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1279 /// the desired ByVal argument alignment.
1280 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1281   if (MaxAlign == 16)
1282     return;
1283   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1284     if (VTy->getBitWidth() == 128)
1285       MaxAlign = 16;
1286   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1287     unsigned EltAlign = 0;
1288     getMaxByValAlign(ATy->getElementType(), EltAlign);
1289     if (EltAlign > MaxAlign)
1290       MaxAlign = EltAlign;
1291   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1292     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1293       unsigned EltAlign = 0;
1294       getMaxByValAlign(STy->getElementType(i), EltAlign);
1295       if (EltAlign > MaxAlign)
1296         MaxAlign = EltAlign;
1297       if (MaxAlign == 16)
1298         break;
1299     }
1300   }
1301 }
1302
1303 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1304 /// function arguments in the caller parameter area. For X86, aggregates
1305 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1306 /// are at 4-byte boundaries.
1307 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1308   if (Subtarget->is64Bit()) {
1309     // Max of 8 and alignment of type.
1310     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1311     if (TyAlign > 8)
1312       return TyAlign;
1313     return 8;
1314   }
1315
1316   unsigned Align = 4;
1317   if (Subtarget->hasSSE1())
1318     getMaxByValAlign(Ty, Align);
1319   return Align;
1320 }
1321
1322 /// getOptimalMemOpType - Returns the target specific optimal type for load
1323 /// and store operations as a result of memset, memcpy, and memmove
1324 /// lowering. If DstAlign is zero that means it's safe to destination
1325 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1326 /// means there isn't a need to check it against alignment requirement,
1327 /// probably because the source does not need to be loaded. If
1328 /// 'IsZeroVal' is true, that means it's safe to return a
1329 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1330 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1331 /// constant so it does not need to be loaded.
1332 /// It returns EVT::Other if the type should be determined using generic
1333 /// target-independent logic.
1334 EVT
1335 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1336                                        unsigned DstAlign, unsigned SrcAlign,
1337                                        bool IsZeroVal,
1338                                        bool MemcpyStrSrc,
1339                                        MachineFunction &MF) const {
1340   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1341   // linux.  This is because the stack realignment code can't handle certain
1342   // cases like PR2962.  This should be removed when PR2962 is fixed.
1343   const Function *F = MF.getFunction();
1344   if (IsZeroVal &&
1345       !F->getFnAttributes().hasNoImplicitFloatAttr()) {
1346     if (Size >= 16 &&
1347         (Subtarget->isUnalignedMemAccessFast() ||
1348          ((DstAlign == 0 || DstAlign >= 16) &&
1349           (SrcAlign == 0 || SrcAlign >= 16))) &&
1350         Subtarget->getStackAlignment() >= 16) {
1351       if (Subtarget->getStackAlignment() >= 32) {
1352         if (Subtarget->hasAVX2())
1353           return MVT::v8i32;
1354         if (Subtarget->hasAVX())
1355           return MVT::v8f32;
1356       }
1357       if (Subtarget->hasSSE2())
1358         return MVT::v4i32;
1359       if (Subtarget->hasSSE1())
1360         return MVT::v4f32;
1361     } else if (!MemcpyStrSrc && Size >= 8 &&
1362                !Subtarget->is64Bit() &&
1363                Subtarget->getStackAlignment() >= 8 &&
1364                Subtarget->hasSSE2()) {
1365       // Do not use f64 to lower memcpy if source is string constant. It's
1366       // better to use i32 to avoid the loads.
1367       return MVT::f64;
1368     }
1369   }
1370   if (Subtarget->is64Bit() && Size >= 8)
1371     return MVT::i64;
1372   return MVT::i32;
1373 }
1374
1375 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1376 /// current function.  The returned value is a member of the
1377 /// MachineJumpTableInfo::JTEntryKind enum.
1378 unsigned X86TargetLowering::getJumpTableEncoding() const {
1379   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1380   // symbol.
1381   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1382       Subtarget->isPICStyleGOT())
1383     return MachineJumpTableInfo::EK_Custom32;
1384
1385   // Otherwise, use the normal jump table encoding heuristics.
1386   return TargetLowering::getJumpTableEncoding();
1387 }
1388
1389 const MCExpr *
1390 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1391                                              const MachineBasicBlock *MBB,
1392                                              unsigned uid,MCContext &Ctx) const{
1393   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1394          Subtarget->isPICStyleGOT());
1395   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1396   // entries.
1397   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1398                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1399 }
1400
1401 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1402 /// jumptable.
1403 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1404                                                     SelectionDAG &DAG) const {
1405   if (!Subtarget->is64Bit())
1406     // This doesn't have DebugLoc associated with it, but is not really the
1407     // same as a Register.
1408     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1409   return Table;
1410 }
1411
1412 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1413 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1414 /// MCExpr.
1415 const MCExpr *X86TargetLowering::
1416 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1417                              MCContext &Ctx) const {
1418   // X86-64 uses RIP relative addressing based on the jump table label.
1419   if (Subtarget->isPICStyleRIPRel())
1420     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1421
1422   // Otherwise, the reference is relative to the PIC base.
1423   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1424 }
1425
1426 // FIXME: Why this routine is here? Move to RegInfo!
1427 std::pair<const TargetRegisterClass*, uint8_t>
1428 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1429   const TargetRegisterClass *RRC = 0;
1430   uint8_t Cost = 1;
1431   switch (VT.getSimpleVT().SimpleTy) {
1432   default:
1433     return TargetLowering::findRepresentativeClass(VT);
1434   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1435     RRC = Subtarget->is64Bit() ?
1436       (const TargetRegisterClass*)&X86::GR64RegClass :
1437       (const TargetRegisterClass*)&X86::GR32RegClass;
1438     break;
1439   case MVT::x86mmx:
1440     RRC = &X86::VR64RegClass;
1441     break;
1442   case MVT::f32: case MVT::f64:
1443   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1444   case MVT::v4f32: case MVT::v2f64:
1445   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1446   case MVT::v4f64:
1447     RRC = &X86::VR128RegClass;
1448     break;
1449   }
1450   return std::make_pair(RRC, Cost);
1451 }
1452
1453 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1454                                                unsigned &Offset) const {
1455   if (!Subtarget->isTargetLinux())
1456     return false;
1457
1458   if (Subtarget->is64Bit()) {
1459     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1460     Offset = 0x28;
1461     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1462       AddressSpace = 256;
1463     else
1464       AddressSpace = 257;
1465   } else {
1466     // %gs:0x14 on i386
1467     Offset = 0x14;
1468     AddressSpace = 256;
1469   }
1470   return true;
1471 }
1472
1473
1474 //===----------------------------------------------------------------------===//
1475 //               Return Value Calling Convention Implementation
1476 //===----------------------------------------------------------------------===//
1477
1478 #include "X86GenCallingConv.inc"
1479
1480 bool
1481 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1482                                   MachineFunction &MF, bool isVarArg,
1483                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1484                         LLVMContext &Context) const {
1485   SmallVector<CCValAssign, 16> RVLocs;
1486   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1487                  RVLocs, Context);
1488   return CCInfo.CheckReturn(Outs, RetCC_X86);
1489 }
1490
1491 SDValue
1492 X86TargetLowering::LowerReturn(SDValue Chain,
1493                                CallingConv::ID CallConv, bool isVarArg,
1494                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1495                                const SmallVectorImpl<SDValue> &OutVals,
1496                                DebugLoc dl, SelectionDAG &DAG) const {
1497   MachineFunction &MF = DAG.getMachineFunction();
1498   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1499
1500   SmallVector<CCValAssign, 16> RVLocs;
1501   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1502                  RVLocs, *DAG.getContext());
1503   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1504
1505   // Add the regs to the liveout set for the function.
1506   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1507   for (unsigned i = 0; i != RVLocs.size(); ++i)
1508     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1509       MRI.addLiveOut(RVLocs[i].getLocReg());
1510
1511   SDValue Flag;
1512
1513   SmallVector<SDValue, 6> RetOps;
1514   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1515   // Operand #1 = Bytes To Pop
1516   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1517                    MVT::i16));
1518
1519   // Copy the result values into the output registers.
1520   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1521     CCValAssign &VA = RVLocs[i];
1522     assert(VA.isRegLoc() && "Can only return in registers!");
1523     SDValue ValToCopy = OutVals[i];
1524     EVT ValVT = ValToCopy.getValueType();
1525
1526     // Promote values to the appropriate types
1527     if (VA.getLocInfo() == CCValAssign::SExt)
1528       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1529     else if (VA.getLocInfo() == CCValAssign::ZExt)
1530       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1531     else if (VA.getLocInfo() == CCValAssign::AExt)
1532       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1533     else if (VA.getLocInfo() == CCValAssign::BCvt)
1534       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1535
1536     // If this is x86-64, and we disabled SSE, we can't return FP values,
1537     // or SSE or MMX vectors.
1538     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1539          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1540           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1541       report_fatal_error("SSE register return with SSE disabled");
1542     }
1543     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1544     // llvm-gcc has never done it right and no one has noticed, so this
1545     // should be OK for now.
1546     if (ValVT == MVT::f64 &&
1547         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1548       report_fatal_error("SSE2 register return with SSE2 disabled");
1549
1550     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1551     // the RET instruction and handled by the FP Stackifier.
1552     if (VA.getLocReg() == X86::ST0 ||
1553         VA.getLocReg() == X86::ST1) {
1554       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1555       // change the value to the FP stack register class.
1556       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1557         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1558       RetOps.push_back(ValToCopy);
1559       // Don't emit a copytoreg.
1560       continue;
1561     }
1562
1563     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1564     // which is returned in RAX / RDX.
1565     if (Subtarget->is64Bit()) {
1566       if (ValVT == MVT::x86mmx) {
1567         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1568           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1569           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1570                                   ValToCopy);
1571           // If we don't have SSE2 available, convert to v4f32 so the generated
1572           // register is legal.
1573           if (!Subtarget->hasSSE2())
1574             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1575         }
1576       }
1577     }
1578
1579     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1580     Flag = Chain.getValue(1);
1581   }
1582
1583   // The x86-64 ABI for returning structs by value requires that we copy
1584   // the sret argument into %rax for the return. We saved the argument into
1585   // a virtual register in the entry block, so now we copy the value out
1586   // and into %rax.
1587   if (Subtarget->is64Bit() &&
1588       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1589     MachineFunction &MF = DAG.getMachineFunction();
1590     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1591     unsigned Reg = FuncInfo->getSRetReturnReg();
1592     assert(Reg &&
1593            "SRetReturnReg should have been set in LowerFormalArguments().");
1594     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1595
1596     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1597     Flag = Chain.getValue(1);
1598
1599     // RAX now acts like a return value.
1600     MRI.addLiveOut(X86::RAX);
1601   }
1602
1603   RetOps[0] = Chain;  // Update chain.
1604
1605   // Add the flag if we have it.
1606   if (Flag.getNode())
1607     RetOps.push_back(Flag);
1608
1609   return DAG.getNode(X86ISD::RET_FLAG, dl,
1610                      MVT::Other, &RetOps[0], RetOps.size());
1611 }
1612
1613 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1614   if (N->getNumValues() != 1)
1615     return false;
1616   if (!N->hasNUsesOfValue(1, 0))
1617     return false;
1618
1619   SDValue TCChain = Chain;
1620   SDNode *Copy = *N->use_begin();
1621   if (Copy->getOpcode() == ISD::CopyToReg) {
1622     // If the copy has a glue operand, we conservatively assume it isn't safe to
1623     // perform a tail call.
1624     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1625       return false;
1626     TCChain = Copy->getOperand(0);
1627   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1628     return false;
1629
1630   bool HasRet = false;
1631   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1632        UI != UE; ++UI) {
1633     if (UI->getOpcode() != X86ISD::RET_FLAG)
1634       return false;
1635     HasRet = true;
1636   }
1637
1638   if (!HasRet)
1639     return false;
1640
1641   Chain = TCChain;
1642   return true;
1643 }
1644
1645 EVT
1646 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1647                                             ISD::NodeType ExtendKind) const {
1648   MVT ReturnMVT;
1649   // TODO: Is this also valid on 32-bit?
1650   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1651     ReturnMVT = MVT::i8;
1652   else
1653     ReturnMVT = MVT::i32;
1654
1655   EVT MinVT = getRegisterType(Context, ReturnMVT);
1656   return VT.bitsLT(MinVT) ? MinVT : VT;
1657 }
1658
1659 /// LowerCallResult - Lower the result values of a call into the
1660 /// appropriate copies out of appropriate physical registers.
1661 ///
1662 SDValue
1663 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1664                                    CallingConv::ID CallConv, bool isVarArg,
1665                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1666                                    DebugLoc dl, SelectionDAG &DAG,
1667                                    SmallVectorImpl<SDValue> &InVals) const {
1668
1669   // Assign locations to each value returned by this call.
1670   SmallVector<CCValAssign, 16> RVLocs;
1671   bool Is64Bit = Subtarget->is64Bit();
1672   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1673                  getTargetMachine(), RVLocs, *DAG.getContext());
1674   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1675
1676   // Copy all of the result registers out of their specified physreg.
1677   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1678     CCValAssign &VA = RVLocs[i];
1679     EVT CopyVT = VA.getValVT();
1680
1681     // If this is x86-64, and we disabled SSE, we can't return FP values
1682     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1683         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1684       report_fatal_error("SSE register return with SSE disabled");
1685     }
1686
1687     SDValue Val;
1688
1689     // If this is a call to a function that returns an fp value on the floating
1690     // point stack, we must guarantee the value is popped from the stack, so
1691     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1692     // if the return value is not used. We use the FpPOP_RETVAL instruction
1693     // instead.
1694     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1695       // If we prefer to use the value in xmm registers, copy it out as f80 and
1696       // use a truncate to move it from fp stack reg to xmm reg.
1697       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1698       SDValue Ops[] = { Chain, InFlag };
1699       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1700                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1701       Val = Chain.getValue(0);
1702
1703       // Round the f80 to the right size, which also moves it to the appropriate
1704       // xmm register.
1705       if (CopyVT != VA.getValVT())
1706         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1707                           // This truncation won't change the value.
1708                           DAG.getIntPtrConstant(1));
1709     } else {
1710       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1711                                  CopyVT, InFlag).getValue(1);
1712       Val = Chain.getValue(0);
1713     }
1714     InFlag = Chain.getValue(2);
1715     InVals.push_back(Val);
1716   }
1717
1718   return Chain;
1719 }
1720
1721
1722 //===----------------------------------------------------------------------===//
1723 //                C & StdCall & Fast Calling Convention implementation
1724 //===----------------------------------------------------------------------===//
1725 //  StdCall calling convention seems to be standard for many Windows' API
1726 //  routines and around. It differs from C calling convention just a little:
1727 //  callee should clean up the stack, not caller. Symbols should be also
1728 //  decorated in some fancy way :) It doesn't support any vector arguments.
1729 //  For info on fast calling convention see Fast Calling Convention (tail call)
1730 //  implementation LowerX86_32FastCCCallTo.
1731
1732 /// CallIsStructReturn - Determines whether a call uses struct return
1733 /// semantics.
1734 enum StructReturnType {
1735   NotStructReturn,
1736   RegStructReturn,
1737   StackStructReturn
1738 };
1739 static StructReturnType
1740 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1741   if (Outs.empty())
1742     return NotStructReturn;
1743
1744   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1745   if (!Flags.isSRet())
1746     return NotStructReturn;
1747   if (Flags.isInReg())
1748     return RegStructReturn;
1749   return StackStructReturn;
1750 }
1751
1752 /// ArgsAreStructReturn - Determines whether a function uses struct
1753 /// return semantics.
1754 static StructReturnType
1755 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1756   if (Ins.empty())
1757     return NotStructReturn;
1758
1759   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1760   if (!Flags.isSRet())
1761     return NotStructReturn;
1762   if (Flags.isInReg())
1763     return RegStructReturn;
1764   return StackStructReturn;
1765 }
1766
1767 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1768 /// by "Src" to address "Dst" with size and alignment information specified by
1769 /// the specific parameter attribute. The copy will be passed as a byval
1770 /// function parameter.
1771 static SDValue
1772 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1773                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1774                           DebugLoc dl) {
1775   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1776
1777   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1778                        /*isVolatile*/false, /*AlwaysInline=*/true,
1779                        MachinePointerInfo(), MachinePointerInfo());
1780 }
1781
1782 /// IsTailCallConvention - Return true if the calling convention is one that
1783 /// supports tail call optimization.
1784 static bool IsTailCallConvention(CallingConv::ID CC) {
1785   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1786 }
1787
1788 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1789   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1790     return false;
1791
1792   CallSite CS(CI);
1793   CallingConv::ID CalleeCC = CS.getCallingConv();
1794   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1795     return false;
1796
1797   return true;
1798 }
1799
1800 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1801 /// a tailcall target by changing its ABI.
1802 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1803                                    bool GuaranteedTailCallOpt) {
1804   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1805 }
1806
1807 SDValue
1808 X86TargetLowering::LowerMemArgument(SDValue Chain,
1809                                     CallingConv::ID CallConv,
1810                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1811                                     DebugLoc dl, SelectionDAG &DAG,
1812                                     const CCValAssign &VA,
1813                                     MachineFrameInfo *MFI,
1814                                     unsigned i) const {
1815   // Create the nodes corresponding to a load from this parameter slot.
1816   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1817   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1818                               getTargetMachine().Options.GuaranteedTailCallOpt);
1819   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1820   EVT ValVT;
1821
1822   // If value is passed by pointer we have address passed instead of the value
1823   // itself.
1824   if (VA.getLocInfo() == CCValAssign::Indirect)
1825     ValVT = VA.getLocVT();
1826   else
1827     ValVT = VA.getValVT();
1828
1829   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1830   // changed with more analysis.
1831   // In case of tail call optimization mark all arguments mutable. Since they
1832   // could be overwritten by lowering of arguments in case of a tail call.
1833   if (Flags.isByVal()) {
1834     unsigned Bytes = Flags.getByValSize();
1835     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1836     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1837     return DAG.getFrameIndex(FI, getPointerTy());
1838   } else {
1839     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1840                                     VA.getLocMemOffset(), isImmutable);
1841     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1842     return DAG.getLoad(ValVT, dl, Chain, FIN,
1843                        MachinePointerInfo::getFixedStack(FI),
1844                        false, false, false, 0);
1845   }
1846 }
1847
1848 SDValue
1849 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1850                                         CallingConv::ID CallConv,
1851                                         bool isVarArg,
1852                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1853                                         DebugLoc dl,
1854                                         SelectionDAG &DAG,
1855                                         SmallVectorImpl<SDValue> &InVals)
1856                                           const {
1857   MachineFunction &MF = DAG.getMachineFunction();
1858   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1859
1860   const Function* Fn = MF.getFunction();
1861   if (Fn->hasExternalLinkage() &&
1862       Subtarget->isTargetCygMing() &&
1863       Fn->getName() == "main")
1864     FuncInfo->setForceFramePointer(true);
1865
1866   MachineFrameInfo *MFI = MF.getFrameInfo();
1867   bool Is64Bit = Subtarget->is64Bit();
1868   bool IsWindows = Subtarget->isTargetWindows();
1869   bool IsWin64 = Subtarget->isTargetWin64();
1870
1871   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1872          "Var args not supported with calling convention fastcc or ghc");
1873
1874   // Assign locations to all of the incoming arguments.
1875   SmallVector<CCValAssign, 16> ArgLocs;
1876   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1877                  ArgLocs, *DAG.getContext());
1878
1879   // Allocate shadow area for Win64
1880   if (IsWin64) {
1881     CCInfo.AllocateStack(32, 8);
1882   }
1883
1884   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1885
1886   unsigned LastVal = ~0U;
1887   SDValue ArgValue;
1888   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1889     CCValAssign &VA = ArgLocs[i];
1890     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1891     // places.
1892     assert(VA.getValNo() != LastVal &&
1893            "Don't support value assigned to multiple locs yet");
1894     (void)LastVal;
1895     LastVal = VA.getValNo();
1896
1897     if (VA.isRegLoc()) {
1898       EVT RegVT = VA.getLocVT();
1899       const TargetRegisterClass *RC;
1900       if (RegVT == MVT::i32)
1901         RC = &X86::GR32RegClass;
1902       else if (Is64Bit && RegVT == MVT::i64)
1903         RC = &X86::GR64RegClass;
1904       else if (RegVT == MVT::f32)
1905         RC = &X86::FR32RegClass;
1906       else if (RegVT == MVT::f64)
1907         RC = &X86::FR64RegClass;
1908       else if (RegVT.is256BitVector())
1909         RC = &X86::VR256RegClass;
1910       else if (RegVT.is128BitVector())
1911         RC = &X86::VR128RegClass;
1912       else if (RegVT == MVT::x86mmx)
1913         RC = &X86::VR64RegClass;
1914       else
1915         llvm_unreachable("Unknown argument type!");
1916
1917       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1918       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1919
1920       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1921       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1922       // right size.
1923       if (VA.getLocInfo() == CCValAssign::SExt)
1924         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1925                                DAG.getValueType(VA.getValVT()));
1926       else if (VA.getLocInfo() == CCValAssign::ZExt)
1927         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1928                                DAG.getValueType(VA.getValVT()));
1929       else if (VA.getLocInfo() == CCValAssign::BCvt)
1930         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1931
1932       if (VA.isExtInLoc()) {
1933         // Handle MMX values passed in XMM regs.
1934         if (RegVT.isVector()) {
1935           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1936                                  ArgValue);
1937         } else
1938           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1939       }
1940     } else {
1941       assert(VA.isMemLoc());
1942       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1943     }
1944
1945     // If value is passed via pointer - do a load.
1946     if (VA.getLocInfo() == CCValAssign::Indirect)
1947       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1948                              MachinePointerInfo(), false, false, false, 0);
1949
1950     InVals.push_back(ArgValue);
1951   }
1952
1953   // The x86-64 ABI for returning structs by value requires that we copy
1954   // the sret argument into %rax for the return. Save the argument into
1955   // a virtual register so that we can access it from the return points.
1956   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1957     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1958     unsigned Reg = FuncInfo->getSRetReturnReg();
1959     if (!Reg) {
1960       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1961       FuncInfo->setSRetReturnReg(Reg);
1962     }
1963     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1965   }
1966
1967   unsigned StackSize = CCInfo.getNextStackOffset();
1968   // Align stack specially for tail calls.
1969   if (FuncIsMadeTailCallSafe(CallConv,
1970                              MF.getTarget().Options.GuaranteedTailCallOpt))
1971     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1972
1973   // If the function takes variable number of arguments, make a frame index for
1974   // the start of the first vararg value... for expansion of llvm.va_start.
1975   if (isVarArg) {
1976     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1977                     CallConv != CallingConv::X86_ThisCall)) {
1978       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1979     }
1980     if (Is64Bit) {
1981       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1982
1983       // FIXME: We should really autogenerate these arrays
1984       static const uint16_t GPR64ArgRegsWin64[] = {
1985         X86::RCX, X86::RDX, X86::R8,  X86::R9
1986       };
1987       static const uint16_t GPR64ArgRegs64Bit[] = {
1988         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1989       };
1990       static const uint16_t XMMArgRegs64Bit[] = {
1991         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1992         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1993       };
1994       const uint16_t *GPR64ArgRegs;
1995       unsigned NumXMMRegs = 0;
1996
1997       if (IsWin64) {
1998         // The XMM registers which might contain var arg parameters are shadowed
1999         // in their paired GPR.  So we only need to save the GPR to their home
2000         // slots.
2001         TotalNumIntRegs = 4;
2002         GPR64ArgRegs = GPR64ArgRegsWin64;
2003       } else {
2004         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2005         GPR64ArgRegs = GPR64ArgRegs64Bit;
2006
2007         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2008                                                 TotalNumXMMRegs);
2009       }
2010       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2011                                                        TotalNumIntRegs);
2012
2013       bool NoImplicitFloatOps = Fn->getFnAttributes().hasNoImplicitFloatAttr();
2014       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2015              "SSE register cannot be used when SSE is disabled!");
2016       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2017                NoImplicitFloatOps) &&
2018              "SSE register cannot be used when SSE is disabled!");
2019       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2020           !Subtarget->hasSSE1())
2021         // Kernel mode asks for SSE to be disabled, so don't push them
2022         // on the stack.
2023         TotalNumXMMRegs = 0;
2024
2025       if (IsWin64) {
2026         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2027         // Get to the caller-allocated home save location.  Add 8 to account
2028         // for the return address.
2029         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2030         FuncInfo->setRegSaveFrameIndex(
2031           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2032         // Fixup to set vararg frame on shadow area (4 x i64).
2033         if (NumIntRegs < 4)
2034           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2035       } else {
2036         // For X86-64, if there are vararg parameters that are passed via
2037         // registers, then we must store them to their spots on the stack so
2038         // they may be loaded by deferencing the result of va_next.
2039         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2040         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2041         FuncInfo->setRegSaveFrameIndex(
2042           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2043                                false));
2044       }
2045
2046       // Store the integer parameter registers.
2047       SmallVector<SDValue, 8> MemOps;
2048       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2049                                         getPointerTy());
2050       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2051       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2052         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2053                                   DAG.getIntPtrConstant(Offset));
2054         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2055                                      &X86::GR64RegClass);
2056         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2057         SDValue Store =
2058           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2059                        MachinePointerInfo::getFixedStack(
2060                          FuncInfo->getRegSaveFrameIndex(), Offset),
2061                        false, false, 0);
2062         MemOps.push_back(Store);
2063         Offset += 8;
2064       }
2065
2066       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2067         // Now store the XMM (fp + vector) parameter registers.
2068         SmallVector<SDValue, 11> SaveXMMOps;
2069         SaveXMMOps.push_back(Chain);
2070
2071         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2072         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2073         SaveXMMOps.push_back(ALVal);
2074
2075         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2076                                FuncInfo->getRegSaveFrameIndex()));
2077         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2078                                FuncInfo->getVarArgsFPOffset()));
2079
2080         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2081           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2082                                        &X86::VR128RegClass);
2083           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2084           SaveXMMOps.push_back(Val);
2085         }
2086         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2087                                      MVT::Other,
2088                                      &SaveXMMOps[0], SaveXMMOps.size()));
2089       }
2090
2091       if (!MemOps.empty())
2092         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2093                             &MemOps[0], MemOps.size());
2094     }
2095   }
2096
2097   // Some CCs need callee pop.
2098   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2099                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2100     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2101   } else {
2102     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2103     // If this is an sret function, the return should pop the hidden pointer.
2104     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2105         argsAreStructReturn(Ins) == StackStructReturn)
2106       FuncInfo->setBytesToPopOnReturn(4);
2107   }
2108
2109   if (!Is64Bit) {
2110     // RegSaveFrameIndex is X86-64 only.
2111     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2112     if (CallConv == CallingConv::X86_FastCall ||
2113         CallConv == CallingConv::X86_ThisCall)
2114       // fastcc functions can't have varargs.
2115       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2116   }
2117
2118   FuncInfo->setArgumentStackSize(StackSize);
2119
2120   return Chain;
2121 }
2122
2123 SDValue
2124 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2125                                     SDValue StackPtr, SDValue Arg,
2126                                     DebugLoc dl, SelectionDAG &DAG,
2127                                     const CCValAssign &VA,
2128                                     ISD::ArgFlagsTy Flags) const {
2129   unsigned LocMemOffset = VA.getLocMemOffset();
2130   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2131   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2132   if (Flags.isByVal())
2133     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2134
2135   return DAG.getStore(Chain, dl, Arg, PtrOff,
2136                       MachinePointerInfo::getStack(LocMemOffset),
2137                       false, false, 0);
2138 }
2139
2140 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2141 /// optimization is performed and it is required.
2142 SDValue
2143 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2144                                            SDValue &OutRetAddr, SDValue Chain,
2145                                            bool IsTailCall, bool Is64Bit,
2146                                            int FPDiff, DebugLoc dl) const {
2147   // Adjust the Return address stack slot.
2148   EVT VT = getPointerTy();
2149   OutRetAddr = getReturnAddressFrameIndex(DAG);
2150
2151   // Load the "old" Return address.
2152   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2153                            false, false, false, 0);
2154   return SDValue(OutRetAddr.getNode(), 1);
2155 }
2156
2157 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2158 /// optimization is performed and it is required (FPDiff!=0).
2159 static SDValue
2160 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2161                          SDValue Chain, SDValue RetAddrFrIdx,
2162                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2163   // Store the return address to the appropriate stack slot.
2164   if (!FPDiff) return Chain;
2165   // Calculate the new stack slot for the return address.
2166   int SlotSize = Is64Bit ? 8 : 4;
2167   int NewReturnAddrFI =
2168     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2169   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2170   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2171   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2172                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2173                        false, false, 0);
2174   return Chain;
2175 }
2176
2177 SDValue
2178 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2179                              SmallVectorImpl<SDValue> &InVals) const {
2180   SelectionDAG &DAG                     = CLI.DAG;
2181   DebugLoc &dl                          = CLI.DL;
2182   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2183   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2184   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2185   SDValue Chain                         = CLI.Chain;
2186   SDValue Callee                        = CLI.Callee;
2187   CallingConv::ID CallConv              = CLI.CallConv;
2188   bool &isTailCall                      = CLI.IsTailCall;
2189   bool isVarArg                         = CLI.IsVarArg;
2190
2191   MachineFunction &MF = DAG.getMachineFunction();
2192   bool Is64Bit        = Subtarget->is64Bit();
2193   bool IsWin64        = Subtarget->isTargetWin64();
2194   bool IsWindows      = Subtarget->isTargetWindows();
2195   StructReturnType SR = callIsStructReturn(Outs);
2196   bool IsSibcall      = false;
2197
2198   if (MF.getTarget().Options.DisableTailCalls)
2199     isTailCall = false;
2200
2201   if (isTailCall) {
2202     // Check if it's really possible to do a tail call.
2203     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2204                     isVarArg, SR != NotStructReturn,
2205                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2206                     Outs, OutVals, Ins, DAG);
2207
2208     // Sibcalls are automatically detected tailcalls which do not require
2209     // ABI changes.
2210     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2211       IsSibcall = true;
2212
2213     if (isTailCall)
2214       ++NumTailCalls;
2215   }
2216
2217   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2218          "Var args not supported with calling convention fastcc or ghc");
2219
2220   // Analyze operands of the call, assigning locations to each operand.
2221   SmallVector<CCValAssign, 16> ArgLocs;
2222   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2223                  ArgLocs, *DAG.getContext());
2224
2225   // Allocate shadow area for Win64
2226   if (IsWin64) {
2227     CCInfo.AllocateStack(32, 8);
2228   }
2229
2230   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2231
2232   // Get a count of how many bytes are to be pushed on the stack.
2233   unsigned NumBytes = CCInfo.getNextStackOffset();
2234   if (IsSibcall)
2235     // This is a sibcall. The memory operands are available in caller's
2236     // own caller's stack.
2237     NumBytes = 0;
2238   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2239            IsTailCallConvention(CallConv))
2240     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2241
2242   int FPDiff = 0;
2243   if (isTailCall && !IsSibcall) {
2244     // Lower arguments at fp - stackoffset + fpdiff.
2245     unsigned NumBytesCallerPushed =
2246       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2247     FPDiff = NumBytesCallerPushed - NumBytes;
2248
2249     // Set the delta of movement of the returnaddr stackslot.
2250     // But only set if delta is greater than previous delta.
2251     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2252       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2253   }
2254
2255   if (!IsSibcall)
2256     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2257
2258   SDValue RetAddrFrIdx;
2259   // Load return address for tail calls.
2260   if (isTailCall && FPDiff)
2261     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2262                                     Is64Bit, FPDiff, dl);
2263
2264   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2265   SmallVector<SDValue, 8> MemOpChains;
2266   SDValue StackPtr;
2267
2268   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2269   // of tail call optimization arguments are handle later.
2270   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2271     CCValAssign &VA = ArgLocs[i];
2272     EVT RegVT = VA.getLocVT();
2273     SDValue Arg = OutVals[i];
2274     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2275     bool isByVal = Flags.isByVal();
2276
2277     // Promote the value if needed.
2278     switch (VA.getLocInfo()) {
2279     default: llvm_unreachable("Unknown loc info!");
2280     case CCValAssign::Full: break;
2281     case CCValAssign::SExt:
2282       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2283       break;
2284     case CCValAssign::ZExt:
2285       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2286       break;
2287     case CCValAssign::AExt:
2288       if (RegVT.is128BitVector()) {
2289         // Special case: passing MMX values in XMM registers.
2290         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2291         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2292         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2293       } else
2294         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2295       break;
2296     case CCValAssign::BCvt:
2297       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2298       break;
2299     case CCValAssign::Indirect: {
2300       // Store the argument.
2301       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2302       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2303       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2304                            MachinePointerInfo::getFixedStack(FI),
2305                            false, false, 0);
2306       Arg = SpillSlot;
2307       break;
2308     }
2309     }
2310
2311     if (VA.isRegLoc()) {
2312       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2313       if (isVarArg && IsWin64) {
2314         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2315         // shadow reg if callee is a varargs function.
2316         unsigned ShadowReg = 0;
2317         switch (VA.getLocReg()) {
2318         case X86::XMM0: ShadowReg = X86::RCX; break;
2319         case X86::XMM1: ShadowReg = X86::RDX; break;
2320         case X86::XMM2: ShadowReg = X86::R8; break;
2321         case X86::XMM3: ShadowReg = X86::R9; break;
2322         }
2323         if (ShadowReg)
2324           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2325       }
2326     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2327       assert(VA.isMemLoc());
2328       if (StackPtr.getNode() == 0)
2329         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2330       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2331                                              dl, DAG, VA, Flags));
2332     }
2333   }
2334
2335   if (!MemOpChains.empty())
2336     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2337                         &MemOpChains[0], MemOpChains.size());
2338
2339   if (Subtarget->isPICStyleGOT()) {
2340     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2341     // GOT pointer.
2342     if (!isTailCall) {
2343       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2344                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2345     } else {
2346       // If we are tail calling and generating PIC/GOT style code load the
2347       // address of the callee into ECX. The value in ecx is used as target of
2348       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2349       // for tail calls on PIC/GOT architectures. Normally we would just put the
2350       // address of GOT into ebx and then call target@PLT. But for tail calls
2351       // ebx would be restored (since ebx is callee saved) before jumping to the
2352       // target@PLT.
2353
2354       // Note: The actual moving to ECX is done further down.
2355       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2356       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2357           !G->getGlobal()->hasProtectedVisibility())
2358         Callee = LowerGlobalAddress(Callee, DAG);
2359       else if (isa<ExternalSymbolSDNode>(Callee))
2360         Callee = LowerExternalSymbol(Callee, DAG);
2361     }
2362   }
2363
2364   if (Is64Bit && isVarArg && !IsWin64) {
2365     // From AMD64 ABI document:
2366     // For calls that may call functions that use varargs or stdargs
2367     // (prototype-less calls or calls to functions containing ellipsis (...) in
2368     // the declaration) %al is used as hidden argument to specify the number
2369     // of SSE registers used. The contents of %al do not need to match exactly
2370     // the number of registers, but must be an ubound on the number of SSE
2371     // registers used and is in the range 0 - 8 inclusive.
2372
2373     // Count the number of XMM registers allocated.
2374     static const uint16_t XMMArgRegs[] = {
2375       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2376       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2377     };
2378     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2379     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2380            && "SSE registers cannot be used when SSE is disabled");
2381
2382     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2383                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2384   }
2385
2386   // For tail calls lower the arguments to the 'real' stack slot.
2387   if (isTailCall) {
2388     // Force all the incoming stack arguments to be loaded from the stack
2389     // before any new outgoing arguments are stored to the stack, because the
2390     // outgoing stack slots may alias the incoming argument stack slots, and
2391     // the alias isn't otherwise explicit. This is slightly more conservative
2392     // than necessary, because it means that each store effectively depends
2393     // on every argument instead of just those arguments it would clobber.
2394     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2395
2396     SmallVector<SDValue, 8> MemOpChains2;
2397     SDValue FIN;
2398     int FI = 0;
2399     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2400       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2401         CCValAssign &VA = ArgLocs[i];
2402         if (VA.isRegLoc())
2403           continue;
2404         assert(VA.isMemLoc());
2405         SDValue Arg = OutVals[i];
2406         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2407         // Create frame index.
2408         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2409         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2410         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2411         FIN = DAG.getFrameIndex(FI, getPointerTy());
2412
2413         if (Flags.isByVal()) {
2414           // Copy relative to framepointer.
2415           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2416           if (StackPtr.getNode() == 0)
2417             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2418                                           getPointerTy());
2419           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2420
2421           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2422                                                            ArgChain,
2423                                                            Flags, DAG, dl));
2424         } else {
2425           // Store relative to framepointer.
2426           MemOpChains2.push_back(
2427             DAG.getStore(ArgChain, dl, Arg, FIN,
2428                          MachinePointerInfo::getFixedStack(FI),
2429                          false, false, 0));
2430         }
2431       }
2432     }
2433
2434     if (!MemOpChains2.empty())
2435       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2436                           &MemOpChains2[0], MemOpChains2.size());
2437
2438     // Store the return address to the appropriate stack slot.
2439     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2440                                      FPDiff, dl);
2441   }
2442
2443   // Build a sequence of copy-to-reg nodes chained together with token chain
2444   // and flag operands which copy the outgoing args into registers.
2445   SDValue InFlag;
2446   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2447     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2448                              RegsToPass[i].second, InFlag);
2449     InFlag = Chain.getValue(1);
2450   }
2451
2452   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2453     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2454     // In the 64-bit large code model, we have to make all calls
2455     // through a register, since the call instruction's 32-bit
2456     // pc-relative offset may not be large enough to hold the whole
2457     // address.
2458   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2459     // If the callee is a GlobalAddress node (quite common, every direct call
2460     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2461     // it.
2462
2463     // We should use extra load for direct calls to dllimported functions in
2464     // non-JIT mode.
2465     const GlobalValue *GV = G->getGlobal();
2466     if (!GV->hasDLLImportLinkage()) {
2467       unsigned char OpFlags = 0;
2468       bool ExtraLoad = false;
2469       unsigned WrapperKind = ISD::DELETED_NODE;
2470
2471       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2472       // external symbols most go through the PLT in PIC mode.  If the symbol
2473       // has hidden or protected visibility, or if it is static or local, then
2474       // we don't need to use the PLT - we can directly call it.
2475       if (Subtarget->isTargetELF() &&
2476           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2477           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2478         OpFlags = X86II::MO_PLT;
2479       } else if (Subtarget->isPICStyleStubAny() &&
2480                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2481                  (!Subtarget->getTargetTriple().isMacOSX() ||
2482                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2483         // PC-relative references to external symbols should go through $stub,
2484         // unless we're building with the leopard linker or later, which
2485         // automatically synthesizes these stubs.
2486         OpFlags = X86II::MO_DARWIN_STUB;
2487       } else if (Subtarget->isPICStyleRIPRel() &&
2488                  isa<Function>(GV) &&
2489                  cast<Function>(GV)->getFnAttributes().hasNonLazyBindAttr()) {
2490         // If the function is marked as non-lazy, generate an indirect call
2491         // which loads from the GOT directly. This avoids runtime overhead
2492         // at the cost of eager binding (and one extra byte of encoding).
2493         OpFlags = X86II::MO_GOTPCREL;
2494         WrapperKind = X86ISD::WrapperRIP;
2495         ExtraLoad = true;
2496       }
2497
2498       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2499                                           G->getOffset(), OpFlags);
2500
2501       // Add a wrapper if needed.
2502       if (WrapperKind != ISD::DELETED_NODE)
2503         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2504       // Add extra indirection if needed.
2505       if (ExtraLoad)
2506         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2507                              MachinePointerInfo::getGOT(),
2508                              false, false, false, 0);
2509     }
2510   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2511     unsigned char OpFlags = 0;
2512
2513     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2514     // external symbols should go through the PLT.
2515     if (Subtarget->isTargetELF() &&
2516         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2517       OpFlags = X86II::MO_PLT;
2518     } else if (Subtarget->isPICStyleStubAny() &&
2519                (!Subtarget->getTargetTriple().isMacOSX() ||
2520                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2521       // PC-relative references to external symbols should go through $stub,
2522       // unless we're building with the leopard linker or later, which
2523       // automatically synthesizes these stubs.
2524       OpFlags = X86II::MO_DARWIN_STUB;
2525     }
2526
2527     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2528                                          OpFlags);
2529   }
2530
2531   // Returns a chain & a flag for retval copy to use.
2532   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2533   SmallVector<SDValue, 8> Ops;
2534
2535   if (!IsSibcall && isTailCall) {
2536     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2537                            DAG.getIntPtrConstant(0, true), InFlag);
2538     InFlag = Chain.getValue(1);
2539   }
2540
2541   Ops.push_back(Chain);
2542   Ops.push_back(Callee);
2543
2544   if (isTailCall)
2545     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2546
2547   // Add argument registers to the end of the list so that they are known live
2548   // into the call.
2549   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2550     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2551                                   RegsToPass[i].second.getValueType()));
2552
2553   // Add a register mask operand representing the call-preserved registers.
2554   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2555   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2556   assert(Mask && "Missing call preserved mask for calling convention");
2557   Ops.push_back(DAG.getRegisterMask(Mask));
2558
2559   if (InFlag.getNode())
2560     Ops.push_back(InFlag);
2561
2562   if (isTailCall) {
2563     // We used to do:
2564     //// If this is the first return lowered for this function, add the regs
2565     //// to the liveout set for the function.
2566     // This isn't right, although it's probably harmless on x86; liveouts
2567     // should be computed from returns not tail calls.  Consider a void
2568     // function making a tail call to a function returning int.
2569     return DAG.getNode(X86ISD::TC_RETURN, dl,
2570                        NodeTys, &Ops[0], Ops.size());
2571   }
2572
2573   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2574   InFlag = Chain.getValue(1);
2575
2576   // Create the CALLSEQ_END node.
2577   unsigned NumBytesForCalleeToPush;
2578   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2579                        getTargetMachine().Options.GuaranteedTailCallOpt))
2580     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2581   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2582            SR == StackStructReturn)
2583     // If this is a call to a struct-return function, the callee
2584     // pops the hidden struct pointer, so we have to push it back.
2585     // This is common for Darwin/X86, Linux & Mingw32 targets.
2586     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2587     NumBytesForCalleeToPush = 4;
2588   else
2589     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2590
2591   // Returns a flag for retval copy to use.
2592   if (!IsSibcall) {
2593     Chain = DAG.getCALLSEQ_END(Chain,
2594                                DAG.getIntPtrConstant(NumBytes, true),
2595                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2596                                                      true),
2597                                InFlag);
2598     InFlag = Chain.getValue(1);
2599   }
2600
2601   // Handle result values, copying them out of physregs into vregs that we
2602   // return.
2603   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2604                          Ins, dl, DAG, InVals);
2605 }
2606
2607
2608 //===----------------------------------------------------------------------===//
2609 //                Fast Calling Convention (tail call) implementation
2610 //===----------------------------------------------------------------------===//
2611
2612 //  Like std call, callee cleans arguments, convention except that ECX is
2613 //  reserved for storing the tail called function address. Only 2 registers are
2614 //  free for argument passing (inreg). Tail call optimization is performed
2615 //  provided:
2616 //                * tailcallopt is enabled
2617 //                * caller/callee are fastcc
2618 //  On X86_64 architecture with GOT-style position independent code only local
2619 //  (within module) calls are supported at the moment.
2620 //  To keep the stack aligned according to platform abi the function
2621 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2622 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2623 //  If a tail called function callee has more arguments than the caller the
2624 //  caller needs to make sure that there is room to move the RETADDR to. This is
2625 //  achieved by reserving an area the size of the argument delta right after the
2626 //  original REtADDR, but before the saved framepointer or the spilled registers
2627 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2628 //  stack layout:
2629 //    arg1
2630 //    arg2
2631 //    RETADDR
2632 //    [ new RETADDR
2633 //      move area ]
2634 //    (possible EBP)
2635 //    ESI
2636 //    EDI
2637 //    local1 ..
2638
2639 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2640 /// for a 16 byte align requirement.
2641 unsigned
2642 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2643                                                SelectionDAG& DAG) const {
2644   MachineFunction &MF = DAG.getMachineFunction();
2645   const TargetMachine &TM = MF.getTarget();
2646   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2647   unsigned StackAlignment = TFI.getStackAlignment();
2648   uint64_t AlignMask = StackAlignment - 1;
2649   int64_t Offset = StackSize;
2650   uint64_t SlotSize = TD->getPointerSize();
2651   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2652     // Number smaller than 12 so just add the difference.
2653     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2654   } else {
2655     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2656     Offset = ((~AlignMask) & Offset) + StackAlignment +
2657       (StackAlignment-SlotSize);
2658   }
2659   return Offset;
2660 }
2661
2662 /// MatchingStackOffset - Return true if the given stack call argument is
2663 /// already available in the same position (relatively) of the caller's
2664 /// incoming argument stack.
2665 static
2666 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2667                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2668                          const X86InstrInfo *TII) {
2669   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2670   int FI = INT_MAX;
2671   if (Arg.getOpcode() == ISD::CopyFromReg) {
2672     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2673     if (!TargetRegisterInfo::isVirtualRegister(VR))
2674       return false;
2675     MachineInstr *Def = MRI->getVRegDef(VR);
2676     if (!Def)
2677       return false;
2678     if (!Flags.isByVal()) {
2679       if (!TII->isLoadFromStackSlot(Def, FI))
2680         return false;
2681     } else {
2682       unsigned Opcode = Def->getOpcode();
2683       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2684           Def->getOperand(1).isFI()) {
2685         FI = Def->getOperand(1).getIndex();
2686         Bytes = Flags.getByValSize();
2687       } else
2688         return false;
2689     }
2690   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2691     if (Flags.isByVal())
2692       // ByVal argument is passed in as a pointer but it's now being
2693       // dereferenced. e.g.
2694       // define @foo(%struct.X* %A) {
2695       //   tail call @bar(%struct.X* byval %A)
2696       // }
2697       return false;
2698     SDValue Ptr = Ld->getBasePtr();
2699     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2700     if (!FINode)
2701       return false;
2702     FI = FINode->getIndex();
2703   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2704     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2705     FI = FINode->getIndex();
2706     Bytes = Flags.getByValSize();
2707   } else
2708     return false;
2709
2710   assert(FI != INT_MAX);
2711   if (!MFI->isFixedObjectIndex(FI))
2712     return false;
2713   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2714 }
2715
2716 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2717 /// for tail call optimization. Targets which want to do tail call
2718 /// optimization should implement this function.
2719 bool
2720 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2721                                                      CallingConv::ID CalleeCC,
2722                                                      bool isVarArg,
2723                                                      bool isCalleeStructRet,
2724                                                      bool isCallerStructRet,
2725                                                      Type *RetTy,
2726                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2727                                     const SmallVectorImpl<SDValue> &OutVals,
2728                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2729                                                      SelectionDAG& DAG) const {
2730   if (!IsTailCallConvention(CalleeCC) &&
2731       CalleeCC != CallingConv::C)
2732     return false;
2733
2734   // If -tailcallopt is specified, make fastcc functions tail-callable.
2735   const MachineFunction &MF = DAG.getMachineFunction();
2736   const Function *CallerF = DAG.getMachineFunction().getFunction();
2737
2738   // If the function return type is x86_fp80 and the callee return type is not,
2739   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2740   // perform a tailcall optimization here.
2741   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2742     return false;
2743
2744   CallingConv::ID CallerCC = CallerF->getCallingConv();
2745   bool CCMatch = CallerCC == CalleeCC;
2746
2747   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2748     if (IsTailCallConvention(CalleeCC) && CCMatch)
2749       return true;
2750     return false;
2751   }
2752
2753   // Look for obvious safe cases to perform tail call optimization that do not
2754   // require ABI changes. This is what gcc calls sibcall.
2755
2756   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2757   // emit a special epilogue.
2758   if (RegInfo->needsStackRealignment(MF))
2759     return false;
2760
2761   // Also avoid sibcall optimization if either caller or callee uses struct
2762   // return semantics.
2763   if (isCalleeStructRet || isCallerStructRet)
2764     return false;
2765
2766   // An stdcall caller is expected to clean up its arguments; the callee
2767   // isn't going to do that.
2768   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2769     return false;
2770
2771   // Do not sibcall optimize vararg calls unless all arguments are passed via
2772   // registers.
2773   if (isVarArg && !Outs.empty()) {
2774
2775     // Optimizing for varargs on Win64 is unlikely to be safe without
2776     // additional testing.
2777     if (Subtarget->isTargetWin64())
2778       return false;
2779
2780     SmallVector<CCValAssign, 16> ArgLocs;
2781     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2782                    getTargetMachine(), ArgLocs, *DAG.getContext());
2783
2784     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2785     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2786       if (!ArgLocs[i].isRegLoc())
2787         return false;
2788   }
2789
2790   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2791   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2792   // this into a sibcall.
2793   bool Unused = false;
2794   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2795     if (!Ins[i].Used) {
2796       Unused = true;
2797       break;
2798     }
2799   }
2800   if (Unused) {
2801     SmallVector<CCValAssign, 16> RVLocs;
2802     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2803                    getTargetMachine(), RVLocs, *DAG.getContext());
2804     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2805     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2806       CCValAssign &VA = RVLocs[i];
2807       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2808         return false;
2809     }
2810   }
2811
2812   // If the calling conventions do not match, then we'd better make sure the
2813   // results are returned in the same way as what the caller expects.
2814   if (!CCMatch) {
2815     SmallVector<CCValAssign, 16> RVLocs1;
2816     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2817                     getTargetMachine(), RVLocs1, *DAG.getContext());
2818     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2819
2820     SmallVector<CCValAssign, 16> RVLocs2;
2821     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2822                     getTargetMachine(), RVLocs2, *DAG.getContext());
2823     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2824
2825     if (RVLocs1.size() != RVLocs2.size())
2826       return false;
2827     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2828       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2829         return false;
2830       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2831         return false;
2832       if (RVLocs1[i].isRegLoc()) {
2833         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2834           return false;
2835       } else {
2836         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2837           return false;
2838       }
2839     }
2840   }
2841
2842   // If the callee takes no arguments then go on to check the results of the
2843   // call.
2844   if (!Outs.empty()) {
2845     // Check if stack adjustment is needed. For now, do not do this if any
2846     // argument is passed on the stack.
2847     SmallVector<CCValAssign, 16> ArgLocs;
2848     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2849                    getTargetMachine(), ArgLocs, *DAG.getContext());
2850
2851     // Allocate shadow area for Win64
2852     if (Subtarget->isTargetWin64()) {
2853       CCInfo.AllocateStack(32, 8);
2854     }
2855
2856     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2857     if (CCInfo.getNextStackOffset()) {
2858       MachineFunction &MF = DAG.getMachineFunction();
2859       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2860         return false;
2861
2862       // Check if the arguments are already laid out in the right way as
2863       // the caller's fixed stack objects.
2864       MachineFrameInfo *MFI = MF.getFrameInfo();
2865       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2866       const X86InstrInfo *TII =
2867         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2868       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2869         CCValAssign &VA = ArgLocs[i];
2870         SDValue Arg = OutVals[i];
2871         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2872         if (VA.getLocInfo() == CCValAssign::Indirect)
2873           return false;
2874         if (!VA.isRegLoc()) {
2875           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2876                                    MFI, MRI, TII))
2877             return false;
2878         }
2879       }
2880     }
2881
2882     // If the tailcall address may be in a register, then make sure it's
2883     // possible to register allocate for it. In 32-bit, the call address can
2884     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2885     // callee-saved registers are restored. These happen to be the same
2886     // registers used to pass 'inreg' arguments so watch out for those.
2887     if (!Subtarget->is64Bit() &&
2888         !isa<GlobalAddressSDNode>(Callee) &&
2889         !isa<ExternalSymbolSDNode>(Callee)) {
2890       unsigned NumInRegs = 0;
2891       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2892         CCValAssign &VA = ArgLocs[i];
2893         if (!VA.isRegLoc())
2894           continue;
2895         unsigned Reg = VA.getLocReg();
2896         switch (Reg) {
2897         default: break;
2898         case X86::EAX: case X86::EDX: case X86::ECX:
2899           if (++NumInRegs == 3)
2900             return false;
2901           break;
2902         }
2903       }
2904     }
2905   }
2906
2907   return true;
2908 }
2909
2910 FastISel *
2911 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2912                                   const TargetLibraryInfo *libInfo) const {
2913   return X86::createFastISel(funcInfo, libInfo);
2914 }
2915
2916
2917 //===----------------------------------------------------------------------===//
2918 //                           Other Lowering Hooks
2919 //===----------------------------------------------------------------------===//
2920
2921 static bool MayFoldLoad(SDValue Op) {
2922   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2923 }
2924
2925 static bool MayFoldIntoStore(SDValue Op) {
2926   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2927 }
2928
2929 static bool isTargetShuffle(unsigned Opcode) {
2930   switch(Opcode) {
2931   default: return false;
2932   case X86ISD::PSHUFD:
2933   case X86ISD::PSHUFHW:
2934   case X86ISD::PSHUFLW:
2935   case X86ISD::SHUFP:
2936   case X86ISD::PALIGN:
2937   case X86ISD::MOVLHPS:
2938   case X86ISD::MOVLHPD:
2939   case X86ISD::MOVHLPS:
2940   case X86ISD::MOVLPS:
2941   case X86ISD::MOVLPD:
2942   case X86ISD::MOVSHDUP:
2943   case X86ISD::MOVSLDUP:
2944   case X86ISD::MOVDDUP:
2945   case X86ISD::MOVSS:
2946   case X86ISD::MOVSD:
2947   case X86ISD::UNPCKL:
2948   case X86ISD::UNPCKH:
2949   case X86ISD::VPERMILP:
2950   case X86ISD::VPERM2X128:
2951   case X86ISD::VPERMI:
2952     return true;
2953   }
2954 }
2955
2956 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2957                                     SDValue V1, SelectionDAG &DAG) {
2958   switch(Opc) {
2959   default: llvm_unreachable("Unknown x86 shuffle node");
2960   case X86ISD::MOVSHDUP:
2961   case X86ISD::MOVSLDUP:
2962   case X86ISD::MOVDDUP:
2963     return DAG.getNode(Opc, dl, VT, V1);
2964   }
2965 }
2966
2967 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2968                                     SDValue V1, unsigned TargetMask,
2969                                     SelectionDAG &DAG) {
2970   switch(Opc) {
2971   default: llvm_unreachable("Unknown x86 shuffle node");
2972   case X86ISD::PSHUFD:
2973   case X86ISD::PSHUFHW:
2974   case X86ISD::PSHUFLW:
2975   case X86ISD::VPERMILP:
2976   case X86ISD::VPERMI:
2977     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2978   }
2979 }
2980
2981 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2982                                     SDValue V1, SDValue V2, unsigned TargetMask,
2983                                     SelectionDAG &DAG) {
2984   switch(Opc) {
2985   default: llvm_unreachable("Unknown x86 shuffle node");
2986   case X86ISD::PALIGN:
2987   case X86ISD::SHUFP:
2988   case X86ISD::VPERM2X128:
2989     return DAG.getNode(Opc, dl, VT, V1, V2,
2990                        DAG.getConstant(TargetMask, MVT::i8));
2991   }
2992 }
2993
2994 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2995                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2996   switch(Opc) {
2997   default: llvm_unreachable("Unknown x86 shuffle node");
2998   case X86ISD::MOVLHPS:
2999   case X86ISD::MOVLHPD:
3000   case X86ISD::MOVHLPS:
3001   case X86ISD::MOVLPS:
3002   case X86ISD::MOVLPD:
3003   case X86ISD::MOVSS:
3004   case X86ISD::MOVSD:
3005   case X86ISD::UNPCKL:
3006   case X86ISD::UNPCKH:
3007     return DAG.getNode(Opc, dl, VT, V1, V2);
3008   }
3009 }
3010
3011 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3012   MachineFunction &MF = DAG.getMachineFunction();
3013   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3014   int ReturnAddrIndex = FuncInfo->getRAIndex();
3015
3016   if (ReturnAddrIndex == 0) {
3017     // Set up a frame object for the return address.
3018     uint64_t SlotSize = TD->getPointerSize();
3019     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3020                                                            false);
3021     FuncInfo->setRAIndex(ReturnAddrIndex);
3022   }
3023
3024   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3025 }
3026
3027
3028 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3029                                        bool hasSymbolicDisplacement) {
3030   // Offset should fit into 32 bit immediate field.
3031   if (!isInt<32>(Offset))
3032     return false;
3033
3034   // If we don't have a symbolic displacement - we don't have any extra
3035   // restrictions.
3036   if (!hasSymbolicDisplacement)
3037     return true;
3038
3039   // FIXME: Some tweaks might be needed for medium code model.
3040   if (M != CodeModel::Small && M != CodeModel::Kernel)
3041     return false;
3042
3043   // For small code model we assume that latest object is 16MB before end of 31
3044   // bits boundary. We may also accept pretty large negative constants knowing
3045   // that all objects are in the positive half of address space.
3046   if (M == CodeModel::Small && Offset < 16*1024*1024)
3047     return true;
3048
3049   // For kernel code model we know that all object resist in the negative half
3050   // of 32bits address space. We may not accept negative offsets, since they may
3051   // be just off and we may accept pretty large positive ones.
3052   if (M == CodeModel::Kernel && Offset > 0)
3053     return true;
3054
3055   return false;
3056 }
3057
3058 /// isCalleePop - Determines whether the callee is required to pop its
3059 /// own arguments. Callee pop is necessary to support tail calls.
3060 bool X86::isCalleePop(CallingConv::ID CallingConv,
3061                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3062   if (IsVarArg)
3063     return false;
3064
3065   switch (CallingConv) {
3066   default:
3067     return false;
3068   case CallingConv::X86_StdCall:
3069     return !is64Bit;
3070   case CallingConv::X86_FastCall:
3071     return !is64Bit;
3072   case CallingConv::X86_ThisCall:
3073     return !is64Bit;
3074   case CallingConv::Fast:
3075     return TailCallOpt;
3076   case CallingConv::GHC:
3077     return TailCallOpt;
3078   }
3079 }
3080
3081 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3082 /// specific condition code, returning the condition code and the LHS/RHS of the
3083 /// comparison to make.
3084 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3085                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3086   if (!isFP) {
3087     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3088       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3089         // X > -1   -> X == 0, jump !sign.
3090         RHS = DAG.getConstant(0, RHS.getValueType());
3091         return X86::COND_NS;
3092       }
3093       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3094         // X < 0   -> X == 0, jump on sign.
3095         return X86::COND_S;
3096       }
3097       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3098         // X < 1   -> X <= 0
3099         RHS = DAG.getConstant(0, RHS.getValueType());
3100         return X86::COND_LE;
3101       }
3102     }
3103
3104     switch (SetCCOpcode) {
3105     default: llvm_unreachable("Invalid integer condition!");
3106     case ISD::SETEQ:  return X86::COND_E;
3107     case ISD::SETGT:  return X86::COND_G;
3108     case ISD::SETGE:  return X86::COND_GE;
3109     case ISD::SETLT:  return X86::COND_L;
3110     case ISD::SETLE:  return X86::COND_LE;
3111     case ISD::SETNE:  return X86::COND_NE;
3112     case ISD::SETULT: return X86::COND_B;
3113     case ISD::SETUGT: return X86::COND_A;
3114     case ISD::SETULE: return X86::COND_BE;
3115     case ISD::SETUGE: return X86::COND_AE;
3116     }
3117   }
3118
3119   // First determine if it is required or is profitable to flip the operands.
3120
3121   // If LHS is a foldable load, but RHS is not, flip the condition.
3122   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3123       !ISD::isNON_EXTLoad(RHS.getNode())) {
3124     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3125     std::swap(LHS, RHS);
3126   }
3127
3128   switch (SetCCOpcode) {
3129   default: break;
3130   case ISD::SETOLT:
3131   case ISD::SETOLE:
3132   case ISD::SETUGT:
3133   case ISD::SETUGE:
3134     std::swap(LHS, RHS);
3135     break;
3136   }
3137
3138   // On a floating point condition, the flags are set as follows:
3139   // ZF  PF  CF   op
3140   //  0 | 0 | 0 | X > Y
3141   //  0 | 0 | 1 | X < Y
3142   //  1 | 0 | 0 | X == Y
3143   //  1 | 1 | 1 | unordered
3144   switch (SetCCOpcode) {
3145   default: llvm_unreachable("Condcode should be pre-legalized away");
3146   case ISD::SETUEQ:
3147   case ISD::SETEQ:   return X86::COND_E;
3148   case ISD::SETOLT:              // flipped
3149   case ISD::SETOGT:
3150   case ISD::SETGT:   return X86::COND_A;
3151   case ISD::SETOLE:              // flipped
3152   case ISD::SETOGE:
3153   case ISD::SETGE:   return X86::COND_AE;
3154   case ISD::SETUGT:              // flipped
3155   case ISD::SETULT:
3156   case ISD::SETLT:   return X86::COND_B;
3157   case ISD::SETUGE:              // flipped
3158   case ISD::SETULE:
3159   case ISD::SETLE:   return X86::COND_BE;
3160   case ISD::SETONE:
3161   case ISD::SETNE:   return X86::COND_NE;
3162   case ISD::SETUO:   return X86::COND_P;
3163   case ISD::SETO:    return X86::COND_NP;
3164   case ISD::SETOEQ:
3165   case ISD::SETUNE:  return X86::COND_INVALID;
3166   }
3167 }
3168
3169 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3170 /// code. Current x86 isa includes the following FP cmov instructions:
3171 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3172 static bool hasFPCMov(unsigned X86CC) {
3173   switch (X86CC) {
3174   default:
3175     return false;
3176   case X86::COND_B:
3177   case X86::COND_BE:
3178   case X86::COND_E:
3179   case X86::COND_P:
3180   case X86::COND_A:
3181   case X86::COND_AE:
3182   case X86::COND_NE:
3183   case X86::COND_NP:
3184     return true;
3185   }
3186 }
3187
3188 /// isFPImmLegal - Returns true if the target can instruction select the
3189 /// specified FP immediate natively. If false, the legalizer will
3190 /// materialize the FP immediate as a load from a constant pool.
3191 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3192   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3193     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3194       return true;
3195   }
3196   return false;
3197 }
3198
3199 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3200 /// the specified range (L, H].
3201 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3202   return (Val < 0) || (Val >= Low && Val < Hi);
3203 }
3204
3205 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3206 /// specified value.
3207 static bool isUndefOrEqual(int Val, int CmpVal) {
3208   if (Val < 0 || Val == CmpVal)
3209     return true;
3210   return false;
3211 }
3212
3213 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3214 /// from position Pos and ending in Pos+Size, falls within the specified
3215 /// sequential range (L, L+Pos]. or is undef.
3216 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3217                                        unsigned Pos, unsigned Size, int Low) {
3218   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3219     if (!isUndefOrEqual(Mask[i], Low))
3220       return false;
3221   return true;
3222 }
3223
3224 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3225 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3226 /// the second operand.
3227 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3228   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3229     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3230   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3231     return (Mask[0] < 2 && Mask[1] < 2);
3232   return false;
3233 }
3234
3235 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3236 /// is suitable for input to PSHUFHW.
3237 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3238   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3239     return false;
3240
3241   // Lower quadword copied in order or undef.
3242   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3243     return false;
3244
3245   // Upper quadword shuffled.
3246   for (unsigned i = 4; i != 8; ++i)
3247     if (!isUndefOrInRange(Mask[i], 4, 8))
3248       return false;
3249
3250   if (VT == MVT::v16i16) {
3251     // Lower quadword copied in order or undef.
3252     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3253       return false;
3254
3255     // Upper quadword shuffled.
3256     for (unsigned i = 12; i != 16; ++i)
3257       if (!isUndefOrInRange(Mask[i], 12, 16))
3258         return false;
3259   }
3260
3261   return true;
3262 }
3263
3264 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3265 /// is suitable for input to PSHUFLW.
3266 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3267   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3268     return false;
3269
3270   // Upper quadword copied in order.
3271   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3272     return false;
3273
3274   // Lower quadword shuffled.
3275   for (unsigned i = 0; i != 4; ++i)
3276     if (!isUndefOrInRange(Mask[i], 0, 4))
3277       return false;
3278
3279   if (VT == MVT::v16i16) {
3280     // Upper quadword copied in order.
3281     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3282       return false;
3283
3284     // Lower quadword shuffled.
3285     for (unsigned i = 8; i != 12; ++i)
3286       if (!isUndefOrInRange(Mask[i], 8, 12))
3287         return false;
3288   }
3289
3290   return true;
3291 }
3292
3293 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3294 /// is suitable for input to PALIGNR.
3295 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3296                           const X86Subtarget *Subtarget) {
3297   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3298       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3299     return false;
3300
3301   unsigned NumElts = VT.getVectorNumElements();
3302   unsigned NumLanes = VT.getSizeInBits()/128;
3303   unsigned NumLaneElts = NumElts/NumLanes;
3304
3305   // Do not handle 64-bit element shuffles with palignr.
3306   if (NumLaneElts == 2)
3307     return false;
3308
3309   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3310     unsigned i;
3311     for (i = 0; i != NumLaneElts; ++i) {
3312       if (Mask[i+l] >= 0)
3313         break;
3314     }
3315
3316     // Lane is all undef, go to next lane
3317     if (i == NumLaneElts)
3318       continue;
3319
3320     int Start = Mask[i+l];
3321
3322     // Make sure its in this lane in one of the sources
3323     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3324         !isUndefOrInRange(Start, 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(Start, Mask[i]+l))
3329       return false;
3330
3331     // Correct second source to be contiguous with first source
3332     if (Start >= (int)NumElts)
3333       Start -= NumElts - NumLaneElts;
3334
3335     // Make sure we're shifting in the right direction.
3336     if (Start <= (int)(i+l))
3337       return false;
3338
3339     Start -= i;
3340
3341     // Check the rest of the elements to see if they are consecutive.
3342     for (++i; i != NumLaneElts; ++i) {
3343       int Idx = Mask[i+l];
3344
3345       // Make sure its in this lane
3346       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3347           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3348         return false;
3349
3350       // If not lane 0, then we must match lane 0
3351       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3352         return false;
3353
3354       if (Idx >= (int)NumElts)
3355         Idx -= NumElts - NumLaneElts;
3356
3357       if (!isUndefOrEqual(Idx, Start+i))
3358         return false;
3359
3360     }
3361   }
3362
3363   return true;
3364 }
3365
3366 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3367 /// the two vector operands have swapped position.
3368 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3369                                      unsigned NumElems) {
3370   for (unsigned i = 0; i != NumElems; ++i) {
3371     int idx = Mask[i];
3372     if (idx < 0)
3373       continue;
3374     else if (idx < (int)NumElems)
3375       Mask[i] = idx + NumElems;
3376     else
3377       Mask[i] = idx - NumElems;
3378   }
3379 }
3380
3381 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3382 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3383 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3384 /// reverse of what x86 shuffles want.
3385 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3386                         bool Commuted = false) {
3387   if (!HasAVX && VT.getSizeInBits() == 256)
3388     return false;
3389
3390   unsigned NumElems = VT.getVectorNumElements();
3391   unsigned NumLanes = VT.getSizeInBits()/128;
3392   unsigned NumLaneElems = NumElems/NumLanes;
3393
3394   if (NumLaneElems != 2 && NumLaneElems != 4)
3395     return false;
3396
3397   // VSHUFPSY divides the resulting vector into 4 chunks.
3398   // The sources are also splitted into 4 chunks, and each destination
3399   // chunk must come from a different source chunk.
3400   //
3401   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3402   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3403   //
3404   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3405   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3406   //
3407   // VSHUFPDY divides the resulting vector into 4 chunks.
3408   // The sources are also splitted into 4 chunks, and each destination
3409   // chunk must come from a different source chunk.
3410   //
3411   //  SRC1 =>      X3       X2       X1       X0
3412   //  SRC2 =>      Y3       Y2       Y1       Y0
3413   //
3414   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3415   //
3416   unsigned HalfLaneElems = NumLaneElems/2;
3417   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3418     for (unsigned i = 0; i != NumLaneElems; ++i) {
3419       int Idx = Mask[i+l];
3420       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3421       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3422         return false;
3423       // For VSHUFPSY, the mask of the second half must be the same as the
3424       // first but with the appropriate offsets. This works in the same way as
3425       // VPERMILPS works with masks.
3426       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3427         continue;
3428       if (!isUndefOrEqual(Idx, Mask[i]+l))
3429         return false;
3430     }
3431   }
3432
3433   return true;
3434 }
3435
3436 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3437 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3438 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3439   if (!VT.is128BitVector())
3440     return false;
3441
3442   unsigned NumElems = VT.getVectorNumElements();
3443
3444   if (NumElems != 4)
3445     return false;
3446
3447   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3448   return isUndefOrEqual(Mask[0], 6) &&
3449          isUndefOrEqual(Mask[1], 7) &&
3450          isUndefOrEqual(Mask[2], 2) &&
3451          isUndefOrEqual(Mask[3], 3);
3452 }
3453
3454 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3455 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3456 /// <2, 3, 2, 3>
3457 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3458   if (!VT.is128BitVector())
3459     return false;
3460
3461   unsigned NumElems = VT.getVectorNumElements();
3462
3463   if (NumElems != 4)
3464     return false;
3465
3466   return isUndefOrEqual(Mask[0], 2) &&
3467          isUndefOrEqual(Mask[1], 3) &&
3468          isUndefOrEqual(Mask[2], 2) &&
3469          isUndefOrEqual(Mask[3], 3);
3470 }
3471
3472 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3473 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3474 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3475   if (!VT.is128BitVector())
3476     return false;
3477
3478   unsigned NumElems = VT.getVectorNumElements();
3479
3480   if (NumElems != 2 && NumElems != 4)
3481     return false;
3482
3483   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3484     if (!isUndefOrEqual(Mask[i], i + NumElems))
3485       return false;
3486
3487   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3488     if (!isUndefOrEqual(Mask[i], i))
3489       return false;
3490
3491   return true;
3492 }
3493
3494 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3495 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3496 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3497   if (!VT.is128BitVector())
3498     return false;
3499
3500   unsigned NumElems = VT.getVectorNumElements();
3501
3502   if (NumElems != 2 && NumElems != 4)
3503     return false;
3504
3505   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3506     if (!isUndefOrEqual(Mask[i], i))
3507       return false;
3508
3509   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3510     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3511       return false;
3512
3513   return true;
3514 }
3515
3516 //
3517 // Some special combinations that can be optimized.
3518 //
3519 static
3520 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3521                                SelectionDAG &DAG) {
3522   EVT VT = SVOp->getValueType(0);
3523   DebugLoc dl = SVOp->getDebugLoc();
3524
3525   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3526     return SDValue();
3527
3528   ArrayRef<int> Mask = SVOp->getMask();
3529
3530   // These are the special masks that may be optimized.
3531   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3532   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3533   bool MatchEvenMask = true;
3534   bool MatchOddMask  = true;
3535   for (int i=0; i<8; ++i) {
3536     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3537       MatchEvenMask = false;
3538     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3539       MatchOddMask = false;
3540   }
3541
3542   if (!MatchEvenMask && !MatchOddMask)
3543     return SDValue();
3544   
3545   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3546
3547   SDValue Op0 = SVOp->getOperand(0);
3548   SDValue Op1 = SVOp->getOperand(1);
3549
3550   if (MatchEvenMask) {
3551     // Shift the second operand right to 32 bits.
3552     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3553     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3554   } else {
3555     // Shift the first operand left to 32 bits.
3556     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3557     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3558   }
3559   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3560   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3561 }
3562
3563 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3564 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3565 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3566                          bool HasAVX2, bool V2IsSplat = false) {
3567   unsigned NumElts = VT.getVectorNumElements();
3568
3569   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3570          "Unsupported vector type for unpckh");
3571
3572   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3573       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3574     return false;
3575
3576   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3577   // independently on 128-bit lanes.
3578   unsigned NumLanes = VT.getSizeInBits()/128;
3579   unsigned NumLaneElts = NumElts/NumLanes;
3580
3581   for (unsigned l = 0; l != NumLanes; ++l) {
3582     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3583          i != (l+1)*NumLaneElts;
3584          i += 2, ++j) {
3585       int BitI  = Mask[i];
3586       int BitI1 = Mask[i+1];
3587       if (!isUndefOrEqual(BitI, j))
3588         return false;
3589       if (V2IsSplat) {
3590         if (!isUndefOrEqual(BitI1, NumElts))
3591           return false;
3592       } else {
3593         if (!isUndefOrEqual(BitI1, j + NumElts))
3594           return false;
3595       }
3596     }
3597   }
3598
3599   return true;
3600 }
3601
3602 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3603 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3604 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3605                          bool HasAVX2, bool V2IsSplat = false) {
3606   unsigned NumElts = VT.getVectorNumElements();
3607
3608   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3609          "Unsupported vector type for unpckh");
3610
3611   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3612       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3613     return false;
3614
3615   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3616   // independently on 128-bit lanes.
3617   unsigned NumLanes = VT.getSizeInBits()/128;
3618   unsigned NumLaneElts = NumElts/NumLanes;
3619
3620   for (unsigned l = 0; l != NumLanes; ++l) {
3621     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3622          i != (l+1)*NumLaneElts; i += 2, ++j) {
3623       int BitI  = Mask[i];
3624       int BitI1 = Mask[i+1];
3625       if (!isUndefOrEqual(BitI, j))
3626         return false;
3627       if (V2IsSplat) {
3628         if (isUndefOrEqual(BitI1, NumElts))
3629           return false;
3630       } else {
3631         if (!isUndefOrEqual(BitI1, j+NumElts))
3632           return false;
3633       }
3634     }
3635   }
3636   return true;
3637 }
3638
3639 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3640 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3641 /// <0, 0, 1, 1>
3642 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3643                                   bool HasAVX2) {
3644   unsigned NumElts = VT.getVectorNumElements();
3645
3646   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3647          "Unsupported vector type for unpckh");
3648
3649   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3650       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3651     return false;
3652
3653   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3654   // FIXME: Need a better way to get rid of this, there's no latency difference
3655   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3656   // the former later. We should also remove the "_undef" special mask.
3657   if (NumElts == 4 && VT.getSizeInBits() == 256)
3658     return false;
3659
3660   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3661   // independently on 128-bit lanes.
3662   unsigned NumLanes = VT.getSizeInBits()/128;
3663   unsigned NumLaneElts = NumElts/NumLanes;
3664
3665   for (unsigned l = 0; l != NumLanes; ++l) {
3666     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3667          i != (l+1)*NumLaneElts;
3668          i += 2, ++j) {
3669       int BitI  = Mask[i];
3670       int BitI1 = Mask[i+1];
3671
3672       if (!isUndefOrEqual(BitI, j))
3673         return false;
3674       if (!isUndefOrEqual(BitI1, j))
3675         return false;
3676     }
3677   }
3678
3679   return true;
3680 }
3681
3682 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3683 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3684 /// <2, 2, 3, 3>
3685 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3686   unsigned NumElts = VT.getVectorNumElements();
3687
3688   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3689          "Unsupported vector type for unpckh");
3690
3691   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3692       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3693     return false;
3694
3695   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3696   // independently on 128-bit lanes.
3697   unsigned NumLanes = VT.getSizeInBits()/128;
3698   unsigned NumLaneElts = NumElts/NumLanes;
3699
3700   for (unsigned l = 0; l != NumLanes; ++l) {
3701     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3702          i != (l+1)*NumLaneElts; i += 2, ++j) {
3703       int BitI  = Mask[i];
3704       int BitI1 = Mask[i+1];
3705       if (!isUndefOrEqual(BitI, j))
3706         return false;
3707       if (!isUndefOrEqual(BitI1, j))
3708         return false;
3709     }
3710   }
3711   return true;
3712 }
3713
3714 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3715 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3716 /// MOVSD, and MOVD, i.e. setting the lowest element.
3717 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3718   if (VT.getVectorElementType().getSizeInBits() < 32)
3719     return false;
3720   if (!VT.is128BitVector())
3721     return false;
3722
3723   unsigned NumElts = VT.getVectorNumElements();
3724
3725   if (!isUndefOrEqual(Mask[0], NumElts))
3726     return false;
3727
3728   for (unsigned i = 1; i != NumElts; ++i)
3729     if (!isUndefOrEqual(Mask[i], i))
3730       return false;
3731
3732   return true;
3733 }
3734
3735 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3736 /// as permutations between 128-bit chunks or halves. As an example: this
3737 /// shuffle bellow:
3738 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3739 /// The first half comes from the second half of V1 and the second half from the
3740 /// the second half of V2.
3741 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3742   if (!HasAVX || !VT.is256BitVector())
3743     return false;
3744
3745   // The shuffle result is divided into half A and half B. In total the two
3746   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3747   // B must come from C, D, E or F.
3748   unsigned HalfSize = VT.getVectorNumElements()/2;
3749   bool MatchA = false, MatchB = false;
3750
3751   // Check if A comes from one of C, D, E, F.
3752   for (unsigned Half = 0; Half != 4; ++Half) {
3753     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3754       MatchA = true;
3755       break;
3756     }
3757   }
3758
3759   // Check if B comes from one of C, D, E, F.
3760   for (unsigned Half = 0; Half != 4; ++Half) {
3761     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3762       MatchB = true;
3763       break;
3764     }
3765   }
3766
3767   return MatchA && MatchB;
3768 }
3769
3770 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3771 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3772 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3773   EVT VT = SVOp->getValueType(0);
3774
3775   unsigned HalfSize = VT.getVectorNumElements()/2;
3776
3777   unsigned FstHalf = 0, SndHalf = 0;
3778   for (unsigned i = 0; i < HalfSize; ++i) {
3779     if (SVOp->getMaskElt(i) > 0) {
3780       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3781       break;
3782     }
3783   }
3784   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3785     if (SVOp->getMaskElt(i) > 0) {
3786       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3787       break;
3788     }
3789   }
3790
3791   return (FstHalf | (SndHalf << 4));
3792 }
3793
3794 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3795 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3796 /// Note that VPERMIL mask matching is different depending whether theunderlying
3797 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3798 /// to the same elements of the low, but to the higher half of the source.
3799 /// In VPERMILPD the two lanes could be shuffled independently of each other
3800 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3801 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3802   if (!HasAVX)
3803     return false;
3804
3805   unsigned NumElts = VT.getVectorNumElements();
3806   // Only match 256-bit with 32/64-bit types
3807   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3808     return false;
3809
3810   unsigned NumLanes = VT.getSizeInBits()/128;
3811   unsigned LaneSize = NumElts/NumLanes;
3812   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3813     for (unsigned i = 0; i != LaneSize; ++i) {
3814       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3815         return false;
3816       if (NumElts != 8 || l == 0)
3817         continue;
3818       // VPERMILPS handling
3819       if (Mask[i] < 0)
3820         continue;
3821       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3822         return false;
3823     }
3824   }
3825
3826   return true;
3827 }
3828
3829 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3830 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3831 /// element of vector 2 and the other elements to come from vector 1 in order.
3832 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3833                                bool V2IsSplat = false, bool V2IsUndef = false) {
3834   if (!VT.is128BitVector())
3835     return false;
3836
3837   unsigned NumOps = VT.getVectorNumElements();
3838   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3839     return false;
3840
3841   if (!isUndefOrEqual(Mask[0], 0))
3842     return false;
3843
3844   for (unsigned i = 1; i != NumOps; ++i)
3845     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3846           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3847           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3848       return false;
3849
3850   return true;
3851 }
3852
3853 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3854 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3855 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3856 static bool isMOVSHDUPMask(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+1" is the value the indexed mask element must have
3868   for (unsigned i = 0; i != NumElems; i += 2)
3869     if (!isUndefOrEqual(Mask[i], i+1) ||
3870         !isUndefOrEqual(Mask[i+1], i+1))
3871       return false;
3872
3873   return true;
3874 }
3875
3876 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3877 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3878 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3879 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3880                            const X86Subtarget *Subtarget) {
3881   if (!Subtarget->hasSSE3())
3882     return false;
3883
3884   unsigned NumElems = VT.getVectorNumElements();
3885
3886   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3887       (VT.getSizeInBits() == 256 && NumElems != 8))
3888     return false;
3889
3890   // "i" is the value the indexed mask element must have
3891   for (unsigned i = 0; i != NumElems; i += 2)
3892     if (!isUndefOrEqual(Mask[i], i) ||
3893         !isUndefOrEqual(Mask[i+1], i))
3894       return false;
3895
3896   return true;
3897 }
3898
3899 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3900 /// specifies a shuffle of elements that is suitable for input to 256-bit
3901 /// version of MOVDDUP.
3902 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3903   if (!HasAVX || !VT.is256BitVector())
3904     return false;
3905
3906   unsigned NumElts = VT.getVectorNumElements();
3907   if (NumElts != 4)
3908     return false;
3909
3910   for (unsigned i = 0; i != NumElts/2; ++i)
3911     if (!isUndefOrEqual(Mask[i], 0))
3912       return false;
3913   for (unsigned i = NumElts/2; i != NumElts; ++i)
3914     if (!isUndefOrEqual(Mask[i], NumElts/2))
3915       return false;
3916   return true;
3917 }
3918
3919 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3920 /// specifies a shuffle of elements that is suitable for input to 128-bit
3921 /// version of MOVDDUP.
3922 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3923   if (!VT.is128BitVector())
3924     return false;
3925
3926   unsigned e = VT.getVectorNumElements() / 2;
3927   for (unsigned i = 0; i != e; ++i)
3928     if (!isUndefOrEqual(Mask[i], i))
3929       return false;
3930   for (unsigned i = 0; i != e; ++i)
3931     if (!isUndefOrEqual(Mask[e+i], i))
3932       return false;
3933   return true;
3934 }
3935
3936 /// isVEXTRACTF128Index - Return true if the specified
3937 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3938 /// suitable for input to VEXTRACTF128.
3939 bool X86::isVEXTRACTF128Index(SDNode *N) {
3940   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3941     return false;
3942
3943   // The index should be aligned on a 128-bit boundary.
3944   uint64_t Index =
3945     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3946
3947   unsigned VL = N->getValueType(0).getVectorNumElements();
3948   unsigned VBits = N->getValueType(0).getSizeInBits();
3949   unsigned ElSize = VBits / VL;
3950   bool Result = (Index * ElSize) % 128 == 0;
3951
3952   return Result;
3953 }
3954
3955 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3956 /// operand specifies a subvector insert that is suitable for input to
3957 /// VINSERTF128.
3958 bool X86::isVINSERTF128Index(SDNode *N) {
3959   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3960     return false;
3961
3962   // The index should be aligned on a 128-bit boundary.
3963   uint64_t Index =
3964     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3965
3966   unsigned VL = N->getValueType(0).getVectorNumElements();
3967   unsigned VBits = N->getValueType(0).getSizeInBits();
3968   unsigned ElSize = VBits / VL;
3969   bool Result = (Index * ElSize) % 128 == 0;
3970
3971   return Result;
3972 }
3973
3974 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3975 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3976 /// Handles 128-bit and 256-bit.
3977 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3978   EVT VT = N->getValueType(0);
3979
3980   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3981          "Unsupported vector type for PSHUF/SHUFP");
3982
3983   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3984   // independently on 128-bit lanes.
3985   unsigned NumElts = VT.getVectorNumElements();
3986   unsigned NumLanes = VT.getSizeInBits()/128;
3987   unsigned NumLaneElts = NumElts/NumLanes;
3988
3989   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3990          "Only supports 2 or 4 elements per lane");
3991
3992   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3993   unsigned Mask = 0;
3994   for (unsigned i = 0; i != NumElts; ++i) {
3995     int Elt = N->getMaskElt(i);
3996     if (Elt < 0) continue;
3997     Elt &= NumLaneElts - 1;
3998     unsigned ShAmt = (i << Shift) % 8;
3999     Mask |= Elt << ShAmt;
4000   }
4001
4002   return Mask;
4003 }
4004
4005 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4006 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4007 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4008   EVT VT = N->getValueType(0);
4009
4010   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4011          "Unsupported vector type for PSHUFHW");
4012
4013   unsigned NumElts = VT.getVectorNumElements();
4014
4015   unsigned Mask = 0;
4016   for (unsigned l = 0; l != NumElts; l += 8) {
4017     // 8 nodes per lane, but we only care about the last 4.
4018     for (unsigned i = 0; i < 4; ++i) {
4019       int Elt = N->getMaskElt(l+i+4);
4020       if (Elt < 0) continue;
4021       Elt &= 0x3; // only 2-bits.
4022       Mask |= Elt << (i * 2);
4023     }
4024   }
4025
4026   return Mask;
4027 }
4028
4029 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4030 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4031 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4032   EVT VT = N->getValueType(0);
4033
4034   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4035          "Unsupported vector type for PSHUFHW");
4036
4037   unsigned NumElts = VT.getVectorNumElements();
4038
4039   unsigned Mask = 0;
4040   for (unsigned l = 0; l != NumElts; l += 8) {
4041     // 8 nodes per lane, but we only care about the first 4.
4042     for (unsigned i = 0; i < 4; ++i) {
4043       int Elt = N->getMaskElt(l+i);
4044       if (Elt < 0) continue;
4045       Elt &= 0x3; // only 2-bits
4046       Mask |= Elt << (i * 2);
4047     }
4048   }
4049
4050   return Mask;
4051 }
4052
4053 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4054 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4055 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4056   EVT VT = SVOp->getValueType(0);
4057   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4058
4059   unsigned NumElts = VT.getVectorNumElements();
4060   unsigned NumLanes = VT.getSizeInBits()/128;
4061   unsigned NumLaneElts = NumElts/NumLanes;
4062
4063   int Val = 0;
4064   unsigned i;
4065   for (i = 0; i != NumElts; ++i) {
4066     Val = SVOp->getMaskElt(i);
4067     if (Val >= 0)
4068       break;
4069   }
4070   if (Val >= (int)NumElts)
4071     Val -= NumElts - NumLaneElts;
4072
4073   assert(Val - i > 0 && "PALIGNR imm should be positive");
4074   return (Val - i) * EltSize;
4075 }
4076
4077 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4078 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4079 /// instructions.
4080 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4081   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4082     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4083
4084   uint64_t Index =
4085     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4086
4087   EVT VecVT = N->getOperand(0).getValueType();
4088   EVT ElVT = VecVT.getVectorElementType();
4089
4090   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4091   return Index / NumElemsPerChunk;
4092 }
4093
4094 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4095 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4096 /// instructions.
4097 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4098   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4099     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4100
4101   uint64_t Index =
4102     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4103
4104   EVT VecVT = N->getValueType(0);
4105   EVT ElVT = VecVT.getVectorElementType();
4106
4107   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4108   return Index / NumElemsPerChunk;
4109 }
4110
4111 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4112 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4113 /// Handles 256-bit.
4114 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4115   EVT VT = N->getValueType(0);
4116
4117   unsigned NumElts = VT.getVectorNumElements();
4118
4119   assert((VT.is256BitVector() && NumElts == 4) &&
4120          "Unsupported vector type for VPERMQ/VPERMPD");
4121
4122   unsigned Mask = 0;
4123   for (unsigned i = 0; i != NumElts; ++i) {
4124     int Elt = N->getMaskElt(i);
4125     if (Elt < 0)
4126       continue;
4127     Mask |= Elt << (i*2);
4128   }
4129
4130   return Mask;
4131 }
4132 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4133 /// constant +0.0.
4134 bool X86::isZeroNode(SDValue Elt) {
4135   return ((isa<ConstantSDNode>(Elt) &&
4136            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4137           (isa<ConstantFPSDNode>(Elt) &&
4138            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4139 }
4140
4141 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4142 /// their permute mask.
4143 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4144                                     SelectionDAG &DAG) {
4145   EVT VT = SVOp->getValueType(0);
4146   unsigned NumElems = VT.getVectorNumElements();
4147   SmallVector<int, 8> MaskVec;
4148
4149   for (unsigned i = 0; i != NumElems; ++i) {
4150     int Idx = SVOp->getMaskElt(i);
4151     if (Idx >= 0) {
4152       if (Idx < (int)NumElems)
4153         Idx += NumElems;
4154       else
4155         Idx -= NumElems;
4156     }
4157     MaskVec.push_back(Idx);
4158   }
4159   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4160                               SVOp->getOperand(0), &MaskVec[0]);
4161 }
4162
4163 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4164 /// match movhlps. The lower half elements should come from upper half of
4165 /// V1 (and in order), and the upper half elements should come from the upper
4166 /// half of V2 (and in order).
4167 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4168   if (!VT.is128BitVector())
4169     return false;
4170   if (VT.getVectorNumElements() != 4)
4171     return false;
4172   for (unsigned i = 0, e = 2; i != e; ++i)
4173     if (!isUndefOrEqual(Mask[i], i+2))
4174       return false;
4175   for (unsigned i = 2; i != 4; ++i)
4176     if (!isUndefOrEqual(Mask[i], i+4))
4177       return false;
4178   return true;
4179 }
4180
4181 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4182 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4183 /// required.
4184 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4185   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4186     return false;
4187   N = N->getOperand(0).getNode();
4188   if (!ISD::isNON_EXTLoad(N))
4189     return false;
4190   if (LD)
4191     *LD = cast<LoadSDNode>(N);
4192   return true;
4193 }
4194
4195 // Test whether the given value is a vector value which will be legalized
4196 // into a load.
4197 static bool WillBeConstantPoolLoad(SDNode *N) {
4198   if (N->getOpcode() != ISD::BUILD_VECTOR)
4199     return false;
4200
4201   // Check for any non-constant elements.
4202   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4203     switch (N->getOperand(i).getNode()->getOpcode()) {
4204     case ISD::UNDEF:
4205     case ISD::ConstantFP:
4206     case ISD::Constant:
4207       break;
4208     default:
4209       return false;
4210     }
4211
4212   // Vectors of all-zeros and all-ones are materialized with special
4213   // instructions rather than being loaded.
4214   return !ISD::isBuildVectorAllZeros(N) &&
4215          !ISD::isBuildVectorAllOnes(N);
4216 }
4217
4218 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4219 /// match movlp{s|d}. The lower half elements should come from lower half of
4220 /// V1 (and in order), and the upper half elements should come from the upper
4221 /// half of V2 (and in order). And since V1 will become the source of the
4222 /// MOVLP, it must be either a vector load or a scalar load to vector.
4223 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4224                                ArrayRef<int> Mask, EVT VT) {
4225   if (!VT.is128BitVector())
4226     return false;
4227
4228   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4229     return false;
4230   // Is V2 is a vector load, don't do this transformation. We will try to use
4231   // load folding shufps op.
4232   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4233     return false;
4234
4235   unsigned NumElems = VT.getVectorNumElements();
4236
4237   if (NumElems != 2 && NumElems != 4)
4238     return false;
4239   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4240     if (!isUndefOrEqual(Mask[i], i))
4241       return false;
4242   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4243     if (!isUndefOrEqual(Mask[i], i+NumElems))
4244       return false;
4245   return true;
4246 }
4247
4248 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4249 /// all the same.
4250 static bool isSplatVector(SDNode *N) {
4251   if (N->getOpcode() != ISD::BUILD_VECTOR)
4252     return false;
4253
4254   SDValue SplatValue = N->getOperand(0);
4255   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4256     if (N->getOperand(i) != SplatValue)
4257       return false;
4258   return true;
4259 }
4260
4261 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4262 /// to an zero vector.
4263 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4264 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4265   SDValue V1 = N->getOperand(0);
4266   SDValue V2 = N->getOperand(1);
4267   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4268   for (unsigned i = 0; i != NumElems; ++i) {
4269     int Idx = N->getMaskElt(i);
4270     if (Idx >= (int)NumElems) {
4271       unsigned Opc = V2.getOpcode();
4272       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4273         continue;
4274       if (Opc != ISD::BUILD_VECTOR ||
4275           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4276         return false;
4277     } else if (Idx >= 0) {
4278       unsigned Opc = V1.getOpcode();
4279       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4280         continue;
4281       if (Opc != ISD::BUILD_VECTOR ||
4282           !X86::isZeroNode(V1.getOperand(Idx)))
4283         return false;
4284     }
4285   }
4286   return true;
4287 }
4288
4289 /// getZeroVector - Returns a vector of specified type with all zero elements.
4290 ///
4291 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4292                              SelectionDAG &DAG, DebugLoc dl) {
4293   assert(VT.isVector() && "Expected a vector type");
4294   unsigned Size = VT.getSizeInBits();
4295
4296   // Always build SSE zero vectors as <4 x i32> bitcasted
4297   // to their dest type. This ensures they get CSE'd.
4298   SDValue Vec;
4299   if (Size == 128) {  // SSE
4300     if (Subtarget->hasSSE2()) {  // SSE2
4301       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4302       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4303     } else { // SSE1
4304       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4305       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4306     }
4307   } else if (Size == 256) { // AVX
4308     if (Subtarget->hasAVX2()) { // AVX2
4309       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4310       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4311       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4312     } else {
4313       // 256-bit logic and arithmetic instructions in AVX are all
4314       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4315       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4316       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4317       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4318     }
4319   } else
4320     llvm_unreachable("Unexpected vector type");
4321
4322   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4323 }
4324
4325 /// getOnesVector - Returns a vector of specified type with all bits set.
4326 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4327 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4328 /// Then bitcast to their original type, ensuring they get CSE'd.
4329 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4330                              DebugLoc dl) {
4331   assert(VT.isVector() && "Expected a vector type");
4332   unsigned Size = VT.getSizeInBits();
4333
4334   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4335   SDValue Vec;
4336   if (Size == 256) {
4337     if (HasAVX2) { // AVX2
4338       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4339       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4340     } else { // AVX
4341       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4342       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4343     }
4344   } else if (Size == 128) {
4345     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4346   } else
4347     llvm_unreachable("Unexpected vector type");
4348
4349   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4350 }
4351
4352 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4353 /// that point to V2 points to its first element.
4354 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4355   for (unsigned i = 0; i != NumElems; ++i) {
4356     if (Mask[i] > (int)NumElems) {
4357       Mask[i] = NumElems;
4358     }
4359   }
4360 }
4361
4362 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4363 /// operation of specified width.
4364 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4365                        SDValue V2) {
4366   unsigned NumElems = VT.getVectorNumElements();
4367   SmallVector<int, 8> Mask;
4368   Mask.push_back(NumElems);
4369   for (unsigned i = 1; i != NumElems; ++i)
4370     Mask.push_back(i);
4371   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4372 }
4373
4374 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4375 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4376                           SDValue V2) {
4377   unsigned NumElems = VT.getVectorNumElements();
4378   SmallVector<int, 8> Mask;
4379   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4380     Mask.push_back(i);
4381     Mask.push_back(i + NumElems);
4382   }
4383   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4384 }
4385
4386 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4387 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4388                           SDValue V2) {
4389   unsigned NumElems = VT.getVectorNumElements();
4390   SmallVector<int, 8> Mask;
4391   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4392     Mask.push_back(i + Half);
4393     Mask.push_back(i + NumElems + Half);
4394   }
4395   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4396 }
4397
4398 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4399 // a generic shuffle instruction because the target has no such instructions.
4400 // Generate shuffles which repeat i16 and i8 several times until they can be
4401 // represented by v4f32 and then be manipulated by target suported shuffles.
4402 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4403   EVT VT = V.getValueType();
4404   int NumElems = VT.getVectorNumElements();
4405   DebugLoc dl = V.getDebugLoc();
4406
4407   while (NumElems > 4) {
4408     if (EltNo < NumElems/2) {
4409       V = getUnpackl(DAG, dl, VT, V, V);
4410     } else {
4411       V = getUnpackh(DAG, dl, VT, V, V);
4412       EltNo -= NumElems/2;
4413     }
4414     NumElems >>= 1;
4415   }
4416   return V;
4417 }
4418
4419 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4420 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4421   EVT VT = V.getValueType();
4422   DebugLoc dl = V.getDebugLoc();
4423   unsigned Size = VT.getSizeInBits();
4424
4425   if (Size == 128) {
4426     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4427     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4428     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4429                              &SplatMask[0]);
4430   } else if (Size == 256) {
4431     // To use VPERMILPS to splat scalars, the second half of indicies must
4432     // refer to the higher part, which is a duplication of the lower one,
4433     // because VPERMILPS can only handle in-lane permutations.
4434     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4435                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4436
4437     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4438     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4439                              &SplatMask[0]);
4440   } else
4441     llvm_unreachable("Vector size not supported");
4442
4443   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4444 }
4445
4446 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4447 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4448   EVT SrcVT = SV->getValueType(0);
4449   SDValue V1 = SV->getOperand(0);
4450   DebugLoc dl = SV->getDebugLoc();
4451
4452   int EltNo = SV->getSplatIndex();
4453   int NumElems = SrcVT.getVectorNumElements();
4454   unsigned Size = SrcVT.getSizeInBits();
4455
4456   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4457           "Unknown how to promote splat for type");
4458
4459   // Extract the 128-bit part containing the splat element and update
4460   // the splat element index when it refers to the higher register.
4461   if (Size == 256) {
4462     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4463     if (EltNo >= NumElems/2)
4464       EltNo -= NumElems/2;
4465   }
4466
4467   // All i16 and i8 vector types can't be used directly by a generic shuffle
4468   // instruction because the target has no such instruction. Generate shuffles
4469   // which repeat i16 and i8 several times until they fit in i32, and then can
4470   // be manipulated by target suported shuffles.
4471   EVT EltVT = SrcVT.getVectorElementType();
4472   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4473     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4474
4475   // Recreate the 256-bit vector and place the same 128-bit vector
4476   // into the low and high part. This is necessary because we want
4477   // to use VPERM* to shuffle the vectors
4478   if (Size == 256) {
4479     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4480   }
4481
4482   return getLegalSplat(DAG, V1, EltNo);
4483 }
4484
4485 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4486 /// vector of zero or undef vector.  This produces a shuffle where the low
4487 /// element of V2 is swizzled into the zero/undef vector, landing at element
4488 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4489 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4490                                            bool IsZero,
4491                                            const X86Subtarget *Subtarget,
4492                                            SelectionDAG &DAG) {
4493   EVT VT = V2.getValueType();
4494   SDValue V1 = IsZero
4495     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4496   unsigned NumElems = VT.getVectorNumElements();
4497   SmallVector<int, 16> MaskVec;
4498   for (unsigned i = 0; i != NumElems; ++i)
4499     // If this is the insertion idx, put the low elt of V2 here.
4500     MaskVec.push_back(i == Idx ? NumElems : i);
4501   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4502 }
4503
4504 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4505 /// target specific opcode. Returns true if the Mask could be calculated.
4506 /// Sets IsUnary to true if only uses one source.
4507 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4508                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4509   unsigned NumElems = VT.getVectorNumElements();
4510   SDValue ImmN;
4511
4512   IsUnary = false;
4513   switch(N->getOpcode()) {
4514   case X86ISD::SHUFP:
4515     ImmN = N->getOperand(N->getNumOperands()-1);
4516     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4517     break;
4518   case X86ISD::UNPCKH:
4519     DecodeUNPCKHMask(VT, Mask);
4520     break;
4521   case X86ISD::UNPCKL:
4522     DecodeUNPCKLMask(VT, Mask);
4523     break;
4524   case X86ISD::MOVHLPS:
4525     DecodeMOVHLPSMask(NumElems, Mask);
4526     break;
4527   case X86ISD::MOVLHPS:
4528     DecodeMOVLHPSMask(NumElems, Mask);
4529     break;
4530   case X86ISD::PSHUFD:
4531   case X86ISD::VPERMILP:
4532     ImmN = N->getOperand(N->getNumOperands()-1);
4533     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534     IsUnary = true;
4535     break;
4536   case X86ISD::PSHUFHW:
4537     ImmN = N->getOperand(N->getNumOperands()-1);
4538     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4539     IsUnary = true;
4540     break;
4541   case X86ISD::PSHUFLW:
4542     ImmN = N->getOperand(N->getNumOperands()-1);
4543     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4544     IsUnary = true;
4545     break;
4546   case X86ISD::VPERMI:
4547     ImmN = N->getOperand(N->getNumOperands()-1);
4548     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4549     IsUnary = true;
4550     break;
4551   case X86ISD::MOVSS:
4552   case X86ISD::MOVSD: {
4553     // The index 0 always comes from the first element of the second source,
4554     // this is why MOVSS and MOVSD are used in the first place. The other
4555     // elements come from the other positions of the first source vector
4556     Mask.push_back(NumElems);
4557     for (unsigned i = 1; i != NumElems; ++i) {
4558       Mask.push_back(i);
4559     }
4560     break;
4561   }
4562   case X86ISD::VPERM2X128:
4563     ImmN = N->getOperand(N->getNumOperands()-1);
4564     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4565     if (Mask.empty()) return false;
4566     break;
4567   case X86ISD::MOVDDUP:
4568   case X86ISD::MOVLHPD:
4569   case X86ISD::MOVLPD:
4570   case X86ISD::MOVLPS:
4571   case X86ISD::MOVSHDUP:
4572   case X86ISD::MOVSLDUP:
4573   case X86ISD::PALIGN:
4574     // Not yet implemented
4575     return false;
4576   default: llvm_unreachable("unknown target shuffle node");
4577   }
4578
4579   return true;
4580 }
4581
4582 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4583 /// element of the result of the vector shuffle.
4584 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4585                                    unsigned Depth) {
4586   if (Depth == 6)
4587     return SDValue();  // Limit search depth.
4588
4589   SDValue V = SDValue(N, 0);
4590   EVT VT = V.getValueType();
4591   unsigned Opcode = V.getOpcode();
4592
4593   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4594   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4595     int Elt = SV->getMaskElt(Index);
4596
4597     if (Elt < 0)
4598       return DAG.getUNDEF(VT.getVectorElementType());
4599
4600     unsigned NumElems = VT.getVectorNumElements();
4601     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4602                                          : SV->getOperand(1);
4603     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4604   }
4605
4606   // Recurse into target specific vector shuffles to find scalars.
4607   if (isTargetShuffle(Opcode)) {
4608     MVT ShufVT = V.getValueType().getSimpleVT();
4609     unsigned NumElems = ShufVT.getVectorNumElements();
4610     SmallVector<int, 16> ShuffleMask;
4611     SDValue ImmN;
4612     bool IsUnary;
4613
4614     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4615       return SDValue();
4616
4617     int Elt = ShuffleMask[Index];
4618     if (Elt < 0)
4619       return DAG.getUNDEF(ShufVT.getVectorElementType());
4620
4621     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4622                                          : N->getOperand(1);
4623     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4624                                Depth+1);
4625   }
4626
4627   // Actual nodes that may contain scalar elements
4628   if (Opcode == ISD::BITCAST) {
4629     V = V.getOperand(0);
4630     EVT SrcVT = V.getValueType();
4631     unsigned NumElems = VT.getVectorNumElements();
4632
4633     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4634       return SDValue();
4635   }
4636
4637   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4638     return (Index == 0) ? V.getOperand(0)
4639                         : DAG.getUNDEF(VT.getVectorElementType());
4640
4641   if (V.getOpcode() == ISD::BUILD_VECTOR)
4642     return V.getOperand(Index);
4643
4644   return SDValue();
4645 }
4646
4647 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4648 /// shuffle operation which come from a consecutively from a zero. The
4649 /// search can start in two different directions, from left or right.
4650 static
4651 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4652                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4653   unsigned i;
4654   for (i = 0; i != NumElems; ++i) {
4655     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4656     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4657     if (!(Elt.getNode() &&
4658          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4659       break;
4660   }
4661
4662   return i;
4663 }
4664
4665 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4666 /// correspond consecutively to elements from one of the vector operands,
4667 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4668 static
4669 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4670                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4671                               unsigned NumElems, unsigned &OpNum) {
4672   bool SeenV1 = false;
4673   bool SeenV2 = false;
4674
4675   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4676     int Idx = SVOp->getMaskElt(i);
4677     // Ignore undef indicies
4678     if (Idx < 0)
4679       continue;
4680
4681     if (Idx < (int)NumElems)
4682       SeenV1 = true;
4683     else
4684       SeenV2 = true;
4685
4686     // Only accept consecutive elements from the same vector
4687     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4688       return false;
4689   }
4690
4691   OpNum = SeenV1 ? 0 : 1;
4692   return true;
4693 }
4694
4695 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4696 /// logical left shift of a vector.
4697 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4698                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4699   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4700   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4701               false /* check zeros from right */, DAG);
4702   unsigned OpSrc;
4703
4704   if (!NumZeros)
4705     return false;
4706
4707   // Considering the elements in the mask that are not consecutive zeros,
4708   // check if they consecutively come from only one of the source vectors.
4709   //
4710   //               V1 = {X, A, B, C}     0
4711   //                         \  \  \    /
4712   //   vector_shuffle V1, V2 <1, 2, 3, X>
4713   //
4714   if (!isShuffleMaskConsecutive(SVOp,
4715             0,                   // Mask Start Index
4716             NumElems-NumZeros,   // Mask End Index(exclusive)
4717             NumZeros,            // Where to start looking in the src vector
4718             NumElems,            // Number of elements in vector
4719             OpSrc))              // Which source operand ?
4720     return false;
4721
4722   isLeft = false;
4723   ShAmt = NumZeros;
4724   ShVal = SVOp->getOperand(OpSrc);
4725   return true;
4726 }
4727
4728 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4729 /// logical left shift of a vector.
4730 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4731                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4732   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4733   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4734               true /* check zeros from left */, DAG);
4735   unsigned OpSrc;
4736
4737   if (!NumZeros)
4738     return false;
4739
4740   // Considering the elements in the mask that are not consecutive zeros,
4741   // check if they consecutively come from only one of the source vectors.
4742   //
4743   //                           0    { A, B, X, X } = V2
4744   //                          / \    /  /
4745   //   vector_shuffle V1, V2 <X, X, 4, 5>
4746   //
4747   if (!isShuffleMaskConsecutive(SVOp,
4748             NumZeros,     // Mask Start Index
4749             NumElems,     // Mask End Index(exclusive)
4750             0,            // Where to start looking in the src vector
4751             NumElems,     // Number of elements in vector
4752             OpSrc))       // Which source operand ?
4753     return false;
4754
4755   isLeft = true;
4756   ShAmt = NumZeros;
4757   ShVal = SVOp->getOperand(OpSrc);
4758   return true;
4759 }
4760
4761 /// isVectorShift - Returns true if the shuffle can be implemented as a
4762 /// logical left or right shift of a vector.
4763 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4764                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4765   // Although the logic below support any bitwidth size, there are no
4766   // shift instructions which handle more than 128-bit vectors.
4767   if (!SVOp->getValueType(0).is128BitVector())
4768     return false;
4769
4770   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4771       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4772     return true;
4773
4774   return false;
4775 }
4776
4777 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4778 ///
4779 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4780                                        unsigned NumNonZero, unsigned NumZero,
4781                                        SelectionDAG &DAG,
4782                                        const X86Subtarget* Subtarget,
4783                                        const TargetLowering &TLI) {
4784   if (NumNonZero > 8)
4785     return SDValue();
4786
4787   DebugLoc dl = Op.getDebugLoc();
4788   SDValue V(0, 0);
4789   bool First = true;
4790   for (unsigned i = 0; i < 16; ++i) {
4791     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4792     if (ThisIsNonZero && First) {
4793       if (NumZero)
4794         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4795       else
4796         V = DAG.getUNDEF(MVT::v8i16);
4797       First = false;
4798     }
4799
4800     if ((i & 1) != 0) {
4801       SDValue ThisElt(0, 0), LastElt(0, 0);
4802       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4803       if (LastIsNonZero) {
4804         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4805                               MVT::i16, Op.getOperand(i-1));
4806       }
4807       if (ThisIsNonZero) {
4808         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4809         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4810                               ThisElt, DAG.getConstant(8, MVT::i8));
4811         if (LastIsNonZero)
4812           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4813       } else
4814         ThisElt = LastElt;
4815
4816       if (ThisElt.getNode())
4817         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4818                         DAG.getIntPtrConstant(i/2));
4819     }
4820   }
4821
4822   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4823 }
4824
4825 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4826 ///
4827 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4828                                      unsigned NumNonZero, unsigned NumZero,
4829                                      SelectionDAG &DAG,
4830                                      const X86Subtarget* Subtarget,
4831                                      const TargetLowering &TLI) {
4832   if (NumNonZero > 4)
4833     return SDValue();
4834
4835   DebugLoc dl = Op.getDebugLoc();
4836   SDValue V(0, 0);
4837   bool First = true;
4838   for (unsigned i = 0; i < 8; ++i) {
4839     bool isNonZero = (NonZeros & (1 << i)) != 0;
4840     if (isNonZero) {
4841       if (First) {
4842         if (NumZero)
4843           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4844         else
4845           V = DAG.getUNDEF(MVT::v8i16);
4846         First = false;
4847       }
4848       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4849                       MVT::v8i16, V, Op.getOperand(i),
4850                       DAG.getIntPtrConstant(i));
4851     }
4852   }
4853
4854   return V;
4855 }
4856
4857 /// getVShift - Return a vector logical shift node.
4858 ///
4859 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4860                          unsigned NumBits, SelectionDAG &DAG,
4861                          const TargetLowering &TLI, DebugLoc dl) {
4862   assert(VT.is128BitVector() && "Unknown type for VShift");
4863   EVT ShVT = MVT::v2i64;
4864   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4865   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4866   return DAG.getNode(ISD::BITCAST, dl, VT,
4867                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4868                              DAG.getConstant(NumBits,
4869                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4870 }
4871
4872 SDValue
4873 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4874                                           SelectionDAG &DAG) const {
4875
4876   // Check if the scalar load can be widened into a vector load. And if
4877   // the address is "base + cst" see if the cst can be "absorbed" into
4878   // the shuffle mask.
4879   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4880     SDValue Ptr = LD->getBasePtr();
4881     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4882       return SDValue();
4883     EVT PVT = LD->getValueType(0);
4884     if (PVT != MVT::i32 && PVT != MVT::f32)
4885       return SDValue();
4886
4887     int FI = -1;
4888     int64_t Offset = 0;
4889     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4890       FI = FINode->getIndex();
4891       Offset = 0;
4892     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4893                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4894       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4895       Offset = Ptr.getConstantOperandVal(1);
4896       Ptr = Ptr.getOperand(0);
4897     } else {
4898       return SDValue();
4899     }
4900
4901     // FIXME: 256-bit vector instructions don't require a strict alignment,
4902     // improve this code to support it better.
4903     unsigned RequiredAlign = VT.getSizeInBits()/8;
4904     SDValue Chain = LD->getChain();
4905     // Make sure the stack object alignment is at least 16 or 32.
4906     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4907     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4908       if (MFI->isFixedObjectIndex(FI)) {
4909         // Can't change the alignment. FIXME: It's possible to compute
4910         // the exact stack offset and reference FI + adjust offset instead.
4911         // If someone *really* cares about this. That's the way to implement it.
4912         return SDValue();
4913       } else {
4914         MFI->setObjectAlignment(FI, RequiredAlign);
4915       }
4916     }
4917
4918     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4919     // Ptr + (Offset & ~15).
4920     if (Offset < 0)
4921       return SDValue();
4922     if ((Offset % RequiredAlign) & 3)
4923       return SDValue();
4924     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4925     if (StartOffset)
4926       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4927                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4928
4929     int EltNo = (Offset - StartOffset) >> 2;
4930     unsigned NumElems = VT.getVectorNumElements();
4931
4932     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4933     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4934                              LD->getPointerInfo().getWithOffset(StartOffset),
4935                              false, false, false, 0);
4936
4937     SmallVector<int, 8> Mask;
4938     for (unsigned i = 0; i != NumElems; ++i)
4939       Mask.push_back(EltNo);
4940
4941     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4942   }
4943
4944   return SDValue();
4945 }
4946
4947 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4948 /// vector of type 'VT', see if the elements can be replaced by a single large
4949 /// load which has the same value as a build_vector whose operands are 'elts'.
4950 ///
4951 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4952 ///
4953 /// FIXME: we'd also like to handle the case where the last elements are zero
4954 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4955 /// There's even a handy isZeroNode for that purpose.
4956 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4957                                         DebugLoc &DL, SelectionDAG &DAG) {
4958   EVT EltVT = VT.getVectorElementType();
4959   unsigned NumElems = Elts.size();
4960
4961   LoadSDNode *LDBase = NULL;
4962   unsigned LastLoadedElt = -1U;
4963
4964   // For each element in the initializer, see if we've found a load or an undef.
4965   // If we don't find an initial load element, or later load elements are
4966   // non-consecutive, bail out.
4967   for (unsigned i = 0; i < NumElems; ++i) {
4968     SDValue Elt = Elts[i];
4969
4970     if (!Elt.getNode() ||
4971         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4972       return SDValue();
4973     if (!LDBase) {
4974       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4975         return SDValue();
4976       LDBase = cast<LoadSDNode>(Elt.getNode());
4977       LastLoadedElt = i;
4978       continue;
4979     }
4980     if (Elt.getOpcode() == ISD::UNDEF)
4981       continue;
4982
4983     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4984     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4985       return SDValue();
4986     LastLoadedElt = i;
4987   }
4988
4989   // If we have found an entire vector of loads and undefs, then return a large
4990   // load of the entire vector width starting at the base pointer.  If we found
4991   // consecutive loads for the low half, generate a vzext_load node.
4992   if (LastLoadedElt == NumElems - 1) {
4993     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4994       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4995                          LDBase->getPointerInfo(),
4996                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4997                          LDBase->isInvariant(), 0);
4998     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4999                        LDBase->getPointerInfo(),
5000                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5001                        LDBase->isInvariant(), LDBase->getAlignment());
5002   }
5003   if (NumElems == 4 && LastLoadedElt == 1 &&
5004       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5005     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5006     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5007     SDValue ResNode =
5008         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5009                                 LDBase->getPointerInfo(),
5010                                 LDBase->getAlignment(),
5011                                 false/*isVolatile*/, true/*ReadMem*/,
5012                                 false/*WriteMem*/);
5013
5014     // Make sure the newly-created LOAD is in the same position as LDBase in
5015     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5016     // update uses of LDBase's output chain to use the TokenFactor.
5017     if (LDBase->hasAnyUseOfValue(1)) {
5018       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5019                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5020       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5021       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5022                              SDValue(ResNode.getNode(), 1));
5023     }
5024
5025     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5026   }
5027   return SDValue();
5028 }
5029
5030 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5031 /// to generate a splat value for the following cases:
5032 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5033 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5034 /// a scalar load, or a constant.
5035 /// The VBROADCAST node is returned when a pattern is found,
5036 /// or SDValue() otherwise.
5037 SDValue
5038 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5039   if (!Subtarget->hasAVX())
5040     return SDValue();
5041
5042   EVT VT = Op.getValueType();
5043   DebugLoc dl = Op.getDebugLoc();
5044
5045   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5046          "Unsupported vector type for broadcast.");
5047
5048   SDValue Ld;
5049   bool ConstSplatVal;
5050
5051   switch (Op.getOpcode()) {
5052     default:
5053       // Unknown pattern found.
5054       return SDValue();
5055
5056     case ISD::BUILD_VECTOR: {
5057       // The BUILD_VECTOR node must be a splat.
5058       if (!isSplatVector(Op.getNode()))
5059         return SDValue();
5060
5061       Ld = Op.getOperand(0);
5062       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5063                      Ld.getOpcode() == ISD::ConstantFP);
5064
5065       // The suspected load node has several users. Make sure that all
5066       // of its users are from the BUILD_VECTOR node.
5067       // Constants may have multiple users.
5068       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5069         return SDValue();
5070       break;
5071     }
5072
5073     case ISD::VECTOR_SHUFFLE: {
5074       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5075
5076       // Shuffles must have a splat mask where the first element is
5077       // broadcasted.
5078       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5079         return SDValue();
5080
5081       SDValue Sc = Op.getOperand(0);
5082       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5083           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5084
5085         if (!Subtarget->hasAVX2())
5086           return SDValue();
5087
5088         // Use the register form of the broadcast instruction available on AVX2.
5089         if (VT.is256BitVector())
5090           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5091         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5092       }
5093
5094       Ld = Sc.getOperand(0);
5095       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5096                        Ld.getOpcode() == ISD::ConstantFP);
5097
5098       // The scalar_to_vector node and the suspected
5099       // load node must have exactly one user.
5100       // Constants may have multiple users.
5101       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5102         return SDValue();
5103       break;
5104     }
5105   }
5106
5107   bool Is256 = VT.is256BitVector();
5108
5109   // Handle the broadcasting a single constant scalar from the constant pool
5110   // into a vector. On Sandybridge it is still better to load a constant vector
5111   // from the constant pool and not to broadcast it from a scalar.
5112   if (ConstSplatVal && Subtarget->hasAVX2()) {
5113     EVT CVT = Ld.getValueType();
5114     assert(!CVT.isVector() && "Must not broadcast a vector type");
5115     unsigned ScalarSize = CVT.getSizeInBits();
5116
5117     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5118       const Constant *C = 0;
5119       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5120         C = CI->getConstantIntValue();
5121       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5122         C = CF->getConstantFPValue();
5123
5124       assert(C && "Invalid constant type");
5125
5126       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5127       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5128       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5129                        MachinePointerInfo::getConstantPool(),
5130                        false, false, false, Alignment);
5131
5132       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5133     }
5134   }
5135
5136   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5137   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5138
5139   // Handle AVX2 in-register broadcasts.
5140   if (!IsLoad && Subtarget->hasAVX2() &&
5141       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5142     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5143
5144   // The scalar source must be a normal load.
5145   if (!IsLoad)
5146     return SDValue();
5147
5148   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5149     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5150
5151   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5152   // double since there is no vbroadcastsd xmm
5153   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5154     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5155       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5156   }
5157
5158   // Unsupported broadcast.
5159   return SDValue();
5160 }
5161
5162 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5163 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5164 // constraint of matching input/output vector elements.
5165 SDValue
5166 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5167   DebugLoc DL = Op.getDebugLoc();
5168   SDNode *N = Op.getNode();
5169   EVT VT = Op.getValueType();
5170   unsigned NumElts = Op.getNumOperands();
5171
5172   // Check supported types and sub-targets.
5173   //
5174   // Only v2f32 -> v2f64 needs special handling.
5175   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5176     return SDValue();
5177
5178   SDValue VecIn;
5179   EVT VecInVT;
5180   SmallVector<int, 8> Mask;
5181   EVT SrcVT = MVT::Other;
5182
5183   // Check the patterns could be translated into X86vfpext.
5184   for (unsigned i = 0; i < NumElts; ++i) {
5185     SDValue In = N->getOperand(i);
5186     unsigned Opcode = In.getOpcode();
5187
5188     // Skip if the element is undefined.
5189     if (Opcode == ISD::UNDEF) {
5190       Mask.push_back(-1);
5191       continue;
5192     }
5193
5194     // Quit if one of the elements is not defined from 'fpext'.
5195     if (Opcode != ISD::FP_EXTEND)
5196       return SDValue();
5197
5198     // Check how the source of 'fpext' is defined.
5199     SDValue L2In = In.getOperand(0);
5200     EVT L2InVT = L2In.getValueType();
5201
5202     // Check the original type
5203     if (SrcVT == MVT::Other)
5204       SrcVT = L2InVT;
5205     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5206       return SDValue();
5207
5208     // Check whether the value being 'fpext'ed is extracted from the same
5209     // source.
5210     Opcode = L2In.getOpcode();
5211
5212     // Quit if it's not extracted with a constant index.
5213     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5214         !isa<ConstantSDNode>(L2In.getOperand(1)))
5215       return SDValue();
5216
5217     SDValue ExtractedFromVec = L2In.getOperand(0);
5218
5219     if (VecIn.getNode() == 0) {
5220       VecIn = ExtractedFromVec;
5221       VecInVT = ExtractedFromVec.getValueType();
5222     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5223       return SDValue();
5224
5225     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5226   }
5227
5228   // Quit if all operands of BUILD_VECTOR are undefined.
5229   if (!VecIn.getNode())
5230     return SDValue();
5231
5232   // Fill the remaining mask as undef.
5233   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5234     Mask.push_back(-1);
5235
5236   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5237                      DAG.getVectorShuffle(VecInVT, DL,
5238                                           VecIn, DAG.getUNDEF(VecInVT),
5239                                           &Mask[0]));
5240 }
5241
5242 SDValue
5243 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5244   DebugLoc dl = Op.getDebugLoc();
5245
5246   EVT VT = Op.getValueType();
5247   EVT ExtVT = VT.getVectorElementType();
5248   unsigned NumElems = Op.getNumOperands();
5249
5250   // Vectors containing all zeros can be matched by pxor and xorps later
5251   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5252     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5253     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5254     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5255       return Op;
5256
5257     return getZeroVector(VT, Subtarget, DAG, dl);
5258   }
5259
5260   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5261   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5262   // vpcmpeqd on 256-bit vectors.
5263   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5264     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5265       return Op;
5266
5267     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5268   }
5269
5270   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5271   if (Broadcast.getNode())
5272     return Broadcast;
5273
5274   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5275   if (FpExt.getNode())
5276     return FpExt;
5277
5278   unsigned EVTBits = ExtVT.getSizeInBits();
5279
5280   unsigned NumZero  = 0;
5281   unsigned NumNonZero = 0;
5282   unsigned NonZeros = 0;
5283   bool IsAllConstants = true;
5284   SmallSet<SDValue, 8> Values;
5285   for (unsigned i = 0; i < NumElems; ++i) {
5286     SDValue Elt = Op.getOperand(i);
5287     if (Elt.getOpcode() == ISD::UNDEF)
5288       continue;
5289     Values.insert(Elt);
5290     if (Elt.getOpcode() != ISD::Constant &&
5291         Elt.getOpcode() != ISD::ConstantFP)
5292       IsAllConstants = false;
5293     if (X86::isZeroNode(Elt))
5294       NumZero++;
5295     else {
5296       NonZeros |= (1 << i);
5297       NumNonZero++;
5298     }
5299   }
5300
5301   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5302   if (NumNonZero == 0)
5303     return DAG.getUNDEF(VT);
5304
5305   // Special case for single non-zero, non-undef, element.
5306   if (NumNonZero == 1) {
5307     unsigned Idx = CountTrailingZeros_32(NonZeros);
5308     SDValue Item = Op.getOperand(Idx);
5309
5310     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5311     // the value are obviously zero, truncate the value to i32 and do the
5312     // insertion that way.  Only do this if the value is non-constant or if the
5313     // value is a constant being inserted into element 0.  It is cheaper to do
5314     // a constant pool load than it is to do a movd + shuffle.
5315     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5316         (!IsAllConstants || Idx == 0)) {
5317       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5318         // Handle SSE only.
5319         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5320         EVT VecVT = MVT::v4i32;
5321         unsigned VecElts = 4;
5322
5323         // Truncate the value (which may itself be a constant) to i32, and
5324         // convert it to a vector with movd (S2V+shuffle to zero extend).
5325         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5326         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5327         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5328
5329         // Now we have our 32-bit value zero extended in the low element of
5330         // a vector.  If Idx != 0, swizzle it into place.
5331         if (Idx != 0) {
5332           SmallVector<int, 4> Mask;
5333           Mask.push_back(Idx);
5334           for (unsigned i = 1; i != VecElts; ++i)
5335             Mask.push_back(i);
5336           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5337                                       &Mask[0]);
5338         }
5339         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5340       }
5341     }
5342
5343     // If we have a constant or non-constant insertion into the low element of
5344     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5345     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5346     // depending on what the source datatype is.
5347     if (Idx == 0) {
5348       if (NumZero == 0)
5349         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5350
5351       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5352           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5353         if (VT.is256BitVector()) {
5354           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5355           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5356                              Item, DAG.getIntPtrConstant(0));
5357         }
5358         assert(VT.is128BitVector() && "Expected an SSE value type!");
5359         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5360         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5361         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5362       }
5363
5364       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5365         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5366         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5367         if (VT.is256BitVector()) {
5368           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5369           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5370         } else {
5371           assert(VT.is128BitVector() && "Expected an SSE value type!");
5372           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5373         }
5374         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5375       }
5376     }
5377
5378     // Is it a vector logical left shift?
5379     if (NumElems == 2 && Idx == 1 &&
5380         X86::isZeroNode(Op.getOperand(0)) &&
5381         !X86::isZeroNode(Op.getOperand(1))) {
5382       unsigned NumBits = VT.getSizeInBits();
5383       return getVShift(true, VT,
5384                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5385                                    VT, Op.getOperand(1)),
5386                        NumBits/2, DAG, *this, dl);
5387     }
5388
5389     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5390       return SDValue();
5391
5392     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5393     // is a non-constant being inserted into an element other than the low one,
5394     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5395     // movd/movss) to move this into the low element, then shuffle it into
5396     // place.
5397     if (EVTBits == 32) {
5398       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5399
5400       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5401       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5402       SmallVector<int, 8> MaskVec;
5403       for (unsigned i = 0; i != NumElems; ++i)
5404         MaskVec.push_back(i == Idx ? 0 : 1);
5405       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5406     }
5407   }
5408
5409   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5410   if (Values.size() == 1) {
5411     if (EVTBits == 32) {
5412       // Instead of a shuffle like this:
5413       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5414       // Check if it's possible to issue this instead.
5415       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5416       unsigned Idx = CountTrailingZeros_32(NonZeros);
5417       SDValue Item = Op.getOperand(Idx);
5418       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5419         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5420     }
5421     return SDValue();
5422   }
5423
5424   // A vector full of immediates; various special cases are already
5425   // handled, so this is best done with a single constant-pool load.
5426   if (IsAllConstants)
5427     return SDValue();
5428
5429   // For AVX-length vectors, build the individual 128-bit pieces and use
5430   // shuffles to put them in place.
5431   if (VT.is256BitVector()) {
5432     SmallVector<SDValue, 32> V;
5433     for (unsigned i = 0; i != NumElems; ++i)
5434       V.push_back(Op.getOperand(i));
5435
5436     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5437
5438     // Build both the lower and upper subvector.
5439     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5440     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5441                                 NumElems/2);
5442
5443     // Recreate the wider vector with the lower and upper part.
5444     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5445   }
5446
5447   // Let legalizer expand 2-wide build_vectors.
5448   if (EVTBits == 64) {
5449     if (NumNonZero == 1) {
5450       // One half is zero or undef.
5451       unsigned Idx = CountTrailingZeros_32(NonZeros);
5452       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5453                                  Op.getOperand(Idx));
5454       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5455     }
5456     return SDValue();
5457   }
5458
5459   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5460   if (EVTBits == 8 && NumElems == 16) {
5461     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5462                                         Subtarget, *this);
5463     if (V.getNode()) return V;
5464   }
5465
5466   if (EVTBits == 16 && NumElems == 8) {
5467     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5468                                       Subtarget, *this);
5469     if (V.getNode()) return V;
5470   }
5471
5472   // If element VT is == 32 bits, turn it into a number of shuffles.
5473   SmallVector<SDValue, 8> V(NumElems);
5474   if (NumElems == 4 && NumZero > 0) {
5475     for (unsigned i = 0; i < 4; ++i) {
5476       bool isZero = !(NonZeros & (1 << i));
5477       if (isZero)
5478         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5479       else
5480         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5481     }
5482
5483     for (unsigned i = 0; i < 2; ++i) {
5484       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5485         default: break;
5486         case 0:
5487           V[i] = V[i*2];  // Must be a zero vector.
5488           break;
5489         case 1:
5490           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5491           break;
5492         case 2:
5493           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5494           break;
5495         case 3:
5496           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5497           break;
5498       }
5499     }
5500
5501     bool Reverse1 = (NonZeros & 0x3) == 2;
5502     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5503     int MaskVec[] = {
5504       Reverse1 ? 1 : 0,
5505       Reverse1 ? 0 : 1,
5506       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5507       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5508     };
5509     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5510   }
5511
5512   if (Values.size() > 1 && VT.is128BitVector()) {
5513     // Check for a build vector of consecutive loads.
5514     for (unsigned i = 0; i < NumElems; ++i)
5515       V[i] = Op.getOperand(i);
5516
5517     // Check for elements which are consecutive loads.
5518     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5519     if (LD.getNode())
5520       return LD;
5521
5522     // For SSE 4.1, use insertps to put the high elements into the low element.
5523     if (getSubtarget()->hasSSE41()) {
5524       SDValue Result;
5525       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5526         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5527       else
5528         Result = DAG.getUNDEF(VT);
5529
5530       for (unsigned i = 1; i < NumElems; ++i) {
5531         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5532         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5533                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5534       }
5535       return Result;
5536     }
5537
5538     // Otherwise, expand into a number of unpckl*, start by extending each of
5539     // our (non-undef) elements to the full vector width with the element in the
5540     // bottom slot of the vector (which generates no code for SSE).
5541     for (unsigned i = 0; i < NumElems; ++i) {
5542       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5543         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5544       else
5545         V[i] = DAG.getUNDEF(VT);
5546     }
5547
5548     // Next, we iteratively mix elements, e.g. for v4f32:
5549     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5550     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5551     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5552     unsigned EltStride = NumElems >> 1;
5553     while (EltStride != 0) {
5554       for (unsigned i = 0; i < EltStride; ++i) {
5555         // If V[i+EltStride] is undef and this is the first round of mixing,
5556         // then it is safe to just drop this shuffle: V[i] is already in the
5557         // right place, the one element (since it's the first round) being
5558         // inserted as undef can be dropped.  This isn't safe for successive
5559         // rounds because they will permute elements within both vectors.
5560         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5561             EltStride == NumElems/2)
5562           continue;
5563
5564         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5565       }
5566       EltStride >>= 1;
5567     }
5568     return V[0];
5569   }
5570   return SDValue();
5571 }
5572
5573 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5574 // to create 256-bit vectors from two other 128-bit ones.
5575 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5576   DebugLoc dl = Op.getDebugLoc();
5577   EVT ResVT = Op.getValueType();
5578
5579   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5580
5581   SDValue V1 = Op.getOperand(0);
5582   SDValue V2 = Op.getOperand(1);
5583   unsigned NumElems = ResVT.getVectorNumElements();
5584
5585   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5586 }
5587
5588 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5589   assert(Op.getNumOperands() == 2);
5590
5591   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5592   // from two other 128-bit ones.
5593   return LowerAVXCONCAT_VECTORS(Op, DAG);
5594 }
5595
5596 // Try to lower a shuffle node into a simple blend instruction.
5597 static SDValue
5598 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5599                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5600   SDValue V1 = SVOp->getOperand(0);
5601   SDValue V2 = SVOp->getOperand(1);
5602   DebugLoc dl = SVOp->getDebugLoc();
5603   MVT VT = SVOp->getValueType(0).getSimpleVT();
5604   unsigned NumElems = VT.getVectorNumElements();
5605
5606   if (!Subtarget->hasSSE41())
5607     return SDValue();
5608
5609   unsigned ISDNo = 0;
5610   MVT OpTy;
5611
5612   switch (VT.SimpleTy) {
5613   default: return SDValue();
5614   case MVT::v8i16:
5615     ISDNo = X86ISD::BLENDPW;
5616     OpTy = MVT::v8i16;
5617     break;
5618   case MVT::v4i32:
5619   case MVT::v4f32:
5620     ISDNo = X86ISD::BLENDPS;
5621     OpTy = MVT::v4f32;
5622     break;
5623   case MVT::v2i64:
5624   case MVT::v2f64:
5625     ISDNo = X86ISD::BLENDPD;
5626     OpTy = MVT::v2f64;
5627     break;
5628   case MVT::v8i32:
5629   case MVT::v8f32:
5630     if (!Subtarget->hasAVX())
5631       return SDValue();
5632     ISDNo = X86ISD::BLENDPS;
5633     OpTy = MVT::v8f32;
5634     break;
5635   case MVT::v4i64:
5636   case MVT::v4f64:
5637     if (!Subtarget->hasAVX())
5638       return SDValue();
5639     ISDNo = X86ISD::BLENDPD;
5640     OpTy = MVT::v4f64;
5641     break;
5642   }
5643   assert(ISDNo && "Invalid Op Number");
5644
5645   unsigned MaskVals = 0;
5646
5647   for (unsigned i = 0; i != NumElems; ++i) {
5648     int EltIdx = SVOp->getMaskElt(i);
5649     if (EltIdx == (int)i || EltIdx < 0)
5650       MaskVals |= (1<<i);
5651     else if (EltIdx == (int)(i + NumElems))
5652       continue; // Bit is set to zero;
5653     else
5654       return SDValue();
5655   }
5656
5657   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5658   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5659   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5660                              DAG.getConstant(MaskVals, MVT::i32));
5661   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5662 }
5663
5664 // v8i16 shuffles - Prefer shuffles in the following order:
5665 // 1. [all]   pshuflw, pshufhw, optional move
5666 // 2. [ssse3] 1 x pshufb
5667 // 3. [ssse3] 2 x pshufb + 1 x por
5668 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5669 static SDValue
5670 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5671                          SelectionDAG &DAG) {
5672   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5673   SDValue V1 = SVOp->getOperand(0);
5674   SDValue V2 = SVOp->getOperand(1);
5675   DebugLoc dl = SVOp->getDebugLoc();
5676   SmallVector<int, 8> MaskVals;
5677
5678   // Determine if more than 1 of the words in each of the low and high quadwords
5679   // of the result come from the same quadword of one of the two inputs.  Undef
5680   // mask values count as coming from any quadword, for better codegen.
5681   unsigned LoQuad[] = { 0, 0, 0, 0 };
5682   unsigned HiQuad[] = { 0, 0, 0, 0 };
5683   std::bitset<4> InputQuads;
5684   for (unsigned i = 0; i < 8; ++i) {
5685     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5686     int EltIdx = SVOp->getMaskElt(i);
5687     MaskVals.push_back(EltIdx);
5688     if (EltIdx < 0) {
5689       ++Quad[0];
5690       ++Quad[1];
5691       ++Quad[2];
5692       ++Quad[3];
5693       continue;
5694     }
5695     ++Quad[EltIdx / 4];
5696     InputQuads.set(EltIdx / 4);
5697   }
5698
5699   int BestLoQuad = -1;
5700   unsigned MaxQuad = 1;
5701   for (unsigned i = 0; i < 4; ++i) {
5702     if (LoQuad[i] > MaxQuad) {
5703       BestLoQuad = i;
5704       MaxQuad = LoQuad[i];
5705     }
5706   }
5707
5708   int BestHiQuad = -1;
5709   MaxQuad = 1;
5710   for (unsigned i = 0; i < 4; ++i) {
5711     if (HiQuad[i] > MaxQuad) {
5712       BestHiQuad = i;
5713       MaxQuad = HiQuad[i];
5714     }
5715   }
5716
5717   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5718   // of the two input vectors, shuffle them into one input vector so only a
5719   // single pshufb instruction is necessary. If There are more than 2 input
5720   // quads, disable the next transformation since it does not help SSSE3.
5721   bool V1Used = InputQuads[0] || InputQuads[1];
5722   bool V2Used = InputQuads[2] || InputQuads[3];
5723   if (Subtarget->hasSSSE3()) {
5724     if (InputQuads.count() == 2 && V1Used && V2Used) {
5725       BestLoQuad = InputQuads[0] ? 0 : 1;
5726       BestHiQuad = InputQuads[2] ? 2 : 3;
5727     }
5728     if (InputQuads.count() > 2) {
5729       BestLoQuad = -1;
5730       BestHiQuad = -1;
5731     }
5732   }
5733
5734   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5735   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5736   // words from all 4 input quadwords.
5737   SDValue NewV;
5738   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5739     int MaskV[] = {
5740       BestLoQuad < 0 ? 0 : BestLoQuad,
5741       BestHiQuad < 0 ? 1 : BestHiQuad
5742     };
5743     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5744                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5745                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5746     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5747
5748     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5749     // source words for the shuffle, to aid later transformations.
5750     bool AllWordsInNewV = true;
5751     bool InOrder[2] = { true, true };
5752     for (unsigned i = 0; i != 8; ++i) {
5753       int idx = MaskVals[i];
5754       if (idx != (int)i)
5755         InOrder[i/4] = false;
5756       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5757         continue;
5758       AllWordsInNewV = false;
5759       break;
5760     }
5761
5762     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5763     if (AllWordsInNewV) {
5764       for (int i = 0; i != 8; ++i) {
5765         int idx = MaskVals[i];
5766         if (idx < 0)
5767           continue;
5768         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5769         if ((idx != i) && idx < 4)
5770           pshufhw = false;
5771         if ((idx != i) && idx > 3)
5772           pshuflw = false;
5773       }
5774       V1 = NewV;
5775       V2Used = false;
5776       BestLoQuad = 0;
5777       BestHiQuad = 1;
5778     }
5779
5780     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5781     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5782     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5783       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5784       unsigned TargetMask = 0;
5785       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5786                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5787       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5788       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5789                              getShufflePSHUFLWImmediate(SVOp);
5790       V1 = NewV.getOperand(0);
5791       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5792     }
5793   }
5794
5795   // If we have SSSE3, and all words of the result are from 1 input vector,
5796   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5797   // is present, fall back to case 4.
5798   if (Subtarget->hasSSSE3()) {
5799     SmallVector<SDValue,16> pshufbMask;
5800
5801     // If we have elements from both input vectors, set the high bit of the
5802     // shuffle mask element to zero out elements that come from V2 in the V1
5803     // mask, and elements that come from V1 in the V2 mask, so that the two
5804     // results can be OR'd together.
5805     bool TwoInputs = V1Used && V2Used;
5806     for (unsigned i = 0; i != 8; ++i) {
5807       int EltIdx = MaskVals[i] * 2;
5808       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5809       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5810       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5811       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5812     }
5813     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5814     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5815                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5816                                  MVT::v16i8, &pshufbMask[0], 16));
5817     if (!TwoInputs)
5818       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5819
5820     // Calculate the shuffle mask for the second input, shuffle it, and
5821     // OR it with the first shuffled input.
5822     pshufbMask.clear();
5823     for (unsigned i = 0; i != 8; ++i) {
5824       int EltIdx = MaskVals[i] * 2;
5825       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5826       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5827       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5828       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5829     }
5830     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5831     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5832                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5833                                  MVT::v16i8, &pshufbMask[0], 16));
5834     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5835     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5836   }
5837
5838   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5839   // and update MaskVals with new element order.
5840   std::bitset<8> InOrder;
5841   if (BestLoQuad >= 0) {
5842     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5843     for (int i = 0; i != 4; ++i) {
5844       int idx = MaskVals[i];
5845       if (idx < 0) {
5846         InOrder.set(i);
5847       } else if ((idx / 4) == BestLoQuad) {
5848         MaskV[i] = idx & 3;
5849         InOrder.set(i);
5850       }
5851     }
5852     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5853                                 &MaskV[0]);
5854
5855     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5856       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5857       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5858                                   NewV.getOperand(0),
5859                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5860     }
5861   }
5862
5863   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5864   // and update MaskVals with the new element order.
5865   if (BestHiQuad >= 0) {
5866     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5867     for (unsigned i = 4; i != 8; ++i) {
5868       int idx = MaskVals[i];
5869       if (idx < 0) {
5870         InOrder.set(i);
5871       } else if ((idx / 4) == BestHiQuad) {
5872         MaskV[i] = (idx & 3) + 4;
5873         InOrder.set(i);
5874       }
5875     }
5876     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5877                                 &MaskV[0]);
5878
5879     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5880       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5881       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5882                                   NewV.getOperand(0),
5883                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5884     }
5885   }
5886
5887   // In case BestHi & BestLo were both -1, which means each quadword has a word
5888   // from each of the four input quadwords, calculate the InOrder bitvector now
5889   // before falling through to the insert/extract cleanup.
5890   if (BestLoQuad == -1 && BestHiQuad == -1) {
5891     NewV = V1;
5892     for (int i = 0; i != 8; ++i)
5893       if (MaskVals[i] < 0 || MaskVals[i] == i)
5894         InOrder.set(i);
5895   }
5896
5897   // The other elements are put in the right place using pextrw and pinsrw.
5898   for (unsigned i = 0; i != 8; ++i) {
5899     if (InOrder[i])
5900       continue;
5901     int EltIdx = MaskVals[i];
5902     if (EltIdx < 0)
5903       continue;
5904     SDValue ExtOp = (EltIdx < 8) ?
5905       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5906                   DAG.getIntPtrConstant(EltIdx)) :
5907       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5908                   DAG.getIntPtrConstant(EltIdx - 8));
5909     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5910                        DAG.getIntPtrConstant(i));
5911   }
5912   return NewV;
5913 }
5914
5915 // v16i8 shuffles - Prefer shuffles in the following order:
5916 // 1. [ssse3] 1 x pshufb
5917 // 2. [ssse3] 2 x pshufb + 1 x por
5918 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5919 static
5920 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5921                                  SelectionDAG &DAG,
5922                                  const X86TargetLowering &TLI) {
5923   SDValue V1 = SVOp->getOperand(0);
5924   SDValue V2 = SVOp->getOperand(1);
5925   DebugLoc dl = SVOp->getDebugLoc();
5926   ArrayRef<int> MaskVals = SVOp->getMask();
5927
5928   // If we have SSSE3, case 1 is generated when all result bytes come from
5929   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5930   // present, fall back to case 3.
5931
5932   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5933   if (TLI.getSubtarget()->hasSSSE3()) {
5934     SmallVector<SDValue,16> pshufbMask;
5935
5936     // If all result elements are from one input vector, then only translate
5937     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5938     //
5939     // Otherwise, we have elements from both input vectors, and must zero out
5940     // elements that come from V2 in the first mask, and V1 in the second mask
5941     // so that we can OR them together.
5942     for (unsigned i = 0; i != 16; ++i) {
5943       int EltIdx = MaskVals[i];
5944       if (EltIdx < 0 || EltIdx >= 16)
5945         EltIdx = 0x80;
5946       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5947     }
5948     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5949                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5950                                  MVT::v16i8, &pshufbMask[0], 16));
5951
5952     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5953     // the 2nd operand if it's undefined or zero.
5954     if (V2.getOpcode() == ISD::UNDEF ||
5955         ISD::isBuildVectorAllZeros(V2.getNode()))
5956       return V1;
5957
5958     // Calculate the shuffle mask for the second input, shuffle it, and
5959     // OR it with the first shuffled input.
5960     pshufbMask.clear();
5961     for (unsigned i = 0; i != 16; ++i) {
5962       int EltIdx = MaskVals[i];
5963       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5964       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5965     }
5966     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5967                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5968                                  MVT::v16i8, &pshufbMask[0], 16));
5969     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5970   }
5971
5972   // No SSSE3 - Calculate in place words and then fix all out of place words
5973   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5974   // the 16 different words that comprise the two doublequadword input vectors.
5975   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5976   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5977   SDValue NewV = V1;
5978   for (int i = 0; i != 8; ++i) {
5979     int Elt0 = MaskVals[i*2];
5980     int Elt1 = MaskVals[i*2+1];
5981
5982     // This word of the result is all undef, skip it.
5983     if (Elt0 < 0 && Elt1 < 0)
5984       continue;
5985
5986     // This word of the result is already in the correct place, skip it.
5987     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5988       continue;
5989
5990     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5991     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5992     SDValue InsElt;
5993
5994     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5995     // using a single extract together, load it and store it.
5996     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5997       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5998                            DAG.getIntPtrConstant(Elt1 / 2));
5999       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6000                         DAG.getIntPtrConstant(i));
6001       continue;
6002     }
6003
6004     // If Elt1 is defined, extract it from the appropriate source.  If the
6005     // source byte is not also odd, shift the extracted word left 8 bits
6006     // otherwise clear the bottom 8 bits if we need to do an or.
6007     if (Elt1 >= 0) {
6008       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6009                            DAG.getIntPtrConstant(Elt1 / 2));
6010       if ((Elt1 & 1) == 0)
6011         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6012                              DAG.getConstant(8,
6013                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6014       else if (Elt0 >= 0)
6015         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6016                              DAG.getConstant(0xFF00, MVT::i16));
6017     }
6018     // If Elt0 is defined, extract it from the appropriate source.  If the
6019     // source byte is not also even, shift the extracted word right 8 bits. If
6020     // Elt1 was also defined, OR the extracted values together before
6021     // inserting them in the result.
6022     if (Elt0 >= 0) {
6023       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6024                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6025       if ((Elt0 & 1) != 0)
6026         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6027                               DAG.getConstant(8,
6028                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6029       else if (Elt1 >= 0)
6030         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6031                              DAG.getConstant(0x00FF, MVT::i16));
6032       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6033                          : InsElt0;
6034     }
6035     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6036                        DAG.getIntPtrConstant(i));
6037   }
6038   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6039 }
6040
6041 // v32i8 shuffles - Translate to VPSHUFB if possible.
6042 static
6043 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6044                                  const X86Subtarget *Subtarget,
6045                                  SelectionDAG &DAG) {
6046   EVT VT = SVOp->getValueType(0);
6047   SDValue V1 = SVOp->getOperand(0);
6048   SDValue V2 = SVOp->getOperand(1);
6049   DebugLoc dl = SVOp->getDebugLoc();
6050   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6051
6052   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6053   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6054   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6055
6056   // VPSHUFB may be generated if 
6057   // (1) one of input vector is undefined or zeroinitializer.
6058   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6059   // And (2) the mask indexes don't cross the 128-bit lane.
6060   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6061       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6062     return SDValue();
6063
6064   if (V1IsAllZero && !V2IsAllZero) {
6065     CommuteVectorShuffleMask(MaskVals, 32);
6066     V1 = V2;
6067   }
6068   SmallVector<SDValue, 32> pshufbMask;
6069   for (unsigned i = 0; i != 32; i++) {
6070     int EltIdx = MaskVals[i];
6071     if (EltIdx < 0 || EltIdx >= 32)
6072       EltIdx = 0x80;
6073     else {
6074       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6075         // Cross lane is not allowed.
6076         return SDValue();
6077       EltIdx &= 0xf;
6078     }
6079     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6080   }
6081   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6082                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6083                                   MVT::v32i8, &pshufbMask[0], 32));
6084 }
6085
6086 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6087 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6088 /// done when every pair / quad of shuffle mask elements point to elements in
6089 /// the right sequence. e.g.
6090 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6091 static
6092 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6093                                  SelectionDAG &DAG, DebugLoc dl) {
6094   MVT VT = SVOp->getValueType(0).getSimpleVT();
6095   unsigned NumElems = VT.getVectorNumElements();
6096   MVT NewVT;
6097   unsigned Scale;
6098   switch (VT.SimpleTy) {
6099   default: llvm_unreachable("Unexpected!");
6100   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6101   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6102   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6103   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6104   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6105   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6106   }
6107
6108   SmallVector<int, 8> MaskVec;
6109   for (unsigned i = 0; i != NumElems; i += Scale) {
6110     int StartIdx = -1;
6111     for (unsigned j = 0; j != Scale; ++j) {
6112       int EltIdx = SVOp->getMaskElt(i+j);
6113       if (EltIdx < 0)
6114         continue;
6115       if (StartIdx < 0)
6116         StartIdx = (EltIdx / Scale);
6117       if (EltIdx != (int)(StartIdx*Scale + j))
6118         return SDValue();
6119     }
6120     MaskVec.push_back(StartIdx);
6121   }
6122
6123   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6124   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6125   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6126 }
6127
6128 /// getVZextMovL - Return a zero-extending vector move low node.
6129 ///
6130 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6131                             SDValue SrcOp, SelectionDAG &DAG,
6132                             const X86Subtarget *Subtarget, DebugLoc dl) {
6133   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6134     LoadSDNode *LD = NULL;
6135     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6136       LD = dyn_cast<LoadSDNode>(SrcOp);
6137     if (!LD) {
6138       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6139       // instead.
6140       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6141       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6142           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6143           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6144           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6145         // PR2108
6146         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6147         return DAG.getNode(ISD::BITCAST, dl, VT,
6148                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6149                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6150                                                    OpVT,
6151                                                    SrcOp.getOperand(0)
6152                                                           .getOperand(0))));
6153       }
6154     }
6155   }
6156
6157   return DAG.getNode(ISD::BITCAST, dl, VT,
6158                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6159                                  DAG.getNode(ISD::BITCAST, dl,
6160                                              OpVT, SrcOp)));
6161 }
6162
6163 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6164 /// which could not be matched by any known target speficic shuffle
6165 static SDValue
6166 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6167
6168   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6169   if (NewOp.getNode())
6170     return NewOp;
6171
6172   EVT VT = SVOp->getValueType(0);
6173
6174   unsigned NumElems = VT.getVectorNumElements();
6175   unsigned NumLaneElems = NumElems / 2;
6176
6177   DebugLoc dl = SVOp->getDebugLoc();
6178   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6179   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6180   SDValue Output[2];
6181
6182   SmallVector<int, 16> Mask;
6183   for (unsigned l = 0; l < 2; ++l) {
6184     // Build a shuffle mask for the output, discovering on the fly which
6185     // input vectors to use as shuffle operands (recorded in InputUsed).
6186     // If building a suitable shuffle vector proves too hard, then bail
6187     // out with UseBuildVector set.
6188     bool UseBuildVector = false;
6189     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6190     unsigned LaneStart = l * NumLaneElems;
6191     for (unsigned i = 0; i != NumLaneElems; ++i) {
6192       // The mask element.  This indexes into the input.
6193       int Idx = SVOp->getMaskElt(i+LaneStart);
6194       if (Idx < 0) {
6195         // the mask element does not index into any input vector.
6196         Mask.push_back(-1);
6197         continue;
6198       }
6199
6200       // The input vector this mask element indexes into.
6201       int Input = Idx / NumLaneElems;
6202
6203       // Turn the index into an offset from the start of the input vector.
6204       Idx -= Input * NumLaneElems;
6205
6206       // Find or create a shuffle vector operand to hold this input.
6207       unsigned OpNo;
6208       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6209         if (InputUsed[OpNo] == Input)
6210           // This input vector is already an operand.
6211           break;
6212         if (InputUsed[OpNo] < 0) {
6213           // Create a new operand for this input vector.
6214           InputUsed[OpNo] = Input;
6215           break;
6216         }
6217       }
6218
6219       if (OpNo >= array_lengthof(InputUsed)) {
6220         // More than two input vectors used!  Give up on trying to create a
6221         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6222         UseBuildVector = true;
6223         break;
6224       }
6225
6226       // Add the mask index for the new shuffle vector.
6227       Mask.push_back(Idx + OpNo * NumLaneElems);
6228     }
6229
6230     if (UseBuildVector) {
6231       SmallVector<SDValue, 16> SVOps;
6232       for (unsigned i = 0; i != NumLaneElems; ++i) {
6233         // The mask element.  This indexes into the input.
6234         int Idx = SVOp->getMaskElt(i+LaneStart);
6235         if (Idx < 0) {
6236           SVOps.push_back(DAG.getUNDEF(EltVT));
6237           continue;
6238         }
6239
6240         // The input vector this mask element indexes into.
6241         int Input = Idx / NumElems;
6242
6243         // Turn the index into an offset from the start of the input vector.
6244         Idx -= Input * NumElems;
6245
6246         // Extract the vector element by hand.
6247         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6248                                     SVOp->getOperand(Input),
6249                                     DAG.getIntPtrConstant(Idx)));
6250       }
6251
6252       // Construct the output using a BUILD_VECTOR.
6253       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6254                               SVOps.size());
6255     } else if (InputUsed[0] < 0) {
6256       // No input vectors were used! The result is undefined.
6257       Output[l] = DAG.getUNDEF(NVT);
6258     } else {
6259       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6260                                         (InputUsed[0] % 2) * NumLaneElems,
6261                                         DAG, dl);
6262       // If only one input was used, use an undefined vector for the other.
6263       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6264         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6265                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6266       // At least one input vector was used. Create a new shuffle vector.
6267       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6268     }
6269
6270     Mask.clear();
6271   }
6272
6273   // Concatenate the result back
6274   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6275 }
6276
6277 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6278 /// 4 elements, and match them with several different shuffle types.
6279 static SDValue
6280 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6281   SDValue V1 = SVOp->getOperand(0);
6282   SDValue V2 = SVOp->getOperand(1);
6283   DebugLoc dl = SVOp->getDebugLoc();
6284   EVT VT = SVOp->getValueType(0);
6285
6286   assert(VT.is128BitVector() && "Unsupported vector size");
6287
6288   std::pair<int, int> Locs[4];
6289   int Mask1[] = { -1, -1, -1, -1 };
6290   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6291
6292   unsigned NumHi = 0;
6293   unsigned NumLo = 0;
6294   for (unsigned i = 0; i != 4; ++i) {
6295     int Idx = PermMask[i];
6296     if (Idx < 0) {
6297       Locs[i] = std::make_pair(-1, -1);
6298     } else {
6299       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6300       if (Idx < 4) {
6301         Locs[i] = std::make_pair(0, NumLo);
6302         Mask1[NumLo] = Idx;
6303         NumLo++;
6304       } else {
6305         Locs[i] = std::make_pair(1, NumHi);
6306         if (2+NumHi < 4)
6307           Mask1[2+NumHi] = Idx;
6308         NumHi++;
6309       }
6310     }
6311   }
6312
6313   if (NumLo <= 2 && NumHi <= 2) {
6314     // If no more than two elements come from either vector. This can be
6315     // implemented with two shuffles. First shuffle gather the elements.
6316     // The second shuffle, which takes the first shuffle as both of its
6317     // vector operands, put the elements into the right order.
6318     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6319
6320     int Mask2[] = { -1, -1, -1, -1 };
6321
6322     for (unsigned i = 0; i != 4; ++i)
6323       if (Locs[i].first != -1) {
6324         unsigned Idx = (i < 2) ? 0 : 4;
6325         Idx += Locs[i].first * 2 + Locs[i].second;
6326         Mask2[i] = Idx;
6327       }
6328
6329     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6330   }
6331
6332   if (NumLo == 3 || NumHi == 3) {
6333     // Otherwise, we must have three elements from one vector, call it X, and
6334     // one element from the other, call it Y.  First, use a shufps to build an
6335     // intermediate vector with the one element from Y and the element from X
6336     // that will be in the same half in the final destination (the indexes don't
6337     // matter). Then, use a shufps to build the final vector, taking the half
6338     // containing the element from Y from the intermediate, and the other half
6339     // from X.
6340     if (NumHi == 3) {
6341       // Normalize it so the 3 elements come from V1.
6342       CommuteVectorShuffleMask(PermMask, 4);
6343       std::swap(V1, V2);
6344     }
6345
6346     // Find the element from V2.
6347     unsigned HiIndex;
6348     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6349       int Val = PermMask[HiIndex];
6350       if (Val < 0)
6351         continue;
6352       if (Val >= 4)
6353         break;
6354     }
6355
6356     Mask1[0] = PermMask[HiIndex];
6357     Mask1[1] = -1;
6358     Mask1[2] = PermMask[HiIndex^1];
6359     Mask1[3] = -1;
6360     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6361
6362     if (HiIndex >= 2) {
6363       Mask1[0] = PermMask[0];
6364       Mask1[1] = PermMask[1];
6365       Mask1[2] = HiIndex & 1 ? 6 : 4;
6366       Mask1[3] = HiIndex & 1 ? 4 : 6;
6367       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6368     }
6369
6370     Mask1[0] = HiIndex & 1 ? 2 : 0;
6371     Mask1[1] = HiIndex & 1 ? 0 : 2;
6372     Mask1[2] = PermMask[2];
6373     Mask1[3] = PermMask[3];
6374     if (Mask1[2] >= 0)
6375       Mask1[2] += 4;
6376     if (Mask1[3] >= 0)
6377       Mask1[3] += 4;
6378     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6379   }
6380
6381   // Break it into (shuffle shuffle_hi, shuffle_lo).
6382   int LoMask[] = { -1, -1, -1, -1 };
6383   int HiMask[] = { -1, -1, -1, -1 };
6384
6385   int *MaskPtr = LoMask;
6386   unsigned MaskIdx = 0;
6387   unsigned LoIdx = 0;
6388   unsigned HiIdx = 2;
6389   for (unsigned i = 0; i != 4; ++i) {
6390     if (i == 2) {
6391       MaskPtr = HiMask;
6392       MaskIdx = 1;
6393       LoIdx = 0;
6394       HiIdx = 2;
6395     }
6396     int Idx = PermMask[i];
6397     if (Idx < 0) {
6398       Locs[i] = std::make_pair(-1, -1);
6399     } else if (Idx < 4) {
6400       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6401       MaskPtr[LoIdx] = Idx;
6402       LoIdx++;
6403     } else {
6404       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6405       MaskPtr[HiIdx] = Idx;
6406       HiIdx++;
6407     }
6408   }
6409
6410   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6411   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6412   int MaskOps[] = { -1, -1, -1, -1 };
6413   for (unsigned i = 0; i != 4; ++i)
6414     if (Locs[i].first != -1)
6415       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6416   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6417 }
6418
6419 static bool MayFoldVectorLoad(SDValue V) {
6420   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6421     V = V.getOperand(0);
6422   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6423     V = V.getOperand(0);
6424   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6425       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6426     // BUILD_VECTOR (load), undef
6427     V = V.getOperand(0);
6428   if (MayFoldLoad(V))
6429     return true;
6430   return false;
6431 }
6432
6433 // FIXME: the version above should always be used. Since there's
6434 // a bug where several vector shuffles can't be folded because the
6435 // DAG is not updated during lowering and a node claims to have two
6436 // uses while it only has one, use this version, and let isel match
6437 // another instruction if the load really happens to have more than
6438 // one use. Remove this version after this bug get fixed.
6439 // rdar://8434668, PR8156
6440 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6441   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6442     V = V.getOperand(0);
6443   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6444     V = V.getOperand(0);
6445   if (ISD::isNormalLoad(V.getNode()))
6446     return true;
6447   return false;
6448 }
6449
6450 static
6451 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6452   EVT VT = Op.getValueType();
6453
6454   // Canonizalize to v2f64.
6455   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6456   return DAG.getNode(ISD::BITCAST, dl, VT,
6457                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6458                                           V1, DAG));
6459 }
6460
6461 static
6462 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6463                         bool HasSSE2) {
6464   SDValue V1 = Op.getOperand(0);
6465   SDValue V2 = Op.getOperand(1);
6466   EVT VT = Op.getValueType();
6467
6468   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6469
6470   if (HasSSE2 && VT == MVT::v2f64)
6471     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6472
6473   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6474   return DAG.getNode(ISD::BITCAST, dl, VT,
6475                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6476                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6477                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6478 }
6479
6480 static
6481 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484   EVT VT = Op.getValueType();
6485
6486   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6487          "unsupported shuffle type");
6488
6489   if (V2.getOpcode() == ISD::UNDEF)
6490     V2 = V1;
6491
6492   // v4i32 or v4f32
6493   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6494 }
6495
6496 static
6497 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6498   SDValue V1 = Op.getOperand(0);
6499   SDValue V2 = Op.getOperand(1);
6500   EVT VT = Op.getValueType();
6501   unsigned NumElems = VT.getVectorNumElements();
6502
6503   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6504   // operand of these instructions is only memory, so check if there's a
6505   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6506   // same masks.
6507   bool CanFoldLoad = false;
6508
6509   // Trivial case, when V2 comes from a load.
6510   if (MayFoldVectorLoad(V2))
6511     CanFoldLoad = true;
6512
6513   // When V1 is a load, it can be folded later into a store in isel, example:
6514   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6515   //    turns into:
6516   //  (MOVLPSmr addr:$src1, VR128:$src2)
6517   // So, recognize this potential and also use MOVLPS or MOVLPD
6518   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6519     CanFoldLoad = true;
6520
6521   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6522   if (CanFoldLoad) {
6523     if (HasSSE2 && NumElems == 2)
6524       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6525
6526     if (NumElems == 4)
6527       // If we don't care about the second element, proceed to use movss.
6528       if (SVOp->getMaskElt(1) != -1)
6529         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6530   }
6531
6532   // movl and movlp will both match v2i64, but v2i64 is never matched by
6533   // movl earlier because we make it strict to avoid messing with the movlp load
6534   // folding logic (see the code above getMOVLP call). Match it here then,
6535   // this is horrible, but will stay like this until we move all shuffle
6536   // matching to x86 specific nodes. Note that for the 1st condition all
6537   // types are matched with movsd.
6538   if (HasSSE2) {
6539     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6540     // as to remove this logic from here, as much as possible
6541     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6542       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6543     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6544   }
6545
6546   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6547
6548   // Invert the operand order and use SHUFPS to match it.
6549   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6550                               getShuffleSHUFImmediate(SVOp), DAG);
6551 }
6552
6553 SDValue
6554 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6555   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6556   EVT VT = Op.getValueType();
6557   DebugLoc dl = Op.getDebugLoc();
6558   SDValue V1 = Op.getOperand(0);
6559   SDValue V2 = Op.getOperand(1);
6560
6561   if (isZeroShuffle(SVOp))
6562     return getZeroVector(VT, Subtarget, DAG, dl);
6563
6564   // Handle splat operations
6565   if (SVOp->isSplat()) {
6566     unsigned NumElem = VT.getVectorNumElements();
6567     int Size = VT.getSizeInBits();
6568
6569     // Use vbroadcast whenever the splat comes from a foldable load
6570     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6571     if (Broadcast.getNode())
6572       return Broadcast;
6573
6574     // Handle splats by matching through known shuffle masks
6575     if ((Size == 128 && NumElem <= 4) ||
6576         (Size == 256 && NumElem < 8))
6577       return SDValue();
6578
6579     // All remaning splats are promoted to target supported vector shuffles.
6580     return PromoteSplat(SVOp, DAG);
6581   }
6582
6583   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6584   // do it!
6585   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6586       VT == MVT::v16i16 || VT == MVT::v32i8) {
6587     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6588     if (NewOp.getNode())
6589       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6590   } else if ((VT == MVT::v4i32 ||
6591              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6592     // FIXME: Figure out a cleaner way to do this.
6593     // Try to make use of movq to zero out the top part.
6594     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6595       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6596       if (NewOp.getNode()) {
6597         EVT NewVT = NewOp.getValueType();
6598         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6599                                NewVT, true, false))
6600           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6601                               DAG, Subtarget, dl);
6602       }
6603     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6604       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6605       if (NewOp.getNode()) {
6606         EVT NewVT = NewOp.getValueType();
6607         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6608           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6609                               DAG, Subtarget, dl);
6610       }
6611     }
6612   }
6613   return SDValue();
6614 }
6615
6616 SDValue
6617 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6618   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6619   SDValue V1 = Op.getOperand(0);
6620   SDValue V2 = Op.getOperand(1);
6621   EVT VT = Op.getValueType();
6622   DebugLoc dl = Op.getDebugLoc();
6623   unsigned NumElems = VT.getVectorNumElements();
6624   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6625   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6626   bool V1IsSplat = false;
6627   bool V2IsSplat = false;
6628   bool HasSSE2 = Subtarget->hasSSE2();
6629   bool HasAVX    = Subtarget->hasAVX();
6630   bool HasAVX2   = Subtarget->hasAVX2();
6631   MachineFunction &MF = DAG.getMachineFunction();
6632   bool OptForSize = MF.getFunction()->getFnAttributes().hasOptimizeForSizeAttr();
6633
6634   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6635
6636   if (V1IsUndef && V2IsUndef)
6637     return DAG.getUNDEF(VT);
6638
6639   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6640
6641   // Vector shuffle lowering takes 3 steps:
6642   //
6643   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6644   //    narrowing and commutation of operands should be handled.
6645   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6646   //    shuffle nodes.
6647   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6648   //    so the shuffle can be broken into other shuffles and the legalizer can
6649   //    try the lowering again.
6650   //
6651   // The general idea is that no vector_shuffle operation should be left to
6652   // be matched during isel, all of them must be converted to a target specific
6653   // node here.
6654
6655   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6656   // narrowing and commutation of operands should be handled. The actual code
6657   // doesn't include all of those, work in progress...
6658   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6659   if (NewOp.getNode())
6660     return NewOp;
6661
6662   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6663
6664   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6665   // unpckh_undef). Only use pshufd if speed is more important than size.
6666   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6667     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6668   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6669     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6670
6671   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6672       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6673     return getMOVDDup(Op, dl, V1, DAG);
6674
6675   if (isMOVHLPS_v_undef_Mask(M, VT))
6676     return getMOVHighToLow(Op, dl, DAG);
6677
6678   // Use to match splats
6679   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6680       (VT == MVT::v2f64 || VT == MVT::v2i64))
6681     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6682
6683   if (isPSHUFDMask(M, VT)) {
6684     // The actual implementation will match the mask in the if above and then
6685     // during isel it can match several different instructions, not only pshufd
6686     // as its name says, sad but true, emulate the behavior for now...
6687     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6688       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6689
6690     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6691
6692     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6693       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6694
6695     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6696       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6697
6698     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6699                                 TargetMask, DAG);
6700   }
6701
6702   // Check if this can be converted into a logical shift.
6703   bool isLeft = false;
6704   unsigned ShAmt = 0;
6705   SDValue ShVal;
6706   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6707   if (isShift && ShVal.hasOneUse()) {
6708     // If the shifted value has multiple uses, it may be cheaper to use
6709     // v_set0 + movlhps or movhlps, etc.
6710     EVT EltVT = VT.getVectorElementType();
6711     ShAmt *= EltVT.getSizeInBits();
6712     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6713   }
6714
6715   if (isMOVLMask(M, VT)) {
6716     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6717       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6718     if (!isMOVLPMask(M, VT)) {
6719       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6720         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6721
6722       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6723         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6724     }
6725   }
6726
6727   // FIXME: fold these into legal mask.
6728   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6729     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6730
6731   if (isMOVHLPSMask(M, VT))
6732     return getMOVHighToLow(Op, dl, DAG);
6733
6734   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6735     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6736
6737   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6738     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6739
6740   if (isMOVLPMask(M, VT))
6741     return getMOVLP(Op, dl, DAG, HasSSE2);
6742
6743   if (ShouldXformToMOVHLPS(M, VT) ||
6744       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6745     return CommuteVectorShuffle(SVOp, DAG);
6746
6747   if (isShift) {
6748     // No better options. Use a vshldq / vsrldq.
6749     EVT EltVT = VT.getVectorElementType();
6750     ShAmt *= EltVT.getSizeInBits();
6751     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6752   }
6753
6754   bool Commuted = false;
6755   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6756   // 1,1,1,1 -> v8i16 though.
6757   V1IsSplat = isSplatVector(V1.getNode());
6758   V2IsSplat = isSplatVector(V2.getNode());
6759
6760   // Canonicalize the splat or undef, if present, to be on the RHS.
6761   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6762     CommuteVectorShuffleMask(M, NumElems);
6763     std::swap(V1, V2);
6764     std::swap(V1IsSplat, V2IsSplat);
6765     Commuted = true;
6766   }
6767
6768   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6769     // Shuffling low element of v1 into undef, just return v1.
6770     if (V2IsUndef)
6771       return V1;
6772     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6773     // the instruction selector will not match, so get a canonical MOVL with
6774     // swapped operands to undo the commute.
6775     return getMOVL(DAG, dl, VT, V2, V1);
6776   }
6777
6778   if (isUNPCKLMask(M, VT, HasAVX2))
6779     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6780
6781   if (isUNPCKHMask(M, VT, HasAVX2))
6782     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6783
6784   if (V2IsSplat) {
6785     // Normalize mask so all entries that point to V2 points to its first
6786     // element then try to match unpck{h|l} again. If match, return a
6787     // new vector_shuffle with the corrected mask.p
6788     SmallVector<int, 8> NewMask(M.begin(), M.end());
6789     NormalizeMask(NewMask, NumElems);
6790     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6791       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6792     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6793       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6794   }
6795
6796   if (Commuted) {
6797     // Commute is back and try unpck* again.
6798     // FIXME: this seems wrong.
6799     CommuteVectorShuffleMask(M, NumElems);
6800     std::swap(V1, V2);
6801     std::swap(V1IsSplat, V2IsSplat);
6802     Commuted = false;
6803
6804     if (isUNPCKLMask(M, VT, HasAVX2))
6805       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6806
6807     if (isUNPCKHMask(M, VT, HasAVX2))
6808       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6809   }
6810
6811   // Normalize the node to match x86 shuffle ops if needed
6812   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6813     return CommuteVectorShuffle(SVOp, DAG);
6814
6815   // The checks below are all present in isShuffleMaskLegal, but they are
6816   // inlined here right now to enable us to directly emit target specific
6817   // nodes, and remove one by one until they don't return Op anymore.
6818
6819   if (isPALIGNRMask(M, VT, Subtarget))
6820     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6821                                 getShufflePALIGNRImmediate(SVOp),
6822                                 DAG);
6823
6824   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6825       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6826     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6827       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6828   }
6829
6830   if (isPSHUFHWMask(M, VT, HasAVX2))
6831     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6832                                 getShufflePSHUFHWImmediate(SVOp),
6833                                 DAG);
6834
6835   if (isPSHUFLWMask(M, VT, HasAVX2))
6836     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6837                                 getShufflePSHUFLWImmediate(SVOp),
6838                                 DAG);
6839
6840   if (isSHUFPMask(M, VT, HasAVX))
6841     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6842                                 getShuffleSHUFImmediate(SVOp), DAG);
6843
6844   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6845     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6846   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6847     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6848
6849   //===--------------------------------------------------------------------===//
6850   // Generate target specific nodes for 128 or 256-bit shuffles only
6851   // supported in the AVX instruction set.
6852   //
6853
6854   // Handle VMOVDDUPY permutations
6855   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6856     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6857
6858   // Handle VPERMILPS/D* permutations
6859   if (isVPERMILPMask(M, VT, HasAVX)) {
6860     if (HasAVX2 && VT == MVT::v8i32)
6861       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6862                                   getShuffleSHUFImmediate(SVOp), DAG);
6863     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6864                                 getShuffleSHUFImmediate(SVOp), DAG);
6865   }
6866
6867   // Handle VPERM2F128/VPERM2I128 permutations
6868   if (isVPERM2X128Mask(M, VT, HasAVX))
6869     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6870                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6871
6872   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6873   if (BlendOp.getNode())
6874     return BlendOp;
6875
6876   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6877     SmallVector<SDValue, 8> permclMask;
6878     for (unsigned i = 0; i != 8; ++i) {
6879       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6880     }
6881     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6882                                &permclMask[0], 8);
6883     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6884     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6885                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6886   }
6887
6888   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6889     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6890                                 getShuffleCLImmediate(SVOp), DAG);
6891
6892
6893   //===--------------------------------------------------------------------===//
6894   // Since no target specific shuffle was selected for this generic one,
6895   // lower it into other known shuffles. FIXME: this isn't true yet, but
6896   // this is the plan.
6897   //
6898
6899   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6900   if (VT == MVT::v8i16) {
6901     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6902     if (NewOp.getNode())
6903       return NewOp;
6904   }
6905
6906   if (VT == MVT::v16i8) {
6907     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6908     if (NewOp.getNode())
6909       return NewOp;
6910   }
6911
6912   if (VT == MVT::v32i8) {
6913     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6914     if (NewOp.getNode())
6915       return NewOp;
6916   }
6917
6918   // Handle all 128-bit wide vectors with 4 elements, and match them with
6919   // several different shuffle types.
6920   if (NumElems == 4 && VT.is128BitVector())
6921     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6922
6923   // Handle general 256-bit shuffles
6924   if (VT.is256BitVector())
6925     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6926
6927   return SDValue();
6928 }
6929
6930 SDValue
6931 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6932                                                 SelectionDAG &DAG) const {
6933   EVT VT = Op.getValueType();
6934   DebugLoc dl = Op.getDebugLoc();
6935
6936   if (!Op.getOperand(0).getValueType().is128BitVector())
6937     return SDValue();
6938
6939   if (VT.getSizeInBits() == 8) {
6940     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6941                                   Op.getOperand(0), Op.getOperand(1));
6942     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6943                                   DAG.getValueType(VT));
6944     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6945   }
6946
6947   if (VT.getSizeInBits() == 16) {
6948     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6949     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6950     if (Idx == 0)
6951       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6952                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6953                                      DAG.getNode(ISD::BITCAST, dl,
6954                                                  MVT::v4i32,
6955                                                  Op.getOperand(0)),
6956                                      Op.getOperand(1)));
6957     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6958                                   Op.getOperand(0), Op.getOperand(1));
6959     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6960                                   DAG.getValueType(VT));
6961     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6962   }
6963
6964   if (VT == MVT::f32) {
6965     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6966     // the result back to FR32 register. It's only worth matching if the
6967     // result has a single use which is a store or a bitcast to i32.  And in
6968     // the case of a store, it's not worth it if the index is a constant 0,
6969     // because a MOVSSmr can be used instead, which is smaller and faster.
6970     if (!Op.hasOneUse())
6971       return SDValue();
6972     SDNode *User = *Op.getNode()->use_begin();
6973     if ((User->getOpcode() != ISD::STORE ||
6974          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6975           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6976         (User->getOpcode() != ISD::BITCAST ||
6977          User->getValueType(0) != MVT::i32))
6978       return SDValue();
6979     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6980                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6981                                               Op.getOperand(0)),
6982                                               Op.getOperand(1));
6983     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6984   }
6985
6986   if (VT == MVT::i32 || VT == MVT::i64) {
6987     // ExtractPS/pextrq works with constant index.
6988     if (isa<ConstantSDNode>(Op.getOperand(1)))
6989       return Op;
6990   }
6991   return SDValue();
6992 }
6993
6994
6995 SDValue
6996 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6997                                            SelectionDAG &DAG) const {
6998   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6999     return SDValue();
7000
7001   SDValue Vec = Op.getOperand(0);
7002   EVT VecVT = Vec.getValueType();
7003
7004   // If this is a 256-bit vector result, first extract the 128-bit vector and
7005   // then extract the element from the 128-bit vector.
7006   if (VecVT.is256BitVector()) {
7007     DebugLoc dl = Op.getNode()->getDebugLoc();
7008     unsigned NumElems = VecVT.getVectorNumElements();
7009     SDValue Idx = Op.getOperand(1);
7010     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7011
7012     // Get the 128-bit vector.
7013     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7014
7015     if (IdxVal >= NumElems/2)
7016       IdxVal -= NumElems/2;
7017     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7018                        DAG.getConstant(IdxVal, MVT::i32));
7019   }
7020
7021   assert(VecVT.is128BitVector() && "Unexpected vector length");
7022
7023   if (Subtarget->hasSSE41()) {
7024     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7025     if (Res.getNode())
7026       return Res;
7027   }
7028
7029   EVT VT = Op.getValueType();
7030   DebugLoc dl = Op.getDebugLoc();
7031   // TODO: handle v16i8.
7032   if (VT.getSizeInBits() == 16) {
7033     SDValue Vec = Op.getOperand(0);
7034     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7035     if (Idx == 0)
7036       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7037                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7038                                      DAG.getNode(ISD::BITCAST, dl,
7039                                                  MVT::v4i32, Vec),
7040                                      Op.getOperand(1)));
7041     // Transform it so it match pextrw which produces a 32-bit result.
7042     EVT EltVT = MVT::i32;
7043     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7044                                   Op.getOperand(0), Op.getOperand(1));
7045     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7046                                   DAG.getValueType(VT));
7047     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7048   }
7049
7050   if (VT.getSizeInBits() == 32) {
7051     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7052     if (Idx == 0)
7053       return Op;
7054
7055     // SHUFPS the element to the lowest double word, then movss.
7056     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7057     EVT VVT = Op.getOperand(0).getValueType();
7058     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7059                                        DAG.getUNDEF(VVT), Mask);
7060     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7061                        DAG.getIntPtrConstant(0));
7062   }
7063
7064   if (VT.getSizeInBits() == 64) {
7065     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7066     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7067     //        to match extract_elt for f64.
7068     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7069     if (Idx == 0)
7070       return Op;
7071
7072     // UNPCKHPD the element to the lowest double word, then movsd.
7073     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7074     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7075     int Mask[2] = { 1, -1 };
7076     EVT VVT = Op.getOperand(0).getValueType();
7077     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7078                                        DAG.getUNDEF(VVT), Mask);
7079     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7080                        DAG.getIntPtrConstant(0));
7081   }
7082
7083   return SDValue();
7084 }
7085
7086 SDValue
7087 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7088                                                SelectionDAG &DAG) const {
7089   EVT VT = Op.getValueType();
7090   EVT EltVT = VT.getVectorElementType();
7091   DebugLoc dl = Op.getDebugLoc();
7092
7093   SDValue N0 = Op.getOperand(0);
7094   SDValue N1 = Op.getOperand(1);
7095   SDValue N2 = Op.getOperand(2);
7096
7097   if (!VT.is128BitVector())
7098     return SDValue();
7099
7100   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7101       isa<ConstantSDNode>(N2)) {
7102     unsigned Opc;
7103     if (VT == MVT::v8i16)
7104       Opc = X86ISD::PINSRW;
7105     else if (VT == MVT::v16i8)
7106       Opc = X86ISD::PINSRB;
7107     else
7108       Opc = X86ISD::PINSRB;
7109
7110     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7111     // argument.
7112     if (N1.getValueType() != MVT::i32)
7113       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7114     if (N2.getValueType() != MVT::i32)
7115       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7116     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7117   }
7118
7119   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7120     // Bits [7:6] of the constant are the source select.  This will always be
7121     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7122     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7123     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7124     // Bits [5:4] of the constant are the destination select.  This is the
7125     //  value of the incoming immediate.
7126     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7127     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7128     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7129     // Create this as a scalar to vector..
7130     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7131     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7132   }
7133
7134   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7135     // PINSR* works with constant index.
7136     return Op;
7137   }
7138   return SDValue();
7139 }
7140
7141 SDValue
7142 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7143   EVT VT = Op.getValueType();
7144   EVT EltVT = VT.getVectorElementType();
7145
7146   DebugLoc dl = Op.getDebugLoc();
7147   SDValue N0 = Op.getOperand(0);
7148   SDValue N1 = Op.getOperand(1);
7149   SDValue N2 = Op.getOperand(2);
7150
7151   // If this is a 256-bit vector result, first extract the 128-bit vector,
7152   // insert the element into the extracted half and then place it back.
7153   if (VT.is256BitVector()) {
7154     if (!isa<ConstantSDNode>(N2))
7155       return SDValue();
7156
7157     // Get the desired 128-bit vector half.
7158     unsigned NumElems = VT.getVectorNumElements();
7159     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7160     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7161
7162     // Insert the element into the desired half.
7163     bool Upper = IdxVal >= NumElems/2;
7164     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7165                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7166
7167     // Insert the changed part back to the 256-bit vector
7168     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7169   }
7170
7171   if (Subtarget->hasSSE41())
7172     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7173
7174   if (EltVT == MVT::i8)
7175     return SDValue();
7176
7177   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7178     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7179     // as its second argument.
7180     if (N1.getValueType() != MVT::i32)
7181       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7182     if (N2.getValueType() != MVT::i32)
7183       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7184     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7185   }
7186   return SDValue();
7187 }
7188
7189 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7190   LLVMContext *Context = DAG.getContext();
7191   DebugLoc dl = Op.getDebugLoc();
7192   EVT OpVT = Op.getValueType();
7193
7194   // If this is a 256-bit vector result, first insert into a 128-bit
7195   // vector and then insert into the 256-bit vector.
7196   if (!OpVT.is128BitVector()) {
7197     // Insert into a 128-bit vector.
7198     EVT VT128 = EVT::getVectorVT(*Context,
7199                                  OpVT.getVectorElementType(),
7200                                  OpVT.getVectorNumElements() / 2);
7201
7202     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7203
7204     // Insert the 128-bit vector.
7205     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7206   }
7207
7208   if (OpVT == MVT::v1i64 &&
7209       Op.getOperand(0).getValueType() == MVT::i64)
7210     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7211
7212   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7213   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7214   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7215                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7216 }
7217
7218 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7219 // a simple subregister reference or explicit instructions to grab
7220 // upper bits of a vector.
7221 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7222                                       SelectionDAG &DAG) {
7223   if (Subtarget->hasAVX()) {
7224     DebugLoc dl = Op.getNode()->getDebugLoc();
7225     SDValue Vec = Op.getNode()->getOperand(0);
7226     SDValue Idx = Op.getNode()->getOperand(1);
7227
7228     if (Op.getNode()->getValueType(0).is128BitVector() &&
7229         Vec.getNode()->getValueType(0).is256BitVector() &&
7230         isa<ConstantSDNode>(Idx)) {
7231       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7232       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7233     }
7234   }
7235   return SDValue();
7236 }
7237
7238 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7239 // simple superregister reference or explicit instructions to insert
7240 // the upper bits of a vector.
7241 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7242                                      SelectionDAG &DAG) {
7243   if (Subtarget->hasAVX()) {
7244     DebugLoc dl = Op.getNode()->getDebugLoc();
7245     SDValue Vec = Op.getNode()->getOperand(0);
7246     SDValue SubVec = Op.getNode()->getOperand(1);
7247     SDValue Idx = Op.getNode()->getOperand(2);
7248
7249     if (Op.getNode()->getValueType(0).is256BitVector() &&
7250         SubVec.getNode()->getValueType(0).is128BitVector() &&
7251         isa<ConstantSDNode>(Idx)) {
7252       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7253       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7254     }
7255   }
7256   return SDValue();
7257 }
7258
7259 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7260 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7261 // one of the above mentioned nodes. It has to be wrapped because otherwise
7262 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7263 // be used to form addressing mode. These wrapped nodes will be selected
7264 // into MOV32ri.
7265 SDValue
7266 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7267   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7268
7269   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7270   // global base reg.
7271   unsigned char OpFlag = 0;
7272   unsigned WrapperKind = X86ISD::Wrapper;
7273   CodeModel::Model M = getTargetMachine().getCodeModel();
7274
7275   if (Subtarget->isPICStyleRIPRel() &&
7276       (M == CodeModel::Small || M == CodeModel::Kernel))
7277     WrapperKind = X86ISD::WrapperRIP;
7278   else if (Subtarget->isPICStyleGOT())
7279     OpFlag = X86II::MO_GOTOFF;
7280   else if (Subtarget->isPICStyleStubPIC())
7281     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7282
7283   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7284                                              CP->getAlignment(),
7285                                              CP->getOffset(), OpFlag);
7286   DebugLoc DL = CP->getDebugLoc();
7287   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7288   // With PIC, the address is actually $g + Offset.
7289   if (OpFlag) {
7290     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7291                          DAG.getNode(X86ISD::GlobalBaseReg,
7292                                      DebugLoc(), getPointerTy()),
7293                          Result);
7294   }
7295
7296   return Result;
7297 }
7298
7299 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7300   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7301
7302   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7303   // global base reg.
7304   unsigned char OpFlag = 0;
7305   unsigned WrapperKind = X86ISD::Wrapper;
7306   CodeModel::Model M = getTargetMachine().getCodeModel();
7307
7308   if (Subtarget->isPICStyleRIPRel() &&
7309       (M == CodeModel::Small || M == CodeModel::Kernel))
7310     WrapperKind = X86ISD::WrapperRIP;
7311   else if (Subtarget->isPICStyleGOT())
7312     OpFlag = X86II::MO_GOTOFF;
7313   else if (Subtarget->isPICStyleStubPIC())
7314     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7315
7316   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7317                                           OpFlag);
7318   DebugLoc DL = JT->getDebugLoc();
7319   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7320
7321   // With PIC, the address is actually $g + Offset.
7322   if (OpFlag)
7323     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7324                          DAG.getNode(X86ISD::GlobalBaseReg,
7325                                      DebugLoc(), getPointerTy()),
7326                          Result);
7327
7328   return Result;
7329 }
7330
7331 SDValue
7332 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7333   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7334
7335   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7336   // global base reg.
7337   unsigned char OpFlag = 0;
7338   unsigned WrapperKind = X86ISD::Wrapper;
7339   CodeModel::Model M = getTargetMachine().getCodeModel();
7340
7341   if (Subtarget->isPICStyleRIPRel() &&
7342       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7343     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7344       OpFlag = X86II::MO_GOTPCREL;
7345     WrapperKind = X86ISD::WrapperRIP;
7346   } else if (Subtarget->isPICStyleGOT()) {
7347     OpFlag = X86II::MO_GOT;
7348   } else if (Subtarget->isPICStyleStubPIC()) {
7349     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7350   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7351     OpFlag = X86II::MO_DARWIN_NONLAZY;
7352   }
7353
7354   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7355
7356   DebugLoc DL = Op.getDebugLoc();
7357   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7358
7359
7360   // With PIC, the address is actually $g + Offset.
7361   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7362       !Subtarget->is64Bit()) {
7363     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7364                          DAG.getNode(X86ISD::GlobalBaseReg,
7365                                      DebugLoc(), getPointerTy()),
7366                          Result);
7367   }
7368
7369   // For symbols that require a load from a stub to get the address, emit the
7370   // load.
7371   if (isGlobalStubReference(OpFlag))
7372     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7373                          MachinePointerInfo::getGOT(), false, false, false, 0);
7374
7375   return Result;
7376 }
7377
7378 SDValue
7379 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7380   // Create the TargetBlockAddressAddress node.
7381   unsigned char OpFlags =
7382     Subtarget->ClassifyBlockAddressReference();
7383   CodeModel::Model M = getTargetMachine().getCodeModel();
7384   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7385   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7386   DebugLoc dl = Op.getDebugLoc();
7387   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7388                                              OpFlags);
7389
7390   if (Subtarget->isPICStyleRIPRel() &&
7391       (M == CodeModel::Small || M == CodeModel::Kernel))
7392     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7393   else
7394     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7395
7396   // With PIC, the address is actually $g + Offset.
7397   if (isGlobalRelativeToPICBase(OpFlags)) {
7398     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7399                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7400                          Result);
7401   }
7402
7403   return Result;
7404 }
7405
7406 SDValue
7407 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7408                                       int64_t Offset,
7409                                       SelectionDAG &DAG) const {
7410   // Create the TargetGlobalAddress node, folding in the constant
7411   // offset if it is legal.
7412   unsigned char OpFlags =
7413     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7414   CodeModel::Model M = getTargetMachine().getCodeModel();
7415   SDValue Result;
7416   if (OpFlags == X86II::MO_NO_FLAG &&
7417       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7418     // A direct static reference to a global.
7419     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7420     Offset = 0;
7421   } else {
7422     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7423   }
7424
7425   if (Subtarget->isPICStyleRIPRel() &&
7426       (M == CodeModel::Small || M == CodeModel::Kernel))
7427     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7428   else
7429     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7430
7431   // With PIC, the address is actually $g + Offset.
7432   if (isGlobalRelativeToPICBase(OpFlags)) {
7433     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7434                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7435                          Result);
7436   }
7437
7438   // For globals that require a load from a stub to get the address, emit the
7439   // load.
7440   if (isGlobalStubReference(OpFlags))
7441     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7442                          MachinePointerInfo::getGOT(), false, false, false, 0);
7443
7444   // If there was a non-zero offset that we didn't fold, create an explicit
7445   // addition for it.
7446   if (Offset != 0)
7447     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7448                          DAG.getConstant(Offset, getPointerTy()));
7449
7450   return Result;
7451 }
7452
7453 SDValue
7454 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7455   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7456   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7457   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7458 }
7459
7460 static SDValue
7461 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7462            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7463            unsigned char OperandFlags, bool LocalDynamic = false) {
7464   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7465   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7466   DebugLoc dl = GA->getDebugLoc();
7467   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7468                                            GA->getValueType(0),
7469                                            GA->getOffset(),
7470                                            OperandFlags);
7471
7472   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7473                                            : X86ISD::TLSADDR;
7474
7475   if (InFlag) {
7476     SDValue Ops[] = { Chain,  TGA, *InFlag };
7477     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7478   } else {
7479     SDValue Ops[]  = { Chain, TGA };
7480     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7481   }
7482
7483   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7484   MFI->setAdjustsStack(true);
7485
7486   SDValue Flag = Chain.getValue(1);
7487   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7488 }
7489
7490 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7491 static SDValue
7492 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7493                                 const EVT PtrVT) {
7494   SDValue InFlag;
7495   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7496   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7497                                    DAG.getNode(X86ISD::GlobalBaseReg,
7498                                                DebugLoc(), PtrVT), InFlag);
7499   InFlag = Chain.getValue(1);
7500
7501   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7502 }
7503
7504 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7505 static SDValue
7506 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7507                                 const EVT PtrVT) {
7508   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7509                     X86::RAX, X86II::MO_TLSGD);
7510 }
7511
7512 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7513                                            SelectionDAG &DAG,
7514                                            const EVT PtrVT,
7515                                            bool is64Bit) {
7516   DebugLoc dl = GA->getDebugLoc();
7517
7518   // Get the start address of the TLS block for this module.
7519   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7520       .getInfo<X86MachineFunctionInfo>();
7521   MFI->incNumLocalDynamicTLSAccesses();
7522
7523   SDValue Base;
7524   if (is64Bit) {
7525     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7526                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7527   } else {
7528     SDValue InFlag;
7529     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7530         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7531     InFlag = Chain.getValue(1);
7532     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7533                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7534   }
7535
7536   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7537   // of Base.
7538
7539   // Build x@dtpoff.
7540   unsigned char OperandFlags = X86II::MO_DTPOFF;
7541   unsigned WrapperKind = X86ISD::Wrapper;
7542   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7543                                            GA->getValueType(0),
7544                                            GA->getOffset(), OperandFlags);
7545   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7546
7547   // Add x@dtpoff with the base.
7548   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7549 }
7550
7551 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7552 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7553                                    const EVT PtrVT, TLSModel::Model model,
7554                                    bool is64Bit, bool isPIC) {
7555   DebugLoc dl = GA->getDebugLoc();
7556
7557   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7558   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7559                                                          is64Bit ? 257 : 256));
7560
7561   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7562                                       DAG.getIntPtrConstant(0),
7563                                       MachinePointerInfo(Ptr),
7564                                       false, false, false, 0);
7565
7566   unsigned char OperandFlags = 0;
7567   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7568   // initialexec.
7569   unsigned WrapperKind = X86ISD::Wrapper;
7570   if (model == TLSModel::LocalExec) {
7571     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7572   } else if (model == TLSModel::InitialExec) {
7573     if (is64Bit) {
7574       OperandFlags = X86II::MO_GOTTPOFF;
7575       WrapperKind = X86ISD::WrapperRIP;
7576     } else {
7577       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7578     }
7579   } else {
7580     llvm_unreachable("Unexpected model");
7581   }
7582
7583   // emit "addl x@ntpoff,%eax" (local exec)
7584   // or "addl x@indntpoff,%eax" (initial exec)
7585   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7586   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7587                                            GA->getValueType(0),
7588                                            GA->getOffset(), OperandFlags);
7589   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7590
7591   if (model == TLSModel::InitialExec) {
7592     if (isPIC && !is64Bit) {
7593       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7594                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7595                            Offset);
7596     }
7597
7598     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7599                          MachinePointerInfo::getGOT(), false, false, false,
7600                          0);
7601   }
7602
7603   // The address of the thread local variable is the add of the thread
7604   // pointer with the offset of the variable.
7605   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7606 }
7607
7608 SDValue
7609 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7610
7611   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7612   const GlobalValue *GV = GA->getGlobal();
7613
7614   if (Subtarget->isTargetELF()) {
7615     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7616
7617     switch (model) {
7618       case TLSModel::GeneralDynamic:
7619         if (Subtarget->is64Bit())
7620           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7621         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7622       case TLSModel::LocalDynamic:
7623         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7624                                            Subtarget->is64Bit());
7625       case TLSModel::InitialExec:
7626       case TLSModel::LocalExec:
7627         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7628                                    Subtarget->is64Bit(),
7629                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7630     }
7631     llvm_unreachable("Unknown TLS model.");
7632   }
7633
7634   if (Subtarget->isTargetDarwin()) {
7635     // Darwin only has one model of TLS.  Lower to that.
7636     unsigned char OpFlag = 0;
7637     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7638                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7639
7640     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7641     // global base reg.
7642     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7643                   !Subtarget->is64Bit();
7644     if (PIC32)
7645       OpFlag = X86II::MO_TLVP_PIC_BASE;
7646     else
7647       OpFlag = X86II::MO_TLVP;
7648     DebugLoc DL = Op.getDebugLoc();
7649     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7650                                                 GA->getValueType(0),
7651                                                 GA->getOffset(), OpFlag);
7652     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7653
7654     // With PIC32, the address is actually $g + Offset.
7655     if (PIC32)
7656       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7657                            DAG.getNode(X86ISD::GlobalBaseReg,
7658                                        DebugLoc(), getPointerTy()),
7659                            Offset);
7660
7661     // Lowering the machine isd will make sure everything is in the right
7662     // location.
7663     SDValue Chain = DAG.getEntryNode();
7664     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7665     SDValue Args[] = { Chain, Offset };
7666     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7667
7668     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7669     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7670     MFI->setAdjustsStack(true);
7671
7672     // And our return value (tls address) is in the standard call return value
7673     // location.
7674     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7675     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7676                               Chain.getValue(1));
7677   }
7678
7679   if (Subtarget->isTargetWindows()) {
7680     // Just use the implicit TLS architecture
7681     // Need to generate someting similar to:
7682     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7683     //                                  ; from TEB
7684     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7685     //   mov     rcx, qword [rdx+rcx*8]
7686     //   mov     eax, .tls$:tlsvar
7687     //   [rax+rcx] contains the address
7688     // Windows 64bit: gs:0x58
7689     // Windows 32bit: fs:__tls_array
7690
7691     // If GV is an alias then use the aliasee for determining
7692     // thread-localness.
7693     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7694       GV = GA->resolveAliasedGlobal(false);
7695     DebugLoc dl = GA->getDebugLoc();
7696     SDValue Chain = DAG.getEntryNode();
7697
7698     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7699     // %gs:0x58 (64-bit).
7700     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7701                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7702                                                              256)
7703                                         : Type::getInt32PtrTy(*DAG.getContext(),
7704                                                               257));
7705
7706     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7707                                         Subtarget->is64Bit()
7708                                         ? DAG.getIntPtrConstant(0x58)
7709                                         : DAG.getExternalSymbol("_tls_array",
7710                                                                 getPointerTy()),
7711                                         MachinePointerInfo(Ptr),
7712                                         false, false, false, 0);
7713
7714     // Load the _tls_index variable
7715     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7716     if (Subtarget->is64Bit())
7717       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7718                            IDX, MachinePointerInfo(), MVT::i32,
7719                            false, false, 0);
7720     else
7721       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7722                         false, false, false, 0);
7723
7724     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7725                                     getPointerTy());
7726     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7727
7728     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7729     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7730                       false, false, false, 0);
7731
7732     // Get the offset of start of .tls section
7733     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7734                                              GA->getValueType(0),
7735                                              GA->getOffset(), X86II::MO_SECREL);
7736     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7737
7738     // The address of the thread local variable is the add of the thread
7739     // pointer with the offset of the variable.
7740     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7741   }
7742
7743   llvm_unreachable("TLS not implemented for this target.");
7744 }
7745
7746
7747 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7748 /// and take a 2 x i32 value to shift plus a shift amount.
7749 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7750   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7751   EVT VT = Op.getValueType();
7752   unsigned VTBits = VT.getSizeInBits();
7753   DebugLoc dl = Op.getDebugLoc();
7754   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7755   SDValue ShOpLo = Op.getOperand(0);
7756   SDValue ShOpHi = Op.getOperand(1);
7757   SDValue ShAmt  = Op.getOperand(2);
7758   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7759                                      DAG.getConstant(VTBits - 1, MVT::i8))
7760                        : DAG.getConstant(0, VT);
7761
7762   SDValue Tmp2, Tmp3;
7763   if (Op.getOpcode() == ISD::SHL_PARTS) {
7764     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7765     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7766   } else {
7767     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7768     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7769   }
7770
7771   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7772                                 DAG.getConstant(VTBits, MVT::i8));
7773   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7774                              AndNode, DAG.getConstant(0, MVT::i8));
7775
7776   SDValue Hi, Lo;
7777   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7778   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7779   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7780
7781   if (Op.getOpcode() == ISD::SHL_PARTS) {
7782     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7783     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7784   } else {
7785     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7786     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7787   }
7788
7789   SDValue Ops[2] = { Lo, Hi };
7790   return DAG.getMergeValues(Ops, 2, dl);
7791 }
7792
7793 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7794                                            SelectionDAG &DAG) const {
7795   EVT SrcVT = Op.getOperand(0).getValueType();
7796
7797   if (SrcVT.isVector())
7798     return SDValue();
7799
7800   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7801          "Unknown SINT_TO_FP to lower!");
7802
7803   // These are really Legal; return the operand so the caller accepts it as
7804   // Legal.
7805   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7806     return Op;
7807   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7808       Subtarget->is64Bit()) {
7809     return Op;
7810   }
7811
7812   DebugLoc dl = Op.getDebugLoc();
7813   unsigned Size = SrcVT.getSizeInBits()/8;
7814   MachineFunction &MF = DAG.getMachineFunction();
7815   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7816   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7817   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7818                                StackSlot,
7819                                MachinePointerInfo::getFixedStack(SSFI),
7820                                false, false, 0);
7821   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7822 }
7823
7824 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7825                                      SDValue StackSlot,
7826                                      SelectionDAG &DAG) const {
7827   // Build the FILD
7828   DebugLoc DL = Op.getDebugLoc();
7829   SDVTList Tys;
7830   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7831   if (useSSE)
7832     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7833   else
7834     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7835
7836   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7837
7838   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7839   MachineMemOperand *MMO;
7840   if (FI) {
7841     int SSFI = FI->getIndex();
7842     MMO =
7843       DAG.getMachineFunction()
7844       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7845                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7846   } else {
7847     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7848     StackSlot = StackSlot.getOperand(1);
7849   }
7850   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7851   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7852                                            X86ISD::FILD, DL,
7853                                            Tys, Ops, array_lengthof(Ops),
7854                                            SrcVT, MMO);
7855
7856   if (useSSE) {
7857     Chain = Result.getValue(1);
7858     SDValue InFlag = Result.getValue(2);
7859
7860     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7861     // shouldn't be necessary except that RFP cannot be live across
7862     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7863     MachineFunction &MF = DAG.getMachineFunction();
7864     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7865     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7866     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7867     Tys = DAG.getVTList(MVT::Other);
7868     SDValue Ops[] = {
7869       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7870     };
7871     MachineMemOperand *MMO =
7872       DAG.getMachineFunction()
7873       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7874                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7875
7876     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7877                                     Ops, array_lengthof(Ops),
7878                                     Op.getValueType(), MMO);
7879     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7880                          MachinePointerInfo::getFixedStack(SSFI),
7881                          false, false, false, 0);
7882   }
7883
7884   return Result;
7885 }
7886
7887 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7888 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7889                                                SelectionDAG &DAG) const {
7890   // This algorithm is not obvious. Here it is what we're trying to output:
7891   /*
7892      movq       %rax,  %xmm0
7893      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7894      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7895      #ifdef __SSE3__
7896        haddpd   %xmm0, %xmm0
7897      #else
7898        pshufd   $0x4e, %xmm0, %xmm1
7899        addpd    %xmm1, %xmm0
7900      #endif
7901   */
7902
7903   DebugLoc dl = Op.getDebugLoc();
7904   LLVMContext *Context = DAG.getContext();
7905
7906   // Build some magic constants.
7907   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7908   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7909   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7910
7911   SmallVector<Constant*,2> CV1;
7912   CV1.push_back(
7913         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7914   CV1.push_back(
7915         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7916   Constant *C1 = ConstantVector::get(CV1);
7917   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7918
7919   // Load the 64-bit value into an XMM register.
7920   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7921                             Op.getOperand(0));
7922   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7923                               MachinePointerInfo::getConstantPool(),
7924                               false, false, false, 16);
7925   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7926                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7927                               CLod0);
7928
7929   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7930                               MachinePointerInfo::getConstantPool(),
7931                               false, false, false, 16);
7932   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7933   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7934   SDValue Result;
7935
7936   if (Subtarget->hasSSE3()) {
7937     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7938     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7939   } else {
7940     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7941     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7942                                            S2F, 0x4E, DAG);
7943     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7944                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7945                          Sub);
7946   }
7947
7948   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7949                      DAG.getIntPtrConstant(0));
7950 }
7951
7952 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7953 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7954                                                SelectionDAG &DAG) const {
7955   DebugLoc dl = Op.getDebugLoc();
7956   // FP constant to bias correct the final result.
7957   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7958                                    MVT::f64);
7959
7960   // Load the 32-bit value into an XMM register.
7961   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7962                              Op.getOperand(0));
7963
7964   // Zero out the upper parts of the register.
7965   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7966
7967   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7968                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7969                      DAG.getIntPtrConstant(0));
7970
7971   // Or the load with the bias.
7972   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7973                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7974                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7975                                                    MVT::v2f64, Load)),
7976                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7977                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7978                                                    MVT::v2f64, Bias)));
7979   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7980                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7981                    DAG.getIntPtrConstant(0));
7982
7983   // Subtract the bias.
7984   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7985
7986   // Handle final rounding.
7987   EVT DestVT = Op.getValueType();
7988
7989   if (DestVT.bitsLT(MVT::f64))
7990     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7991                        DAG.getIntPtrConstant(0));
7992   if (DestVT.bitsGT(MVT::f64))
7993     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7994
7995   // Handle final rounding.
7996   return Sub;
7997 }
7998
7999 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8000                                            SelectionDAG &DAG) const {
8001   SDValue N0 = Op.getOperand(0);
8002   DebugLoc dl = Op.getDebugLoc();
8003
8004   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8005   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8006   // the optimization here.
8007   if (DAG.SignBitIsZero(N0))
8008     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8009
8010   EVT SrcVT = N0.getValueType();
8011   EVT DstVT = Op.getValueType();
8012   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8013     return LowerUINT_TO_FP_i64(Op, DAG);
8014   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8015     return LowerUINT_TO_FP_i32(Op, DAG);
8016   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8017     return SDValue();
8018
8019   // Make a 64-bit buffer, and use it to build an FILD.
8020   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8021   if (SrcVT == MVT::i32) {
8022     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8023     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8024                                      getPointerTy(), StackSlot, WordOff);
8025     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8026                                   StackSlot, MachinePointerInfo(),
8027                                   false, false, 0);
8028     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8029                                   OffsetSlot, MachinePointerInfo(),
8030                                   false, false, 0);
8031     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8032     return Fild;
8033   }
8034
8035   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8036   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8037                                StackSlot, MachinePointerInfo(),
8038                                false, false, 0);
8039   // For i64 source, we need to add the appropriate power of 2 if the input
8040   // was negative.  This is the same as the optimization in
8041   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8042   // we must be careful to do the computation in x87 extended precision, not
8043   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8044   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8045   MachineMemOperand *MMO =
8046     DAG.getMachineFunction()
8047     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8048                           MachineMemOperand::MOLoad, 8, 8);
8049
8050   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8051   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8052   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8053                                          MVT::i64, MMO);
8054
8055   APInt FF(32, 0x5F800000ULL);
8056
8057   // Check whether the sign bit is set.
8058   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8059                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8060                                  ISD::SETLT);
8061
8062   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8063   SDValue FudgePtr = DAG.getConstantPool(
8064                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8065                                          getPointerTy());
8066
8067   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8068   SDValue Zero = DAG.getIntPtrConstant(0);
8069   SDValue Four = DAG.getIntPtrConstant(4);
8070   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8071                                Zero, Four);
8072   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8073
8074   // Load the value out, extending it from f32 to f80.
8075   // FIXME: Avoid the extend by constructing the right constant pool?
8076   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8077                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8078                                  MVT::f32, false, false, 4);
8079   // Extend everything to 80 bits to force it to be done on x87.
8080   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8081   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8082 }
8083
8084 std::pair<SDValue,SDValue> X86TargetLowering::
8085 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8086   DebugLoc DL = Op.getDebugLoc();
8087
8088   EVT DstTy = Op.getValueType();
8089
8090   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8091     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8092     DstTy = MVT::i64;
8093   }
8094
8095   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8096          DstTy.getSimpleVT() >= MVT::i16 &&
8097          "Unknown FP_TO_INT to lower!");
8098
8099   // These are really Legal.
8100   if (DstTy == MVT::i32 &&
8101       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8102     return std::make_pair(SDValue(), SDValue());
8103   if (Subtarget->is64Bit() &&
8104       DstTy == MVT::i64 &&
8105       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8106     return std::make_pair(SDValue(), SDValue());
8107
8108   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8109   // stack slot, or into the FTOL runtime function.
8110   MachineFunction &MF = DAG.getMachineFunction();
8111   unsigned MemSize = DstTy.getSizeInBits()/8;
8112   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8113   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8114
8115   unsigned Opc;
8116   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8117     Opc = X86ISD::WIN_FTOL;
8118   else
8119     switch (DstTy.getSimpleVT().SimpleTy) {
8120     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8121     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8122     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8123     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8124     }
8125
8126   SDValue Chain = DAG.getEntryNode();
8127   SDValue Value = Op.getOperand(0);
8128   EVT TheVT = Op.getOperand(0).getValueType();
8129   // FIXME This causes a redundant load/store if the SSE-class value is already
8130   // in memory, such as if it is on the callstack.
8131   if (isScalarFPTypeInSSEReg(TheVT)) {
8132     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8133     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8134                          MachinePointerInfo::getFixedStack(SSFI),
8135                          false, false, 0);
8136     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8137     SDValue Ops[] = {
8138       Chain, StackSlot, DAG.getValueType(TheVT)
8139     };
8140
8141     MachineMemOperand *MMO =
8142       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8143                               MachineMemOperand::MOLoad, MemSize, MemSize);
8144     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8145                                     DstTy, MMO);
8146     Chain = Value.getValue(1);
8147     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8148     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8149   }
8150
8151   MachineMemOperand *MMO =
8152     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8153                             MachineMemOperand::MOStore, MemSize, MemSize);
8154
8155   if (Opc != X86ISD::WIN_FTOL) {
8156     // Build the FP_TO_INT*_IN_MEM
8157     SDValue Ops[] = { Chain, Value, StackSlot };
8158     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8159                                            Ops, 3, DstTy, MMO);
8160     return std::make_pair(FIST, StackSlot);
8161   } else {
8162     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8163       DAG.getVTList(MVT::Other, MVT::Glue),
8164       Chain, Value);
8165     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8166       MVT::i32, ftol.getValue(1));
8167     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8168       MVT::i32, eax.getValue(2));
8169     SDValue Ops[] = { eax, edx };
8170     SDValue pair = IsReplace
8171       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8172       : DAG.getMergeValues(Ops, 2, DL);
8173     return std::make_pair(pair, SDValue());
8174   }
8175 }
8176
8177 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8178                                            SelectionDAG &DAG) const {
8179   if (Op.getValueType().isVector())
8180     return SDValue();
8181
8182   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8183     /*IsSigned=*/ true, /*IsReplace=*/ false);
8184   SDValue FIST = Vals.first, StackSlot = Vals.second;
8185   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8186   if (FIST.getNode() == 0) return Op;
8187
8188   if (StackSlot.getNode())
8189     // Load the result.
8190     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8191                        FIST, StackSlot, MachinePointerInfo(),
8192                        false, false, false, 0);
8193
8194   // The node is the result.
8195   return FIST;
8196 }
8197
8198 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8199                                            SelectionDAG &DAG) const {
8200   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8201     /*IsSigned=*/ false, /*IsReplace=*/ false);
8202   SDValue FIST = Vals.first, StackSlot = Vals.second;
8203   assert(FIST.getNode() && "Unexpected failure");
8204
8205   if (StackSlot.getNode())
8206     // Load the result.
8207     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8208                        FIST, StackSlot, MachinePointerInfo(),
8209                        false, false, false, 0);
8210
8211   // The node is the result.
8212   return FIST;
8213 }
8214
8215 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8216   LLVMContext *Context = DAG.getContext();
8217   DebugLoc dl = Op.getDebugLoc();
8218   EVT VT = Op.getValueType();
8219   EVT EltVT = VT;
8220   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8221   if (VT.isVector()) {
8222     EltVT = VT.getVectorElementType();
8223     NumElts = VT.getVectorNumElements();
8224   }
8225   Constant *C;
8226   if (EltVT == MVT::f64)
8227     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8228   else
8229     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8230   C = ConstantVector::getSplat(NumElts, C);
8231   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8232   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8233   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8234                              MachinePointerInfo::getConstantPool(),
8235                              false, false, false, Alignment);
8236   if (VT.isVector()) {
8237     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8238     return DAG.getNode(ISD::BITCAST, dl, VT,
8239                        DAG.getNode(ISD::AND, dl, ANDVT,
8240                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8241                                                Op.getOperand(0)),
8242                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8243   }
8244   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8245 }
8246
8247 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8248   LLVMContext *Context = DAG.getContext();
8249   DebugLoc dl = Op.getDebugLoc();
8250   EVT VT = Op.getValueType();
8251   EVT EltVT = VT;
8252   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8253   if (VT.isVector()) {
8254     EltVT = VT.getVectorElementType();
8255     NumElts = VT.getVectorNumElements();
8256   }
8257   Constant *C;
8258   if (EltVT == MVT::f64)
8259     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8260   else
8261     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8262   C = ConstantVector::getSplat(NumElts, C);
8263   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8264   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8265   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8266                              MachinePointerInfo::getConstantPool(),
8267                              false, false, false, Alignment);
8268   if (VT.isVector()) {
8269     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8270     return DAG.getNode(ISD::BITCAST, dl, VT,
8271                        DAG.getNode(ISD::XOR, dl, XORVT,
8272                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8273                                                Op.getOperand(0)),
8274                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8275   }
8276
8277   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8278 }
8279
8280 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8281   LLVMContext *Context = DAG.getContext();
8282   SDValue Op0 = Op.getOperand(0);
8283   SDValue Op1 = Op.getOperand(1);
8284   DebugLoc dl = Op.getDebugLoc();
8285   EVT VT = Op.getValueType();
8286   EVT SrcVT = Op1.getValueType();
8287
8288   // If second operand is smaller, extend it first.
8289   if (SrcVT.bitsLT(VT)) {
8290     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8291     SrcVT = VT;
8292   }
8293   // And if it is bigger, shrink it first.
8294   if (SrcVT.bitsGT(VT)) {
8295     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8296     SrcVT = VT;
8297   }
8298
8299   // At this point the operands and the result should have the same
8300   // type, and that won't be f80 since that is not custom lowered.
8301
8302   // First get the sign bit of second operand.
8303   SmallVector<Constant*,4> CV;
8304   if (SrcVT == MVT::f64) {
8305     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8306     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8307   } else {
8308     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8309     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8310     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8311     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8312   }
8313   Constant *C = ConstantVector::get(CV);
8314   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8315   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8316                               MachinePointerInfo::getConstantPool(),
8317                               false, false, false, 16);
8318   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8319
8320   // Shift sign bit right or left if the two operands have different types.
8321   if (SrcVT.bitsGT(VT)) {
8322     // Op0 is MVT::f32, Op1 is MVT::f64.
8323     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8324     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8325                           DAG.getConstant(32, MVT::i32));
8326     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8327     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8328                           DAG.getIntPtrConstant(0));
8329   }
8330
8331   // Clear first operand sign bit.
8332   CV.clear();
8333   if (VT == MVT::f64) {
8334     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8335     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8336   } else {
8337     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8338     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8339     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8340     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8341   }
8342   C = ConstantVector::get(CV);
8343   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8344   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8345                               MachinePointerInfo::getConstantPool(),
8346                               false, false, false, 16);
8347   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8348
8349   // Or the value with the sign bit.
8350   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8351 }
8352
8353 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8354   SDValue N0 = Op.getOperand(0);
8355   DebugLoc dl = Op.getDebugLoc();
8356   EVT VT = Op.getValueType();
8357
8358   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8359   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8360                                   DAG.getConstant(1, VT));
8361   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8362 }
8363
8364 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8365 //
8366 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8367   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8368
8369   if (!Subtarget->hasSSE41())
8370     return SDValue();
8371
8372   if (!Op->hasOneUse())
8373     return SDValue();
8374
8375   SDNode *N = Op.getNode();
8376   DebugLoc DL = N->getDebugLoc();
8377
8378   SmallVector<SDValue, 8> Opnds;
8379   DenseMap<SDValue, unsigned> VecInMap;
8380   EVT VT = MVT::Other;
8381
8382   // Recognize a special case where a vector is casted into wide integer to
8383   // test all 0s.
8384   Opnds.push_back(N->getOperand(0));
8385   Opnds.push_back(N->getOperand(1));
8386
8387   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8388     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8389     // BFS traverse all OR'd operands.
8390     if (I->getOpcode() == ISD::OR) {
8391       Opnds.push_back(I->getOperand(0));
8392       Opnds.push_back(I->getOperand(1));
8393       // Re-evaluate the number of nodes to be traversed.
8394       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8395       continue;
8396     }
8397
8398     // Quit if a non-EXTRACT_VECTOR_ELT
8399     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8400       return SDValue();
8401
8402     // Quit if without a constant index.
8403     SDValue Idx = I->getOperand(1);
8404     if (!isa<ConstantSDNode>(Idx))
8405       return SDValue();
8406
8407     SDValue ExtractedFromVec = I->getOperand(0);
8408     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8409     if (M == VecInMap.end()) {
8410       VT = ExtractedFromVec.getValueType();
8411       // Quit if not 128/256-bit vector.
8412       if (!VT.is128BitVector() && !VT.is256BitVector())
8413         return SDValue();
8414       // Quit if not the same type.
8415       if (VecInMap.begin() != VecInMap.end() &&
8416           VT != VecInMap.begin()->first.getValueType())
8417         return SDValue();
8418       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8419     }
8420     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8421   }
8422
8423   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8424          "Not extracted from 128-/256-bit vector.");
8425
8426   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8427   SmallVector<SDValue, 8> VecIns;
8428
8429   for (DenseMap<SDValue, unsigned>::const_iterator
8430         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8431     // Quit if not all elements are used.
8432     if (I->second != FullMask)
8433       return SDValue();
8434     VecIns.push_back(I->first);
8435   }
8436
8437   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8438
8439   // Cast all vectors into TestVT for PTEST.
8440   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8441     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8442
8443   // If more than one full vectors are evaluated, OR them first before PTEST.
8444   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8445     // Each iteration will OR 2 nodes and append the result until there is only
8446     // 1 node left, i.e. the final OR'd value of all vectors.
8447     SDValue LHS = VecIns[Slot];
8448     SDValue RHS = VecIns[Slot + 1];
8449     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8450   }
8451
8452   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8453                      VecIns.back(), VecIns.back());
8454 }
8455
8456 /// Emit nodes that will be selected as "test Op0,Op0", or something
8457 /// equivalent.
8458 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8459                                     SelectionDAG &DAG) const {
8460   DebugLoc dl = Op.getDebugLoc();
8461
8462   // CF and OF aren't always set the way we want. Determine which
8463   // of these we need.
8464   bool NeedCF = false;
8465   bool NeedOF = false;
8466   switch (X86CC) {
8467   default: break;
8468   case X86::COND_A: case X86::COND_AE:
8469   case X86::COND_B: case X86::COND_BE:
8470     NeedCF = true;
8471     break;
8472   case X86::COND_G: case X86::COND_GE:
8473   case X86::COND_L: case X86::COND_LE:
8474   case X86::COND_O: case X86::COND_NO:
8475     NeedOF = true;
8476     break;
8477   }
8478
8479   // See if we can use the EFLAGS value from the operand instead of
8480   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8481   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8482   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8483     // Emit a CMP with 0, which is the TEST pattern.
8484     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8485                        DAG.getConstant(0, Op.getValueType()));
8486
8487   unsigned Opcode = 0;
8488   unsigned NumOperands = 0;
8489
8490   // Truncate operations may prevent the merge of the SETCC instruction
8491   // and the arithmetic intruction before it. Attempt to truncate the operands
8492   // of the arithmetic instruction and use a reduced bit-width instruction.
8493   bool NeedTruncation = false;
8494   SDValue ArithOp = Op;
8495   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8496     SDValue Arith = Op->getOperand(0);
8497     // Both the trunc and the arithmetic op need to have one user each.
8498     if (Arith->hasOneUse())
8499       switch (Arith.getOpcode()) {
8500         default: break;
8501         case ISD::ADD:
8502         case ISD::SUB:
8503         case ISD::AND:
8504         case ISD::OR:
8505         case ISD::XOR: {
8506           NeedTruncation = true;
8507           ArithOp = Arith;
8508         }
8509       }
8510   }
8511
8512   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8513   // which may be the result of a CAST.  We use the variable 'Op', which is the
8514   // non-casted variable when we check for possible users.
8515   switch (ArithOp.getOpcode()) {
8516   case ISD::ADD:
8517     // Due to an isel shortcoming, be conservative if this add is likely to be
8518     // selected as part of a load-modify-store instruction. When the root node
8519     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8520     // uses of other nodes in the match, such as the ADD in this case. This
8521     // leads to the ADD being left around and reselected, with the result being
8522     // two adds in the output.  Alas, even if none our users are stores, that
8523     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8524     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8525     // climbing the DAG back to the root, and it doesn't seem to be worth the
8526     // effort.
8527     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8528          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8529       if (UI->getOpcode() != ISD::CopyToReg &&
8530           UI->getOpcode() != ISD::SETCC &&
8531           UI->getOpcode() != ISD::STORE)
8532         goto default_case;
8533
8534     if (ConstantSDNode *C =
8535         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8536       // An add of one will be selected as an INC.
8537       if (C->getAPIntValue() == 1) {
8538         Opcode = X86ISD::INC;
8539         NumOperands = 1;
8540         break;
8541       }
8542
8543       // An add of negative one (subtract of one) will be selected as a DEC.
8544       if (C->getAPIntValue().isAllOnesValue()) {
8545         Opcode = X86ISD::DEC;
8546         NumOperands = 1;
8547         break;
8548       }
8549     }
8550
8551     // Otherwise use a regular EFLAGS-setting add.
8552     Opcode = X86ISD::ADD;
8553     NumOperands = 2;
8554     break;
8555   case ISD::AND: {
8556     // If the primary and result isn't used, don't bother using X86ISD::AND,
8557     // because a TEST instruction will be better.
8558     bool NonFlagUse = false;
8559     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8560            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8561       SDNode *User = *UI;
8562       unsigned UOpNo = UI.getOperandNo();
8563       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8564         // Look pass truncate.
8565         UOpNo = User->use_begin().getOperandNo();
8566         User = *User->use_begin();
8567       }
8568
8569       if (User->getOpcode() != ISD::BRCOND &&
8570           User->getOpcode() != ISD::SETCC &&
8571           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8572         NonFlagUse = true;
8573         break;
8574       }
8575     }
8576
8577     if (!NonFlagUse)
8578       break;
8579   }
8580     // FALL THROUGH
8581   case ISD::SUB:
8582   case ISD::OR:
8583   case ISD::XOR:
8584     // Due to the ISEL shortcoming noted above, be conservative if this op is
8585     // likely to be selected as part of a load-modify-store instruction.
8586     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8587            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8588       if (UI->getOpcode() == ISD::STORE)
8589         goto default_case;
8590
8591     // Otherwise use a regular EFLAGS-setting instruction.
8592     switch (ArithOp.getOpcode()) {
8593     default: llvm_unreachable("unexpected operator!");
8594     case ISD::SUB: Opcode = X86ISD::SUB; break;
8595     case ISD::XOR: Opcode = X86ISD::XOR; break;
8596     case ISD::AND: Opcode = X86ISD::AND; break;
8597     case ISD::OR: {
8598       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8599         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8600         if (EFLAGS.getNode())
8601           return EFLAGS;
8602       }
8603       Opcode = X86ISD::OR;
8604       break;
8605     }
8606     }
8607
8608     NumOperands = 2;
8609     break;
8610   case X86ISD::ADD:
8611   case X86ISD::SUB:
8612   case X86ISD::INC:
8613   case X86ISD::DEC:
8614   case X86ISD::OR:
8615   case X86ISD::XOR:
8616   case X86ISD::AND:
8617     return SDValue(Op.getNode(), 1);
8618   default:
8619   default_case:
8620     break;
8621   }
8622
8623   // If we found that truncation is beneficial, perform the truncation and
8624   // update 'Op'.
8625   if (NeedTruncation) {
8626     EVT VT = Op.getValueType();
8627     SDValue WideVal = Op->getOperand(0);
8628     EVT WideVT = WideVal.getValueType();
8629     unsigned ConvertedOp = 0;
8630     // Use a target machine opcode to prevent further DAGCombine
8631     // optimizations that may separate the arithmetic operations
8632     // from the setcc node.
8633     switch (WideVal.getOpcode()) {
8634       default: break;
8635       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8636       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8637       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8638       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8639       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8640     }
8641
8642     if (ConvertedOp) {
8643       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8644       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8645         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8646         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8647         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8648       }
8649     }
8650   }
8651
8652   if (Opcode == 0)
8653     // Emit a CMP with 0, which is the TEST pattern.
8654     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8655                        DAG.getConstant(0, Op.getValueType()));
8656
8657   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8658   SmallVector<SDValue, 4> Ops;
8659   for (unsigned i = 0; i != NumOperands; ++i)
8660     Ops.push_back(Op.getOperand(i));
8661
8662   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8663   DAG.ReplaceAllUsesWith(Op, New);
8664   return SDValue(New.getNode(), 1);
8665 }
8666
8667 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8668 /// equivalent.
8669 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8670                                    SelectionDAG &DAG) const {
8671   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8672     if (C->getAPIntValue() == 0)
8673       return EmitTest(Op0, X86CC, DAG);
8674
8675   DebugLoc dl = Op0.getDebugLoc();
8676   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8677        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8678     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8679     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8680     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8681                               Op0, Op1);
8682     return SDValue(Sub.getNode(), 1);
8683   }
8684   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8685 }
8686
8687 /// Convert a comparison if required by the subtarget.
8688 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8689                                                  SelectionDAG &DAG) const {
8690   // If the subtarget does not support the FUCOMI instruction, floating-point
8691   // comparisons have to be converted.
8692   if (Subtarget->hasCMov() ||
8693       Cmp.getOpcode() != X86ISD::CMP ||
8694       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8695       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8696     return Cmp;
8697
8698   // The instruction selector will select an FUCOM instruction instead of
8699   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8700   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8701   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8702   DebugLoc dl = Cmp.getDebugLoc();
8703   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8704   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8705   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8706                             DAG.getConstant(8, MVT::i8));
8707   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8708   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8709 }
8710
8711 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8712 /// if it's possible.
8713 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8714                                      DebugLoc dl, SelectionDAG &DAG) const {
8715   SDValue Op0 = And.getOperand(0);
8716   SDValue Op1 = And.getOperand(1);
8717   if (Op0.getOpcode() == ISD::TRUNCATE)
8718     Op0 = Op0.getOperand(0);
8719   if (Op1.getOpcode() == ISD::TRUNCATE)
8720     Op1 = Op1.getOperand(0);
8721
8722   SDValue LHS, RHS;
8723   if (Op1.getOpcode() == ISD::SHL)
8724     std::swap(Op0, Op1);
8725   if (Op0.getOpcode() == ISD::SHL) {
8726     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8727       if (And00C->getZExtValue() == 1) {
8728         // If we looked past a truncate, check that it's only truncating away
8729         // known zeros.
8730         unsigned BitWidth = Op0.getValueSizeInBits();
8731         unsigned AndBitWidth = And.getValueSizeInBits();
8732         if (BitWidth > AndBitWidth) {
8733           APInt Zeros, Ones;
8734           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8735           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8736             return SDValue();
8737         }
8738         LHS = Op1;
8739         RHS = Op0.getOperand(1);
8740       }
8741   } else if (Op1.getOpcode() == ISD::Constant) {
8742     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8743     uint64_t AndRHSVal = AndRHS->getZExtValue();
8744     SDValue AndLHS = Op0;
8745
8746     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8747       LHS = AndLHS.getOperand(0);
8748       RHS = AndLHS.getOperand(1);
8749     }
8750
8751     // Use BT if the immediate can't be encoded in a TEST instruction.
8752     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8753       LHS = AndLHS;
8754       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8755     }
8756   }
8757
8758   if (LHS.getNode()) {
8759     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8760     // instruction.  Since the shift amount is in-range-or-undefined, we know
8761     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8762     // the encoding for the i16 version is larger than the i32 version.
8763     // Also promote i16 to i32 for performance / code size reason.
8764     if (LHS.getValueType() == MVT::i8 ||
8765         LHS.getValueType() == MVT::i16)
8766       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8767
8768     // If the operand types disagree, extend the shift amount to match.  Since
8769     // BT ignores high bits (like shifts) we can use anyextend.
8770     if (LHS.getValueType() != RHS.getValueType())
8771       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8772
8773     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8774     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8775     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8776                        DAG.getConstant(Cond, MVT::i8), BT);
8777   }
8778
8779   return SDValue();
8780 }
8781
8782 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8783
8784   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8785
8786   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8787   SDValue Op0 = Op.getOperand(0);
8788   SDValue Op1 = Op.getOperand(1);
8789   DebugLoc dl = Op.getDebugLoc();
8790   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8791
8792   // Optimize to BT if possible.
8793   // Lower (X & (1 << N)) == 0 to BT(X, N).
8794   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8795   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8796   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8797       Op1.getOpcode() == ISD::Constant &&
8798       cast<ConstantSDNode>(Op1)->isNullValue() &&
8799       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8800     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8801     if (NewSetCC.getNode())
8802       return NewSetCC;
8803   }
8804
8805   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8806   // these.
8807   if (Op1.getOpcode() == ISD::Constant &&
8808       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8809        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8810       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8811
8812     // If the input is a setcc, then reuse the input setcc or use a new one with
8813     // the inverted condition.
8814     if (Op0.getOpcode() == X86ISD::SETCC) {
8815       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8816       bool Invert = (CC == ISD::SETNE) ^
8817         cast<ConstantSDNode>(Op1)->isNullValue();
8818       if (!Invert) return Op0;
8819
8820       CCode = X86::GetOppositeBranchCondition(CCode);
8821       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8822                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8823     }
8824   }
8825
8826   bool isFP = Op1.getValueType().isFloatingPoint();
8827   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8828   if (X86CC == X86::COND_INVALID)
8829     return SDValue();
8830
8831   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8832   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8833   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8834                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8835 }
8836
8837 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8838 // ones, and then concatenate the result back.
8839 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8840   EVT VT = Op.getValueType();
8841
8842   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8843          "Unsupported value type for operation");
8844
8845   unsigned NumElems = VT.getVectorNumElements();
8846   DebugLoc dl = Op.getDebugLoc();
8847   SDValue CC = Op.getOperand(2);
8848
8849   // Extract the LHS vectors
8850   SDValue LHS = Op.getOperand(0);
8851   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8852   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8853
8854   // Extract the RHS vectors
8855   SDValue RHS = Op.getOperand(1);
8856   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8857   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8858
8859   // Issue the operation on the smaller types and concatenate the result back
8860   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8861   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8862   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8863                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8864                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8865 }
8866
8867
8868 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8869   SDValue Cond;
8870   SDValue Op0 = Op.getOperand(0);
8871   SDValue Op1 = Op.getOperand(1);
8872   SDValue CC = Op.getOperand(2);
8873   EVT VT = Op.getValueType();
8874   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8875   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8876   DebugLoc dl = Op.getDebugLoc();
8877
8878   if (isFP) {
8879 #ifndef NDEBUG
8880     EVT EltVT = Op0.getValueType().getVectorElementType();
8881     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8882 #endif
8883
8884     unsigned SSECC;
8885     bool Swap = false;
8886
8887     // SSE Condition code mapping:
8888     //  0 - EQ
8889     //  1 - LT
8890     //  2 - LE
8891     //  3 - UNORD
8892     //  4 - NEQ
8893     //  5 - NLT
8894     //  6 - NLE
8895     //  7 - ORD
8896     switch (SetCCOpcode) {
8897     default: llvm_unreachable("Unexpected SETCC condition");
8898     case ISD::SETOEQ:
8899     case ISD::SETEQ:  SSECC = 0; break;
8900     case ISD::SETOGT:
8901     case ISD::SETGT: Swap = true; // Fallthrough
8902     case ISD::SETLT:
8903     case ISD::SETOLT: SSECC = 1; break;
8904     case ISD::SETOGE:
8905     case ISD::SETGE: Swap = true; // Fallthrough
8906     case ISD::SETLE:
8907     case ISD::SETOLE: SSECC = 2; break;
8908     case ISD::SETUO:  SSECC = 3; break;
8909     case ISD::SETUNE:
8910     case ISD::SETNE:  SSECC = 4; break;
8911     case ISD::SETULE: Swap = true; // Fallthrough
8912     case ISD::SETUGE: SSECC = 5; break;
8913     case ISD::SETULT: Swap = true; // Fallthrough
8914     case ISD::SETUGT: SSECC = 6; break;
8915     case ISD::SETO:   SSECC = 7; break;
8916     case ISD::SETUEQ:
8917     case ISD::SETONE: SSECC = 8; break;
8918     }
8919     if (Swap)
8920       std::swap(Op0, Op1);
8921
8922     // In the two special cases we can't handle, emit two comparisons.
8923     if (SSECC == 8) {
8924       unsigned CC0, CC1;
8925       unsigned CombineOpc;
8926       if (SetCCOpcode == ISD::SETUEQ) {
8927         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8928       } else {
8929         assert(SetCCOpcode == ISD::SETONE);
8930         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8931       }
8932
8933       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8934                                  DAG.getConstant(CC0, MVT::i8));
8935       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8936                                  DAG.getConstant(CC1, MVT::i8));
8937       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8938     }
8939     // Handle all other FP comparisons here.
8940     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8941                        DAG.getConstant(SSECC, MVT::i8));
8942   }
8943
8944   // Break 256-bit integer vector compare into smaller ones.
8945   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8946     return Lower256IntVSETCC(Op, DAG);
8947
8948   // We are handling one of the integer comparisons here.  Since SSE only has
8949   // GT and EQ comparisons for integer, swapping operands and multiple
8950   // operations may be required for some comparisons.
8951   unsigned Opc;
8952   bool Swap = false, Invert = false, FlipSigns = false;
8953
8954   switch (SetCCOpcode) {
8955   default: llvm_unreachable("Unexpected SETCC condition");
8956   case ISD::SETNE:  Invert = true;
8957   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8958   case ISD::SETLT:  Swap = true;
8959   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8960   case ISD::SETGE:  Swap = true;
8961   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8962   case ISD::SETULT: Swap = true;
8963   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8964   case ISD::SETUGE: Swap = true;
8965   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8966   }
8967   if (Swap)
8968     std::swap(Op0, Op1);
8969
8970   // Check that the operation in question is available (most are plain SSE2,
8971   // but PCMPGTQ and PCMPEQQ have different requirements).
8972   if (VT == MVT::v2i64) {
8973     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8974       return SDValue();
8975     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8976       return SDValue();
8977   }
8978
8979   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8980   // bits of the inputs before performing those operations.
8981   if (FlipSigns) {
8982     EVT EltVT = VT.getVectorElementType();
8983     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8984                                       EltVT);
8985     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8986     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8987                                     SignBits.size());
8988     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8989     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8990   }
8991
8992   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8993
8994   // If the logical-not of the result is required, perform that now.
8995   if (Invert)
8996     Result = DAG.getNOT(dl, Result, VT);
8997
8998   return Result;
8999 }
9000
9001 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9002 static bool isX86LogicalCmp(SDValue Op) {
9003   unsigned Opc = Op.getNode()->getOpcode();
9004   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9005       Opc == X86ISD::SAHF)
9006     return true;
9007   if (Op.getResNo() == 1 &&
9008       (Opc == X86ISD::ADD ||
9009        Opc == X86ISD::SUB ||
9010        Opc == X86ISD::ADC ||
9011        Opc == X86ISD::SBB ||
9012        Opc == X86ISD::SMUL ||
9013        Opc == X86ISD::UMUL ||
9014        Opc == X86ISD::INC ||
9015        Opc == X86ISD::DEC ||
9016        Opc == X86ISD::OR ||
9017        Opc == X86ISD::XOR ||
9018        Opc == X86ISD::AND))
9019     return true;
9020
9021   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9022     return true;
9023
9024   return false;
9025 }
9026
9027 static bool isZero(SDValue V) {
9028   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9029   return C && C->isNullValue();
9030 }
9031
9032 static bool isAllOnes(SDValue V) {
9033   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9034   return C && C->isAllOnesValue();
9035 }
9036
9037 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9038   if (V.getOpcode() != ISD::TRUNCATE)
9039     return false;
9040
9041   SDValue VOp0 = V.getOperand(0);
9042   unsigned InBits = VOp0.getValueSizeInBits();
9043   unsigned Bits = V.getValueSizeInBits();
9044   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9045 }
9046
9047 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9048   bool addTest = true;
9049   SDValue Cond  = Op.getOperand(0);
9050   SDValue Op1 = Op.getOperand(1);
9051   SDValue Op2 = Op.getOperand(2);
9052   DebugLoc DL = Op.getDebugLoc();
9053   SDValue CC;
9054
9055   if (Cond.getOpcode() == ISD::SETCC) {
9056     SDValue NewCond = LowerSETCC(Cond, DAG);
9057     if (NewCond.getNode())
9058       Cond = NewCond;
9059   }
9060
9061   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9062   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9063   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9064   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9065   if (Cond.getOpcode() == X86ISD::SETCC &&
9066       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9067       isZero(Cond.getOperand(1).getOperand(1))) {
9068     SDValue Cmp = Cond.getOperand(1);
9069
9070     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9071
9072     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9073         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9074       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9075
9076       SDValue CmpOp0 = Cmp.getOperand(0);
9077       // Apply further optimizations for special cases
9078       // (select (x != 0), -1, 0) -> neg & sbb
9079       // (select (x == 0), 0, -1) -> neg & sbb
9080       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9081         if (YC->isNullValue() &&
9082             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9083           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9084           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9085                                     DAG.getConstant(0, CmpOp0.getValueType()),
9086                                     CmpOp0);
9087           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9088                                     DAG.getConstant(X86::COND_B, MVT::i8),
9089                                     SDValue(Neg.getNode(), 1));
9090           return Res;
9091         }
9092
9093       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9094                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9095       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9096
9097       SDValue Res =   // Res = 0 or -1.
9098         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9099                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9100
9101       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9102         Res = DAG.getNOT(DL, Res, Res.getValueType());
9103
9104       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9105       if (N2C == 0 || !N2C->isNullValue())
9106         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9107       return Res;
9108     }
9109   }
9110
9111   // Look past (and (setcc_carry (cmp ...)), 1).
9112   if (Cond.getOpcode() == ISD::AND &&
9113       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9114     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9115     if (C && C->getAPIntValue() == 1)
9116       Cond = Cond.getOperand(0);
9117   }
9118
9119   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9120   // setting operand in place of the X86ISD::SETCC.
9121   unsigned CondOpcode = Cond.getOpcode();
9122   if (CondOpcode == X86ISD::SETCC ||
9123       CondOpcode == X86ISD::SETCC_CARRY) {
9124     CC = Cond.getOperand(0);
9125
9126     SDValue Cmp = Cond.getOperand(1);
9127     unsigned Opc = Cmp.getOpcode();
9128     EVT VT = Op.getValueType();
9129
9130     bool IllegalFPCMov = false;
9131     if (VT.isFloatingPoint() && !VT.isVector() &&
9132         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9133       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9134
9135     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9136         Opc == X86ISD::BT) { // FIXME
9137       Cond = Cmp;
9138       addTest = false;
9139     }
9140   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9141              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9142              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9143               Cond.getOperand(0).getValueType() != MVT::i8)) {
9144     SDValue LHS = Cond.getOperand(0);
9145     SDValue RHS = Cond.getOperand(1);
9146     unsigned X86Opcode;
9147     unsigned X86Cond;
9148     SDVTList VTs;
9149     switch (CondOpcode) {
9150     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9151     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9152     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9153     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9154     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9155     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9156     default: llvm_unreachable("unexpected overflowing operator");
9157     }
9158     if (CondOpcode == ISD::UMULO)
9159       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9160                           MVT::i32);
9161     else
9162       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9163
9164     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9165
9166     if (CondOpcode == ISD::UMULO)
9167       Cond = X86Op.getValue(2);
9168     else
9169       Cond = X86Op.getValue(1);
9170
9171     CC = DAG.getConstant(X86Cond, MVT::i8);
9172     addTest = false;
9173   }
9174
9175   if (addTest) {
9176     // Look pass the truncate if the high bits are known zero.
9177     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9178         Cond = Cond.getOperand(0);
9179
9180     // We know the result of AND is compared against zero. Try to match
9181     // it to BT.
9182     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9183       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9184       if (NewSetCC.getNode()) {
9185         CC = NewSetCC.getOperand(0);
9186         Cond = NewSetCC.getOperand(1);
9187         addTest = false;
9188       }
9189     }
9190   }
9191
9192   if (addTest) {
9193     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9194     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9195   }
9196
9197   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9198   // a <  b ?  0 : -1 -> RES = setcc_carry
9199   // a >= b ? -1 :  0 -> RES = setcc_carry
9200   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9201   if (Cond.getOpcode() == X86ISD::SUB) {
9202     Cond = ConvertCmpIfNecessary(Cond, DAG);
9203     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9204
9205     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9206         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9207       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9208                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9209       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9210         return DAG.getNOT(DL, Res, Res.getValueType());
9211       return Res;
9212     }
9213   }
9214
9215   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9216   // condition is true.
9217   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9218   SDValue Ops[] = { Op2, Op1, CC, Cond };
9219   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9220 }
9221
9222 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9223 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9224 // from the AND / OR.
9225 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9226   Opc = Op.getOpcode();
9227   if (Opc != ISD::OR && Opc != ISD::AND)
9228     return false;
9229   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9230           Op.getOperand(0).hasOneUse() &&
9231           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9232           Op.getOperand(1).hasOneUse());
9233 }
9234
9235 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9236 // 1 and that the SETCC node has a single use.
9237 static bool isXor1OfSetCC(SDValue Op) {
9238   if (Op.getOpcode() != ISD::XOR)
9239     return false;
9240   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9241   if (N1C && N1C->getAPIntValue() == 1) {
9242     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9243       Op.getOperand(0).hasOneUse();
9244   }
9245   return false;
9246 }
9247
9248 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9249   bool addTest = true;
9250   SDValue Chain = Op.getOperand(0);
9251   SDValue Cond  = Op.getOperand(1);
9252   SDValue Dest  = Op.getOperand(2);
9253   DebugLoc dl = Op.getDebugLoc();
9254   SDValue CC;
9255   bool Inverted = false;
9256
9257   if (Cond.getOpcode() == ISD::SETCC) {
9258     // Check for setcc([su]{add,sub,mul}o == 0).
9259     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9260         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9261         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9262         Cond.getOperand(0).getResNo() == 1 &&
9263         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9264          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9265          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9266          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9267          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9268          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9269       Inverted = true;
9270       Cond = Cond.getOperand(0);
9271     } else {
9272       SDValue NewCond = LowerSETCC(Cond, DAG);
9273       if (NewCond.getNode())
9274         Cond = NewCond;
9275     }
9276   }
9277 #if 0
9278   // FIXME: LowerXALUO doesn't handle these!!
9279   else if (Cond.getOpcode() == X86ISD::ADD  ||
9280            Cond.getOpcode() == X86ISD::SUB  ||
9281            Cond.getOpcode() == X86ISD::SMUL ||
9282            Cond.getOpcode() == X86ISD::UMUL)
9283     Cond = LowerXALUO(Cond, DAG);
9284 #endif
9285
9286   // Look pass (and (setcc_carry (cmp ...)), 1).
9287   if (Cond.getOpcode() == ISD::AND &&
9288       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9289     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9290     if (C && C->getAPIntValue() == 1)
9291       Cond = Cond.getOperand(0);
9292   }
9293
9294   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9295   // setting operand in place of the X86ISD::SETCC.
9296   unsigned CondOpcode = Cond.getOpcode();
9297   if (CondOpcode == X86ISD::SETCC ||
9298       CondOpcode == X86ISD::SETCC_CARRY) {
9299     CC = Cond.getOperand(0);
9300
9301     SDValue Cmp = Cond.getOperand(1);
9302     unsigned Opc = Cmp.getOpcode();
9303     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9304     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9305       Cond = Cmp;
9306       addTest = false;
9307     } else {
9308       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9309       default: break;
9310       case X86::COND_O:
9311       case X86::COND_B:
9312         // These can only come from an arithmetic instruction with overflow,
9313         // e.g. SADDO, UADDO.
9314         Cond = Cond.getNode()->getOperand(1);
9315         addTest = false;
9316         break;
9317       }
9318     }
9319   }
9320   CondOpcode = Cond.getOpcode();
9321   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9322       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9323       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9324        Cond.getOperand(0).getValueType() != MVT::i8)) {
9325     SDValue LHS = Cond.getOperand(0);
9326     SDValue RHS = Cond.getOperand(1);
9327     unsigned X86Opcode;
9328     unsigned X86Cond;
9329     SDVTList VTs;
9330     switch (CondOpcode) {
9331     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9332     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9333     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9334     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9335     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9336     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9337     default: llvm_unreachable("unexpected overflowing operator");
9338     }
9339     if (Inverted)
9340       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9341     if (CondOpcode == ISD::UMULO)
9342       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9343                           MVT::i32);
9344     else
9345       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9346
9347     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9348
9349     if (CondOpcode == ISD::UMULO)
9350       Cond = X86Op.getValue(2);
9351     else
9352       Cond = X86Op.getValue(1);
9353
9354     CC = DAG.getConstant(X86Cond, MVT::i8);
9355     addTest = false;
9356   } else {
9357     unsigned CondOpc;
9358     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9359       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9360       if (CondOpc == ISD::OR) {
9361         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9362         // two branches instead of an explicit OR instruction with a
9363         // separate test.
9364         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9365             isX86LogicalCmp(Cmp)) {
9366           CC = Cond.getOperand(0).getOperand(0);
9367           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9368                               Chain, Dest, CC, Cmp);
9369           CC = Cond.getOperand(1).getOperand(0);
9370           Cond = Cmp;
9371           addTest = false;
9372         }
9373       } else { // ISD::AND
9374         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9375         // two branches instead of an explicit AND instruction with a
9376         // separate test. However, we only do this if this block doesn't
9377         // have a fall-through edge, because this requires an explicit
9378         // jmp when the condition is false.
9379         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9380             isX86LogicalCmp(Cmp) &&
9381             Op.getNode()->hasOneUse()) {
9382           X86::CondCode CCode =
9383             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9384           CCode = X86::GetOppositeBranchCondition(CCode);
9385           CC = DAG.getConstant(CCode, MVT::i8);
9386           SDNode *User = *Op.getNode()->use_begin();
9387           // Look for an unconditional branch following this conditional branch.
9388           // We need this because we need to reverse the successors in order
9389           // to implement FCMP_OEQ.
9390           if (User->getOpcode() == ISD::BR) {
9391             SDValue FalseBB = User->getOperand(1);
9392             SDNode *NewBR =
9393               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9394             assert(NewBR == User);
9395             (void)NewBR;
9396             Dest = FalseBB;
9397
9398             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9399                                 Chain, Dest, CC, Cmp);
9400             X86::CondCode CCode =
9401               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9402             CCode = X86::GetOppositeBranchCondition(CCode);
9403             CC = DAG.getConstant(CCode, MVT::i8);
9404             Cond = Cmp;
9405             addTest = false;
9406           }
9407         }
9408       }
9409     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9410       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9411       // It should be transformed during dag combiner except when the condition
9412       // is set by a arithmetics with overflow node.
9413       X86::CondCode CCode =
9414         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9415       CCode = X86::GetOppositeBranchCondition(CCode);
9416       CC = DAG.getConstant(CCode, MVT::i8);
9417       Cond = Cond.getOperand(0).getOperand(1);
9418       addTest = false;
9419     } else if (Cond.getOpcode() == ISD::SETCC &&
9420                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9421       // For FCMP_OEQ, we can emit
9422       // two branches instead of an explicit AND instruction with a
9423       // separate test. However, we only do this if this block doesn't
9424       // have a fall-through edge, because this requires an explicit
9425       // jmp when the condition is false.
9426       if (Op.getNode()->hasOneUse()) {
9427         SDNode *User = *Op.getNode()->use_begin();
9428         // Look for an unconditional branch following this conditional branch.
9429         // We need this because we need to reverse the successors in order
9430         // to implement FCMP_OEQ.
9431         if (User->getOpcode() == ISD::BR) {
9432           SDValue FalseBB = User->getOperand(1);
9433           SDNode *NewBR =
9434             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9435           assert(NewBR == User);
9436           (void)NewBR;
9437           Dest = FalseBB;
9438
9439           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9440                                     Cond.getOperand(0), Cond.getOperand(1));
9441           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9442           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9443           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9444                               Chain, Dest, CC, Cmp);
9445           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9446           Cond = Cmp;
9447           addTest = false;
9448         }
9449       }
9450     } else if (Cond.getOpcode() == ISD::SETCC &&
9451                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9452       // For FCMP_UNE, we can emit
9453       // two branches instead of an explicit AND instruction with a
9454       // separate test. However, we only do this if this block doesn't
9455       // have a fall-through edge, because this requires an explicit
9456       // jmp when the condition is false.
9457       if (Op.getNode()->hasOneUse()) {
9458         SDNode *User = *Op.getNode()->use_begin();
9459         // Look for an unconditional branch following this conditional branch.
9460         // We need this because we need to reverse the successors in order
9461         // to implement FCMP_UNE.
9462         if (User->getOpcode() == ISD::BR) {
9463           SDValue FalseBB = User->getOperand(1);
9464           SDNode *NewBR =
9465             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9466           assert(NewBR == User);
9467           (void)NewBR;
9468
9469           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9470                                     Cond.getOperand(0), Cond.getOperand(1));
9471           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9472           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9473           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9474                               Chain, Dest, CC, Cmp);
9475           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9476           Cond = Cmp;
9477           addTest = false;
9478           Dest = FalseBB;
9479         }
9480       }
9481     }
9482   }
9483
9484   if (addTest) {
9485     // Look pass the truncate if the high bits are known zero.
9486     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9487         Cond = Cond.getOperand(0);
9488
9489     // We know the result of AND is compared against zero. Try to match
9490     // it to BT.
9491     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9492       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9493       if (NewSetCC.getNode()) {
9494         CC = NewSetCC.getOperand(0);
9495         Cond = NewSetCC.getOperand(1);
9496         addTest = false;
9497       }
9498     }
9499   }
9500
9501   if (addTest) {
9502     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9503     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9504   }
9505   Cond = ConvertCmpIfNecessary(Cond, DAG);
9506   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9507                      Chain, Dest, CC, Cond);
9508 }
9509
9510
9511 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9512 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9513 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9514 // that the guard pages used by the OS virtual memory manager are allocated in
9515 // correct sequence.
9516 SDValue
9517 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9518                                            SelectionDAG &DAG) const {
9519   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9520           getTargetMachine().Options.EnableSegmentedStacks) &&
9521          "This should be used only on Windows targets or when segmented stacks "
9522          "are being used");
9523   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9524   DebugLoc dl = Op.getDebugLoc();
9525
9526   // Get the inputs.
9527   SDValue Chain = Op.getOperand(0);
9528   SDValue Size  = Op.getOperand(1);
9529   // FIXME: Ensure alignment here
9530
9531   bool Is64Bit = Subtarget->is64Bit();
9532   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9533
9534   if (getTargetMachine().Options.EnableSegmentedStacks) {
9535     MachineFunction &MF = DAG.getMachineFunction();
9536     MachineRegisterInfo &MRI = MF.getRegInfo();
9537
9538     if (Is64Bit) {
9539       // The 64 bit implementation of segmented stacks needs to clobber both r10
9540       // r11. This makes it impossible to use it along with nested parameters.
9541       const Function *F = MF.getFunction();
9542
9543       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9544            I != E; ++I)
9545         if (I->hasNestAttr())
9546           report_fatal_error("Cannot use segmented stacks with functions that "
9547                              "have nested arguments.");
9548     }
9549
9550     const TargetRegisterClass *AddrRegClass =
9551       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9552     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9553     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9554     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9555                                 DAG.getRegister(Vreg, SPTy));
9556     SDValue Ops1[2] = { Value, Chain };
9557     return DAG.getMergeValues(Ops1, 2, dl);
9558   } else {
9559     SDValue Flag;
9560     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9561
9562     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9563     Flag = Chain.getValue(1);
9564     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9565
9566     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9567     Flag = Chain.getValue(1);
9568
9569     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9570
9571     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9572     return DAG.getMergeValues(Ops1, 2, dl);
9573   }
9574 }
9575
9576 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9577   MachineFunction &MF = DAG.getMachineFunction();
9578   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9579
9580   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9581   DebugLoc DL = Op.getDebugLoc();
9582
9583   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9584     // vastart just stores the address of the VarArgsFrameIndex slot into the
9585     // memory location argument.
9586     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9587                                    getPointerTy());
9588     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9589                         MachinePointerInfo(SV), false, false, 0);
9590   }
9591
9592   // __va_list_tag:
9593   //   gp_offset         (0 - 6 * 8)
9594   //   fp_offset         (48 - 48 + 8 * 16)
9595   //   overflow_arg_area (point to parameters coming in memory).
9596   //   reg_save_area
9597   SmallVector<SDValue, 8> MemOps;
9598   SDValue FIN = Op.getOperand(1);
9599   // Store gp_offset
9600   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9601                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9602                                                MVT::i32),
9603                                FIN, MachinePointerInfo(SV), false, false, 0);
9604   MemOps.push_back(Store);
9605
9606   // Store fp_offset
9607   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9608                     FIN, DAG.getIntPtrConstant(4));
9609   Store = DAG.getStore(Op.getOperand(0), DL,
9610                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9611                                        MVT::i32),
9612                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9613   MemOps.push_back(Store);
9614
9615   // Store ptr to overflow_arg_area
9616   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9617                     FIN, DAG.getIntPtrConstant(4));
9618   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9619                                     getPointerTy());
9620   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9621                        MachinePointerInfo(SV, 8),
9622                        false, false, 0);
9623   MemOps.push_back(Store);
9624
9625   // Store ptr to reg_save_area.
9626   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9627                     FIN, DAG.getIntPtrConstant(8));
9628   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9629                                     getPointerTy());
9630   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9631                        MachinePointerInfo(SV, 16), false, false, 0);
9632   MemOps.push_back(Store);
9633   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9634                      &MemOps[0], MemOps.size());
9635 }
9636
9637 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9638   assert(Subtarget->is64Bit() &&
9639          "LowerVAARG only handles 64-bit va_arg!");
9640   assert((Subtarget->isTargetLinux() ||
9641           Subtarget->isTargetDarwin()) &&
9642           "Unhandled target in LowerVAARG");
9643   assert(Op.getNode()->getNumOperands() == 4);
9644   SDValue Chain = Op.getOperand(0);
9645   SDValue SrcPtr = Op.getOperand(1);
9646   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9647   unsigned Align = Op.getConstantOperandVal(3);
9648   DebugLoc dl = Op.getDebugLoc();
9649
9650   EVT ArgVT = Op.getNode()->getValueType(0);
9651   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9652   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9653   uint8_t ArgMode;
9654
9655   // Decide which area this value should be read from.
9656   // TODO: Implement the AMD64 ABI in its entirety. This simple
9657   // selection mechanism works only for the basic types.
9658   if (ArgVT == MVT::f80) {
9659     llvm_unreachable("va_arg for f80 not yet implemented");
9660   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9661     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9662   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9663     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9664   } else {
9665     llvm_unreachable("Unhandled argument type in LowerVAARG");
9666   }
9667
9668   if (ArgMode == 2) {
9669     // Sanity Check: Make sure using fp_offset makes sense.
9670     assert(!getTargetMachine().Options.UseSoftFloat &&
9671            !(DAG.getMachineFunction()
9672                 .getFunction()->getFnAttributes().hasNoImplicitFloatAttr()) &&
9673            Subtarget->hasSSE1());
9674   }
9675
9676   // Insert VAARG_64 node into the DAG
9677   // VAARG_64 returns two values: Variable Argument Address, Chain
9678   SmallVector<SDValue, 11> InstOps;
9679   InstOps.push_back(Chain);
9680   InstOps.push_back(SrcPtr);
9681   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9682   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9683   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9684   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9685   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9686                                           VTs, &InstOps[0], InstOps.size(),
9687                                           MVT::i64,
9688                                           MachinePointerInfo(SV),
9689                                           /*Align=*/0,
9690                                           /*Volatile=*/false,
9691                                           /*ReadMem=*/true,
9692                                           /*WriteMem=*/true);
9693   Chain = VAARG.getValue(1);
9694
9695   // Load the next argument and return it
9696   return DAG.getLoad(ArgVT, dl,
9697                      Chain,
9698                      VAARG,
9699                      MachinePointerInfo(),
9700                      false, false, false, 0);
9701 }
9702
9703 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9704                            SelectionDAG &DAG) {
9705   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9706   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9707   SDValue Chain = Op.getOperand(0);
9708   SDValue DstPtr = Op.getOperand(1);
9709   SDValue SrcPtr = Op.getOperand(2);
9710   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9711   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9712   DebugLoc DL = Op.getDebugLoc();
9713
9714   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9715                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9716                        false,
9717                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9718 }
9719
9720 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9721 // may or may not be a constant. Takes immediate version of shift as input.
9722 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9723                                    SDValue SrcOp, SDValue ShAmt,
9724                                    SelectionDAG &DAG) {
9725   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9726
9727   if (isa<ConstantSDNode>(ShAmt)) {
9728     // Constant may be a TargetConstant. Use a regular constant.
9729     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9730     switch (Opc) {
9731       default: llvm_unreachable("Unknown target vector shift node");
9732       case X86ISD::VSHLI:
9733       case X86ISD::VSRLI:
9734       case X86ISD::VSRAI:
9735         return DAG.getNode(Opc, dl, VT, SrcOp,
9736                            DAG.getConstant(ShiftAmt, MVT::i32));
9737     }
9738   }
9739
9740   // Change opcode to non-immediate version
9741   switch (Opc) {
9742     default: llvm_unreachable("Unknown target vector shift node");
9743     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9744     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9745     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9746   }
9747
9748   // Need to build a vector containing shift amount
9749   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9750   SDValue ShOps[4];
9751   ShOps[0] = ShAmt;
9752   ShOps[1] = DAG.getConstant(0, MVT::i32);
9753   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9754   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9755
9756   // The return type has to be a 128-bit type with the same element
9757   // type as the input type.
9758   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9759   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9760
9761   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9762   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9763 }
9764
9765 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9766   DebugLoc dl = Op.getDebugLoc();
9767   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9768   switch (IntNo) {
9769   default: return SDValue();    // Don't custom lower most intrinsics.
9770   // Comparison intrinsics.
9771   case Intrinsic::x86_sse_comieq_ss:
9772   case Intrinsic::x86_sse_comilt_ss:
9773   case Intrinsic::x86_sse_comile_ss:
9774   case Intrinsic::x86_sse_comigt_ss:
9775   case Intrinsic::x86_sse_comige_ss:
9776   case Intrinsic::x86_sse_comineq_ss:
9777   case Intrinsic::x86_sse_ucomieq_ss:
9778   case Intrinsic::x86_sse_ucomilt_ss:
9779   case Intrinsic::x86_sse_ucomile_ss:
9780   case Intrinsic::x86_sse_ucomigt_ss:
9781   case Intrinsic::x86_sse_ucomige_ss:
9782   case Intrinsic::x86_sse_ucomineq_ss:
9783   case Intrinsic::x86_sse2_comieq_sd:
9784   case Intrinsic::x86_sse2_comilt_sd:
9785   case Intrinsic::x86_sse2_comile_sd:
9786   case Intrinsic::x86_sse2_comigt_sd:
9787   case Intrinsic::x86_sse2_comige_sd:
9788   case Intrinsic::x86_sse2_comineq_sd:
9789   case Intrinsic::x86_sse2_ucomieq_sd:
9790   case Intrinsic::x86_sse2_ucomilt_sd:
9791   case Intrinsic::x86_sse2_ucomile_sd:
9792   case Intrinsic::x86_sse2_ucomigt_sd:
9793   case Intrinsic::x86_sse2_ucomige_sd:
9794   case Intrinsic::x86_sse2_ucomineq_sd: {
9795     unsigned Opc;
9796     ISD::CondCode CC;
9797     switch (IntNo) {
9798     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9799     case Intrinsic::x86_sse_comieq_ss:
9800     case Intrinsic::x86_sse2_comieq_sd:
9801       Opc = X86ISD::COMI;
9802       CC = ISD::SETEQ;
9803       break;
9804     case Intrinsic::x86_sse_comilt_ss:
9805     case Intrinsic::x86_sse2_comilt_sd:
9806       Opc = X86ISD::COMI;
9807       CC = ISD::SETLT;
9808       break;
9809     case Intrinsic::x86_sse_comile_ss:
9810     case Intrinsic::x86_sse2_comile_sd:
9811       Opc = X86ISD::COMI;
9812       CC = ISD::SETLE;
9813       break;
9814     case Intrinsic::x86_sse_comigt_ss:
9815     case Intrinsic::x86_sse2_comigt_sd:
9816       Opc = X86ISD::COMI;
9817       CC = ISD::SETGT;
9818       break;
9819     case Intrinsic::x86_sse_comige_ss:
9820     case Intrinsic::x86_sse2_comige_sd:
9821       Opc = X86ISD::COMI;
9822       CC = ISD::SETGE;
9823       break;
9824     case Intrinsic::x86_sse_comineq_ss:
9825     case Intrinsic::x86_sse2_comineq_sd:
9826       Opc = X86ISD::COMI;
9827       CC = ISD::SETNE;
9828       break;
9829     case Intrinsic::x86_sse_ucomieq_ss:
9830     case Intrinsic::x86_sse2_ucomieq_sd:
9831       Opc = X86ISD::UCOMI;
9832       CC = ISD::SETEQ;
9833       break;
9834     case Intrinsic::x86_sse_ucomilt_ss:
9835     case Intrinsic::x86_sse2_ucomilt_sd:
9836       Opc = X86ISD::UCOMI;
9837       CC = ISD::SETLT;
9838       break;
9839     case Intrinsic::x86_sse_ucomile_ss:
9840     case Intrinsic::x86_sse2_ucomile_sd:
9841       Opc = X86ISD::UCOMI;
9842       CC = ISD::SETLE;
9843       break;
9844     case Intrinsic::x86_sse_ucomigt_ss:
9845     case Intrinsic::x86_sse2_ucomigt_sd:
9846       Opc = X86ISD::UCOMI;
9847       CC = ISD::SETGT;
9848       break;
9849     case Intrinsic::x86_sse_ucomige_ss:
9850     case Intrinsic::x86_sse2_ucomige_sd:
9851       Opc = X86ISD::UCOMI;
9852       CC = ISD::SETGE;
9853       break;
9854     case Intrinsic::x86_sse_ucomineq_ss:
9855     case Intrinsic::x86_sse2_ucomineq_sd:
9856       Opc = X86ISD::UCOMI;
9857       CC = ISD::SETNE;
9858       break;
9859     }
9860
9861     SDValue LHS = Op.getOperand(1);
9862     SDValue RHS = Op.getOperand(2);
9863     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9864     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9865     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9866     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9867                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9868     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9869   }
9870
9871   // Arithmetic intrinsics.
9872   case Intrinsic::x86_sse2_pmulu_dq:
9873   case Intrinsic::x86_avx2_pmulu_dq:
9874     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9875                        Op.getOperand(1), Op.getOperand(2));
9876
9877   // SSE3/AVX horizontal add/sub intrinsics
9878   case Intrinsic::x86_sse3_hadd_ps:
9879   case Intrinsic::x86_sse3_hadd_pd:
9880   case Intrinsic::x86_avx_hadd_ps_256:
9881   case Intrinsic::x86_avx_hadd_pd_256:
9882   case Intrinsic::x86_sse3_hsub_ps:
9883   case Intrinsic::x86_sse3_hsub_pd:
9884   case Intrinsic::x86_avx_hsub_ps_256:
9885   case Intrinsic::x86_avx_hsub_pd_256:
9886   case Intrinsic::x86_ssse3_phadd_w_128:
9887   case Intrinsic::x86_ssse3_phadd_d_128:
9888   case Intrinsic::x86_avx2_phadd_w:
9889   case Intrinsic::x86_avx2_phadd_d:
9890   case Intrinsic::x86_ssse3_phsub_w_128:
9891   case Intrinsic::x86_ssse3_phsub_d_128:
9892   case Intrinsic::x86_avx2_phsub_w:
9893   case Intrinsic::x86_avx2_phsub_d: {
9894     unsigned Opcode;
9895     switch (IntNo) {
9896     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9897     case Intrinsic::x86_sse3_hadd_ps:
9898     case Intrinsic::x86_sse3_hadd_pd:
9899     case Intrinsic::x86_avx_hadd_ps_256:
9900     case Intrinsic::x86_avx_hadd_pd_256:
9901       Opcode = X86ISD::FHADD;
9902       break;
9903     case Intrinsic::x86_sse3_hsub_ps:
9904     case Intrinsic::x86_sse3_hsub_pd:
9905     case Intrinsic::x86_avx_hsub_ps_256:
9906     case Intrinsic::x86_avx_hsub_pd_256:
9907       Opcode = X86ISD::FHSUB;
9908       break;
9909     case Intrinsic::x86_ssse3_phadd_w_128:
9910     case Intrinsic::x86_ssse3_phadd_d_128:
9911     case Intrinsic::x86_avx2_phadd_w:
9912     case Intrinsic::x86_avx2_phadd_d:
9913       Opcode = X86ISD::HADD;
9914       break;
9915     case Intrinsic::x86_ssse3_phsub_w_128:
9916     case Intrinsic::x86_ssse3_phsub_d_128:
9917     case Intrinsic::x86_avx2_phsub_w:
9918     case Intrinsic::x86_avx2_phsub_d:
9919       Opcode = X86ISD::HSUB;
9920       break;
9921     }
9922     return DAG.getNode(Opcode, dl, Op.getValueType(),
9923                        Op.getOperand(1), Op.getOperand(2));
9924   }
9925
9926   // AVX2 variable shift intrinsics
9927   case Intrinsic::x86_avx2_psllv_d:
9928   case Intrinsic::x86_avx2_psllv_q:
9929   case Intrinsic::x86_avx2_psllv_d_256:
9930   case Intrinsic::x86_avx2_psllv_q_256:
9931   case Intrinsic::x86_avx2_psrlv_d:
9932   case Intrinsic::x86_avx2_psrlv_q:
9933   case Intrinsic::x86_avx2_psrlv_d_256:
9934   case Intrinsic::x86_avx2_psrlv_q_256:
9935   case Intrinsic::x86_avx2_psrav_d:
9936   case Intrinsic::x86_avx2_psrav_d_256: {
9937     unsigned Opcode;
9938     switch (IntNo) {
9939     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9940     case Intrinsic::x86_avx2_psllv_d:
9941     case Intrinsic::x86_avx2_psllv_q:
9942     case Intrinsic::x86_avx2_psllv_d_256:
9943     case Intrinsic::x86_avx2_psllv_q_256:
9944       Opcode = ISD::SHL;
9945       break;
9946     case Intrinsic::x86_avx2_psrlv_d:
9947     case Intrinsic::x86_avx2_psrlv_q:
9948     case Intrinsic::x86_avx2_psrlv_d_256:
9949     case Intrinsic::x86_avx2_psrlv_q_256:
9950       Opcode = ISD::SRL;
9951       break;
9952     case Intrinsic::x86_avx2_psrav_d:
9953     case Intrinsic::x86_avx2_psrav_d_256:
9954       Opcode = ISD::SRA;
9955       break;
9956     }
9957     return DAG.getNode(Opcode, dl, Op.getValueType(),
9958                        Op.getOperand(1), Op.getOperand(2));
9959   }
9960
9961   case Intrinsic::x86_ssse3_pshuf_b_128:
9962   case Intrinsic::x86_avx2_pshuf_b:
9963     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9964                        Op.getOperand(1), Op.getOperand(2));
9965
9966   case Intrinsic::x86_ssse3_psign_b_128:
9967   case Intrinsic::x86_ssse3_psign_w_128:
9968   case Intrinsic::x86_ssse3_psign_d_128:
9969   case Intrinsic::x86_avx2_psign_b:
9970   case Intrinsic::x86_avx2_psign_w:
9971   case Intrinsic::x86_avx2_psign_d:
9972     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9973                        Op.getOperand(1), Op.getOperand(2));
9974
9975   case Intrinsic::x86_sse41_insertps:
9976     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9977                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9978
9979   case Intrinsic::x86_avx_vperm2f128_ps_256:
9980   case Intrinsic::x86_avx_vperm2f128_pd_256:
9981   case Intrinsic::x86_avx_vperm2f128_si_256:
9982   case Intrinsic::x86_avx2_vperm2i128:
9983     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9984                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9985
9986   case Intrinsic::x86_avx2_permd:
9987   case Intrinsic::x86_avx2_permps:
9988     // Operands intentionally swapped. Mask is last operand to intrinsic,
9989     // but second operand for node/intruction.
9990     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9991                        Op.getOperand(2), Op.getOperand(1));
9992
9993   // ptest and testp intrinsics. The intrinsic these come from are designed to
9994   // return an integer value, not just an instruction so lower it to the ptest
9995   // or testp pattern and a setcc for the result.
9996   case Intrinsic::x86_sse41_ptestz:
9997   case Intrinsic::x86_sse41_ptestc:
9998   case Intrinsic::x86_sse41_ptestnzc:
9999   case Intrinsic::x86_avx_ptestz_256:
10000   case Intrinsic::x86_avx_ptestc_256:
10001   case Intrinsic::x86_avx_ptestnzc_256:
10002   case Intrinsic::x86_avx_vtestz_ps:
10003   case Intrinsic::x86_avx_vtestc_ps:
10004   case Intrinsic::x86_avx_vtestnzc_ps:
10005   case Intrinsic::x86_avx_vtestz_pd:
10006   case Intrinsic::x86_avx_vtestc_pd:
10007   case Intrinsic::x86_avx_vtestnzc_pd:
10008   case Intrinsic::x86_avx_vtestz_ps_256:
10009   case Intrinsic::x86_avx_vtestc_ps_256:
10010   case Intrinsic::x86_avx_vtestnzc_ps_256:
10011   case Intrinsic::x86_avx_vtestz_pd_256:
10012   case Intrinsic::x86_avx_vtestc_pd_256:
10013   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10014     bool IsTestPacked = false;
10015     unsigned X86CC;
10016     switch (IntNo) {
10017     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10018     case Intrinsic::x86_avx_vtestz_ps:
10019     case Intrinsic::x86_avx_vtestz_pd:
10020     case Intrinsic::x86_avx_vtestz_ps_256:
10021     case Intrinsic::x86_avx_vtestz_pd_256:
10022       IsTestPacked = true; // Fallthrough
10023     case Intrinsic::x86_sse41_ptestz:
10024     case Intrinsic::x86_avx_ptestz_256:
10025       // ZF = 1
10026       X86CC = X86::COND_E;
10027       break;
10028     case Intrinsic::x86_avx_vtestc_ps:
10029     case Intrinsic::x86_avx_vtestc_pd:
10030     case Intrinsic::x86_avx_vtestc_ps_256:
10031     case Intrinsic::x86_avx_vtestc_pd_256:
10032       IsTestPacked = true; // Fallthrough
10033     case Intrinsic::x86_sse41_ptestc:
10034     case Intrinsic::x86_avx_ptestc_256:
10035       // CF = 1
10036       X86CC = X86::COND_B;
10037       break;
10038     case Intrinsic::x86_avx_vtestnzc_ps:
10039     case Intrinsic::x86_avx_vtestnzc_pd:
10040     case Intrinsic::x86_avx_vtestnzc_ps_256:
10041     case Intrinsic::x86_avx_vtestnzc_pd_256:
10042       IsTestPacked = true; // Fallthrough
10043     case Intrinsic::x86_sse41_ptestnzc:
10044     case Intrinsic::x86_avx_ptestnzc_256:
10045       // ZF and CF = 0
10046       X86CC = X86::COND_A;
10047       break;
10048     }
10049
10050     SDValue LHS = Op.getOperand(1);
10051     SDValue RHS = Op.getOperand(2);
10052     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10053     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10054     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10055     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10056     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10057   }
10058
10059   // SSE/AVX shift intrinsics
10060   case Intrinsic::x86_sse2_psll_w:
10061   case Intrinsic::x86_sse2_psll_d:
10062   case Intrinsic::x86_sse2_psll_q:
10063   case Intrinsic::x86_avx2_psll_w:
10064   case Intrinsic::x86_avx2_psll_d:
10065   case Intrinsic::x86_avx2_psll_q:
10066   case Intrinsic::x86_sse2_psrl_w:
10067   case Intrinsic::x86_sse2_psrl_d:
10068   case Intrinsic::x86_sse2_psrl_q:
10069   case Intrinsic::x86_avx2_psrl_w:
10070   case Intrinsic::x86_avx2_psrl_d:
10071   case Intrinsic::x86_avx2_psrl_q:
10072   case Intrinsic::x86_sse2_psra_w:
10073   case Intrinsic::x86_sse2_psra_d:
10074   case Intrinsic::x86_avx2_psra_w:
10075   case Intrinsic::x86_avx2_psra_d: {
10076     unsigned Opcode;
10077     switch (IntNo) {
10078     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10079     case Intrinsic::x86_sse2_psll_w:
10080     case Intrinsic::x86_sse2_psll_d:
10081     case Intrinsic::x86_sse2_psll_q:
10082     case Intrinsic::x86_avx2_psll_w:
10083     case Intrinsic::x86_avx2_psll_d:
10084     case Intrinsic::x86_avx2_psll_q:
10085       Opcode = X86ISD::VSHL;
10086       break;
10087     case Intrinsic::x86_sse2_psrl_w:
10088     case Intrinsic::x86_sse2_psrl_d:
10089     case Intrinsic::x86_sse2_psrl_q:
10090     case Intrinsic::x86_avx2_psrl_w:
10091     case Intrinsic::x86_avx2_psrl_d:
10092     case Intrinsic::x86_avx2_psrl_q:
10093       Opcode = X86ISD::VSRL;
10094       break;
10095     case Intrinsic::x86_sse2_psra_w:
10096     case Intrinsic::x86_sse2_psra_d:
10097     case Intrinsic::x86_avx2_psra_w:
10098     case Intrinsic::x86_avx2_psra_d:
10099       Opcode = X86ISD::VSRA;
10100       break;
10101     }
10102     return DAG.getNode(Opcode, dl, Op.getValueType(),
10103                        Op.getOperand(1), Op.getOperand(2));
10104   }
10105
10106   // SSE/AVX immediate shift intrinsics
10107   case Intrinsic::x86_sse2_pslli_w:
10108   case Intrinsic::x86_sse2_pslli_d:
10109   case Intrinsic::x86_sse2_pslli_q:
10110   case Intrinsic::x86_avx2_pslli_w:
10111   case Intrinsic::x86_avx2_pslli_d:
10112   case Intrinsic::x86_avx2_pslli_q:
10113   case Intrinsic::x86_sse2_psrli_w:
10114   case Intrinsic::x86_sse2_psrli_d:
10115   case Intrinsic::x86_sse2_psrli_q:
10116   case Intrinsic::x86_avx2_psrli_w:
10117   case Intrinsic::x86_avx2_psrli_d:
10118   case Intrinsic::x86_avx2_psrli_q:
10119   case Intrinsic::x86_sse2_psrai_w:
10120   case Intrinsic::x86_sse2_psrai_d:
10121   case Intrinsic::x86_avx2_psrai_w:
10122   case Intrinsic::x86_avx2_psrai_d: {
10123     unsigned Opcode;
10124     switch (IntNo) {
10125     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10126     case Intrinsic::x86_sse2_pslli_w:
10127     case Intrinsic::x86_sse2_pslli_d:
10128     case Intrinsic::x86_sse2_pslli_q:
10129     case Intrinsic::x86_avx2_pslli_w:
10130     case Intrinsic::x86_avx2_pslli_d:
10131     case Intrinsic::x86_avx2_pslli_q:
10132       Opcode = X86ISD::VSHLI;
10133       break;
10134     case Intrinsic::x86_sse2_psrli_w:
10135     case Intrinsic::x86_sse2_psrli_d:
10136     case Intrinsic::x86_sse2_psrli_q:
10137     case Intrinsic::x86_avx2_psrli_w:
10138     case Intrinsic::x86_avx2_psrli_d:
10139     case Intrinsic::x86_avx2_psrli_q:
10140       Opcode = X86ISD::VSRLI;
10141       break;
10142     case Intrinsic::x86_sse2_psrai_w:
10143     case Intrinsic::x86_sse2_psrai_d:
10144     case Intrinsic::x86_avx2_psrai_w:
10145     case Intrinsic::x86_avx2_psrai_d:
10146       Opcode = X86ISD::VSRAI;
10147       break;
10148     }
10149     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10150                                Op.getOperand(1), Op.getOperand(2), DAG);
10151   }
10152
10153   case Intrinsic::x86_sse42_pcmpistria128:
10154   case Intrinsic::x86_sse42_pcmpestria128:
10155   case Intrinsic::x86_sse42_pcmpistric128:
10156   case Intrinsic::x86_sse42_pcmpestric128:
10157   case Intrinsic::x86_sse42_pcmpistrio128:
10158   case Intrinsic::x86_sse42_pcmpestrio128:
10159   case Intrinsic::x86_sse42_pcmpistris128:
10160   case Intrinsic::x86_sse42_pcmpestris128:
10161   case Intrinsic::x86_sse42_pcmpistriz128:
10162   case Intrinsic::x86_sse42_pcmpestriz128: {
10163     unsigned Opcode;
10164     unsigned X86CC;
10165     switch (IntNo) {
10166     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10167     case Intrinsic::x86_sse42_pcmpistria128:
10168       Opcode = X86ISD::PCMPISTRI;
10169       X86CC = X86::COND_A;
10170       break;
10171     case Intrinsic::x86_sse42_pcmpestria128:
10172       Opcode = X86ISD::PCMPESTRI;
10173       X86CC = X86::COND_A;
10174       break;
10175     case Intrinsic::x86_sse42_pcmpistric128:
10176       Opcode = X86ISD::PCMPISTRI;
10177       X86CC = X86::COND_B;
10178       break;
10179     case Intrinsic::x86_sse42_pcmpestric128:
10180       Opcode = X86ISD::PCMPESTRI;
10181       X86CC = X86::COND_B;
10182       break;
10183     case Intrinsic::x86_sse42_pcmpistrio128:
10184       Opcode = X86ISD::PCMPISTRI;
10185       X86CC = X86::COND_O;
10186       break;
10187     case Intrinsic::x86_sse42_pcmpestrio128:
10188       Opcode = X86ISD::PCMPESTRI;
10189       X86CC = X86::COND_O;
10190       break;
10191     case Intrinsic::x86_sse42_pcmpistris128:
10192       Opcode = X86ISD::PCMPISTRI;
10193       X86CC = X86::COND_S;
10194       break;
10195     case Intrinsic::x86_sse42_pcmpestris128:
10196       Opcode = X86ISD::PCMPESTRI;
10197       X86CC = X86::COND_S;
10198       break;
10199     case Intrinsic::x86_sse42_pcmpistriz128:
10200       Opcode = X86ISD::PCMPISTRI;
10201       X86CC = X86::COND_E;
10202       break;
10203     case Intrinsic::x86_sse42_pcmpestriz128:
10204       Opcode = X86ISD::PCMPESTRI;
10205       X86CC = X86::COND_E;
10206       break;
10207     }
10208     SmallVector<SDValue, 5> NewOps;
10209     NewOps.append(Op->op_begin()+1, Op->op_end());
10210     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10211     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10212     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10213                                 DAG.getConstant(X86CC, MVT::i8),
10214                                 SDValue(PCMP.getNode(), 1));
10215     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10216   }
10217
10218   case Intrinsic::x86_sse42_pcmpistri128:
10219   case Intrinsic::x86_sse42_pcmpestri128: {
10220     unsigned Opcode;
10221     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10222       Opcode = X86ISD::PCMPISTRI;
10223     else
10224       Opcode = X86ISD::PCMPESTRI;
10225
10226     SmallVector<SDValue, 5> NewOps;
10227     NewOps.append(Op->op_begin()+1, Op->op_end());
10228     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10229     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10230   }
10231   case Intrinsic::x86_fma_vfmadd_ps:
10232   case Intrinsic::x86_fma_vfmadd_pd:
10233   case Intrinsic::x86_fma_vfmsub_ps:
10234   case Intrinsic::x86_fma_vfmsub_pd:
10235   case Intrinsic::x86_fma_vfnmadd_ps:
10236   case Intrinsic::x86_fma_vfnmadd_pd:
10237   case Intrinsic::x86_fma_vfnmsub_ps:
10238   case Intrinsic::x86_fma_vfnmsub_pd:
10239   case Intrinsic::x86_fma_vfmaddsub_ps:
10240   case Intrinsic::x86_fma_vfmaddsub_pd:
10241   case Intrinsic::x86_fma_vfmsubadd_ps:
10242   case Intrinsic::x86_fma_vfmsubadd_pd:
10243   case Intrinsic::x86_fma_vfmadd_ps_256:
10244   case Intrinsic::x86_fma_vfmadd_pd_256:
10245   case Intrinsic::x86_fma_vfmsub_ps_256:
10246   case Intrinsic::x86_fma_vfmsub_pd_256:
10247   case Intrinsic::x86_fma_vfnmadd_ps_256:
10248   case Intrinsic::x86_fma_vfnmadd_pd_256:
10249   case Intrinsic::x86_fma_vfnmsub_ps_256:
10250   case Intrinsic::x86_fma_vfnmsub_pd_256:
10251   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10252   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10253   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10254   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10255     unsigned Opc;
10256     switch (IntNo) {
10257     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10258     case Intrinsic::x86_fma_vfmadd_ps:
10259     case Intrinsic::x86_fma_vfmadd_pd:
10260     case Intrinsic::x86_fma_vfmadd_ps_256:
10261     case Intrinsic::x86_fma_vfmadd_pd_256:
10262       Opc = X86ISD::FMADD;
10263       break;
10264     case Intrinsic::x86_fma_vfmsub_ps:
10265     case Intrinsic::x86_fma_vfmsub_pd:
10266     case Intrinsic::x86_fma_vfmsub_ps_256:
10267     case Intrinsic::x86_fma_vfmsub_pd_256:
10268       Opc = X86ISD::FMSUB;
10269       break;
10270     case Intrinsic::x86_fma_vfnmadd_ps:
10271     case Intrinsic::x86_fma_vfnmadd_pd:
10272     case Intrinsic::x86_fma_vfnmadd_ps_256:
10273     case Intrinsic::x86_fma_vfnmadd_pd_256:
10274       Opc = X86ISD::FNMADD;
10275       break;
10276     case Intrinsic::x86_fma_vfnmsub_ps:
10277     case Intrinsic::x86_fma_vfnmsub_pd:
10278     case Intrinsic::x86_fma_vfnmsub_ps_256:
10279     case Intrinsic::x86_fma_vfnmsub_pd_256:
10280       Opc = X86ISD::FNMSUB;
10281       break;
10282     case Intrinsic::x86_fma_vfmaddsub_ps:
10283     case Intrinsic::x86_fma_vfmaddsub_pd:
10284     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10285     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10286       Opc = X86ISD::FMADDSUB;
10287       break;
10288     case Intrinsic::x86_fma_vfmsubadd_ps:
10289     case Intrinsic::x86_fma_vfmsubadd_pd:
10290     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10291     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10292       Opc = X86ISD::FMSUBADD;
10293       break;
10294     }
10295
10296     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10297                        Op.getOperand(2), Op.getOperand(3));
10298   }
10299   }
10300 }
10301
10302 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10303   DebugLoc dl = Op.getDebugLoc();
10304   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10305   switch (IntNo) {
10306   default: return SDValue();    // Don't custom lower most intrinsics.
10307
10308   // RDRAND intrinsics.
10309   case Intrinsic::x86_rdrand_16:
10310   case Intrinsic::x86_rdrand_32:
10311   case Intrinsic::x86_rdrand_64: {
10312     // Emit the node with the right value type.
10313     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10314     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10315
10316     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10317     // return the value from Rand, which is always 0, casted to i32.
10318     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10319                       DAG.getConstant(1, Op->getValueType(1)),
10320                       DAG.getConstant(X86::COND_B, MVT::i32),
10321                       SDValue(Result.getNode(), 1) };
10322     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10323                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10324                                   Ops, 4);
10325
10326     // Return { result, isValid, chain }.
10327     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10328                        SDValue(Result.getNode(), 2));
10329   }
10330   }
10331 }
10332
10333 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10334                                            SelectionDAG &DAG) const {
10335   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10336   MFI->setReturnAddressIsTaken(true);
10337
10338   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10339   DebugLoc dl = Op.getDebugLoc();
10340
10341   if (Depth > 0) {
10342     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10343     SDValue Offset =
10344       DAG.getConstant(TD->getPointerSize(),
10345                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10346     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10347                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10348                                    FrameAddr, Offset),
10349                        MachinePointerInfo(), false, false, false, 0);
10350   }
10351
10352   // Just load the return address.
10353   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10354   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10355                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10356 }
10357
10358 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10359   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10360   MFI->setFrameAddressIsTaken(true);
10361
10362   EVT VT = Op.getValueType();
10363   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10364   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10365   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10366   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10367   while (Depth--)
10368     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10369                             MachinePointerInfo(),
10370                             false, false, false, 0);
10371   return FrameAddr;
10372 }
10373
10374 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10375                                                      SelectionDAG &DAG) const {
10376   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10377 }
10378
10379 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10380   SDValue Chain     = Op.getOperand(0);
10381   SDValue Offset    = Op.getOperand(1);
10382   SDValue Handler   = Op.getOperand(2);
10383   DebugLoc dl       = Op.getDebugLoc();
10384
10385   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10386                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10387                                      getPointerTy());
10388   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10389
10390   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10391                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10392   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10393   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10394                        false, false, 0);
10395   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10396
10397   return DAG.getNode(X86ISD::EH_RETURN, dl,
10398                      MVT::Other,
10399                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10400 }
10401
10402 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10403   return Op.getOperand(0);
10404 }
10405
10406 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10407                                                 SelectionDAG &DAG) const {
10408   SDValue Root = Op.getOperand(0);
10409   SDValue Trmp = Op.getOperand(1); // trampoline
10410   SDValue FPtr = Op.getOperand(2); // nested function
10411   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10412   DebugLoc dl  = Op.getDebugLoc();
10413
10414   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10415
10416   if (Subtarget->is64Bit()) {
10417     SDValue OutChains[6];
10418
10419     // Large code-model.
10420     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10421     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10422
10423     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10424     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10425
10426     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10427
10428     // Load the pointer to the nested function into R11.
10429     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10430     SDValue Addr = Trmp;
10431     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10432                                 Addr, MachinePointerInfo(TrmpAddr),
10433                                 false, false, 0);
10434
10435     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10436                        DAG.getConstant(2, MVT::i64));
10437     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10438                                 MachinePointerInfo(TrmpAddr, 2),
10439                                 false, false, 2);
10440
10441     // Load the 'nest' parameter value into R10.
10442     // R10 is specified in X86CallingConv.td
10443     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10444     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10445                        DAG.getConstant(10, MVT::i64));
10446     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10447                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10448                                 false, false, 0);
10449
10450     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10451                        DAG.getConstant(12, MVT::i64));
10452     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10453                                 MachinePointerInfo(TrmpAddr, 12),
10454                                 false, false, 2);
10455
10456     // Jump to the nested function.
10457     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10458     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10459                        DAG.getConstant(20, MVT::i64));
10460     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10461                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10462                                 false, false, 0);
10463
10464     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10465     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10466                        DAG.getConstant(22, MVT::i64));
10467     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10468                                 MachinePointerInfo(TrmpAddr, 22),
10469                                 false, false, 0);
10470
10471     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10472   } else {
10473     const Function *Func =
10474       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10475     CallingConv::ID CC = Func->getCallingConv();
10476     unsigned NestReg;
10477
10478     switch (CC) {
10479     default:
10480       llvm_unreachable("Unsupported calling convention");
10481     case CallingConv::C:
10482     case CallingConv::X86_StdCall: {
10483       // Pass 'nest' parameter in ECX.
10484       // Must be kept in sync with X86CallingConv.td
10485       NestReg = X86::ECX;
10486
10487       // Check that ECX wasn't needed by an 'inreg' parameter.
10488       FunctionType *FTy = Func->getFunctionType();
10489       const AttrListPtr &Attrs = Func->getAttributes();
10490
10491       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10492         unsigned InRegCount = 0;
10493         unsigned Idx = 1;
10494
10495         for (FunctionType::param_iterator I = FTy->param_begin(),
10496              E = FTy->param_end(); I != E; ++I, ++Idx)
10497           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10498             // FIXME: should only count parameters that are lowered to integers.
10499             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10500
10501         if (InRegCount > 2) {
10502           report_fatal_error("Nest register in use - reduce number of inreg"
10503                              " parameters!");
10504         }
10505       }
10506       break;
10507     }
10508     case CallingConv::X86_FastCall:
10509     case CallingConv::X86_ThisCall:
10510     case CallingConv::Fast:
10511       // Pass 'nest' parameter in EAX.
10512       // Must be kept in sync with X86CallingConv.td
10513       NestReg = X86::EAX;
10514       break;
10515     }
10516
10517     SDValue OutChains[4];
10518     SDValue Addr, Disp;
10519
10520     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10521                        DAG.getConstant(10, MVT::i32));
10522     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10523
10524     // This is storing the opcode for MOV32ri.
10525     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10526     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10527     OutChains[0] = DAG.getStore(Root, dl,
10528                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10529                                 Trmp, MachinePointerInfo(TrmpAddr),
10530                                 false, false, 0);
10531
10532     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10533                        DAG.getConstant(1, MVT::i32));
10534     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10535                                 MachinePointerInfo(TrmpAddr, 1),
10536                                 false, false, 1);
10537
10538     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10539     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10540                        DAG.getConstant(5, MVT::i32));
10541     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10542                                 MachinePointerInfo(TrmpAddr, 5),
10543                                 false, false, 1);
10544
10545     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10546                        DAG.getConstant(6, MVT::i32));
10547     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10548                                 MachinePointerInfo(TrmpAddr, 6),
10549                                 false, false, 1);
10550
10551     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10552   }
10553 }
10554
10555 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10556                                             SelectionDAG &DAG) const {
10557   /*
10558    The rounding mode is in bits 11:10 of FPSR, and has the following
10559    settings:
10560      00 Round to nearest
10561      01 Round to -inf
10562      10 Round to +inf
10563      11 Round to 0
10564
10565   FLT_ROUNDS, on the other hand, expects the following:
10566     -1 Undefined
10567      0 Round to 0
10568      1 Round to nearest
10569      2 Round to +inf
10570      3 Round to -inf
10571
10572   To perform the conversion, we do:
10573     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10574   */
10575
10576   MachineFunction &MF = DAG.getMachineFunction();
10577   const TargetMachine &TM = MF.getTarget();
10578   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10579   unsigned StackAlignment = TFI.getStackAlignment();
10580   EVT VT = Op.getValueType();
10581   DebugLoc DL = Op.getDebugLoc();
10582
10583   // Save FP Control Word to stack slot
10584   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10585   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10586
10587
10588   MachineMemOperand *MMO =
10589    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10590                            MachineMemOperand::MOStore, 2, 2);
10591
10592   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10593   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10594                                           DAG.getVTList(MVT::Other),
10595                                           Ops, 2, MVT::i16, MMO);
10596
10597   // Load FP Control Word from stack slot
10598   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10599                             MachinePointerInfo(), false, false, false, 0);
10600
10601   // Transform as necessary
10602   SDValue CWD1 =
10603     DAG.getNode(ISD::SRL, DL, MVT::i16,
10604                 DAG.getNode(ISD::AND, DL, MVT::i16,
10605                             CWD, DAG.getConstant(0x800, MVT::i16)),
10606                 DAG.getConstant(11, MVT::i8));
10607   SDValue CWD2 =
10608     DAG.getNode(ISD::SRL, DL, MVT::i16,
10609                 DAG.getNode(ISD::AND, DL, MVT::i16,
10610                             CWD, DAG.getConstant(0x400, MVT::i16)),
10611                 DAG.getConstant(9, MVT::i8));
10612
10613   SDValue RetVal =
10614     DAG.getNode(ISD::AND, DL, MVT::i16,
10615                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10616                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10617                             DAG.getConstant(1, MVT::i16)),
10618                 DAG.getConstant(3, MVT::i16));
10619
10620
10621   return DAG.getNode((VT.getSizeInBits() < 16 ?
10622                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10623 }
10624
10625 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10626   EVT VT = Op.getValueType();
10627   EVT OpVT = VT;
10628   unsigned NumBits = VT.getSizeInBits();
10629   DebugLoc dl = Op.getDebugLoc();
10630
10631   Op = Op.getOperand(0);
10632   if (VT == MVT::i8) {
10633     // Zero extend to i32 since there is not an i8 bsr.
10634     OpVT = MVT::i32;
10635     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10636   }
10637
10638   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10639   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10640   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10641
10642   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10643   SDValue Ops[] = {
10644     Op,
10645     DAG.getConstant(NumBits+NumBits-1, OpVT),
10646     DAG.getConstant(X86::COND_E, MVT::i8),
10647     Op.getValue(1)
10648   };
10649   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10650
10651   // Finally xor with NumBits-1.
10652   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10653
10654   if (VT == MVT::i8)
10655     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10656   return Op;
10657 }
10658
10659 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10660   EVT VT = Op.getValueType();
10661   EVT OpVT = VT;
10662   unsigned NumBits = VT.getSizeInBits();
10663   DebugLoc dl = Op.getDebugLoc();
10664
10665   Op = Op.getOperand(0);
10666   if (VT == MVT::i8) {
10667     // Zero extend to i32 since there is not an i8 bsr.
10668     OpVT = MVT::i32;
10669     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10670   }
10671
10672   // Issue a bsr (scan bits in reverse).
10673   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10674   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10675
10676   // And xor with NumBits-1.
10677   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10678
10679   if (VT == MVT::i8)
10680     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10681   return Op;
10682 }
10683
10684 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10685   EVT VT = Op.getValueType();
10686   unsigned NumBits = VT.getSizeInBits();
10687   DebugLoc dl = Op.getDebugLoc();
10688   Op = Op.getOperand(0);
10689
10690   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10691   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10692   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10693
10694   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10695   SDValue Ops[] = {
10696     Op,
10697     DAG.getConstant(NumBits, VT),
10698     DAG.getConstant(X86::COND_E, MVT::i8),
10699     Op.getValue(1)
10700   };
10701   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10702 }
10703
10704 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10705 // ones, and then concatenate the result back.
10706 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10707   EVT VT = Op.getValueType();
10708
10709   assert(VT.is256BitVector() && VT.isInteger() &&
10710          "Unsupported value type for operation");
10711
10712   unsigned NumElems = VT.getVectorNumElements();
10713   DebugLoc dl = Op.getDebugLoc();
10714
10715   // Extract the LHS vectors
10716   SDValue LHS = Op.getOperand(0);
10717   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10718   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10719
10720   // Extract the RHS vectors
10721   SDValue RHS = Op.getOperand(1);
10722   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10723   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10724
10725   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10726   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10727
10728   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10729                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10730                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10731 }
10732
10733 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10734   assert(Op.getValueType().is256BitVector() &&
10735          Op.getValueType().isInteger() &&
10736          "Only handle AVX 256-bit vector integer operation");
10737   return Lower256IntArith(Op, DAG);
10738 }
10739
10740 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10741   assert(Op.getValueType().is256BitVector() &&
10742          Op.getValueType().isInteger() &&
10743          "Only handle AVX 256-bit vector integer operation");
10744   return Lower256IntArith(Op, DAG);
10745 }
10746
10747 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10748                         SelectionDAG &DAG) {
10749   EVT VT = Op.getValueType();
10750
10751   // Decompose 256-bit ops into smaller 128-bit ops.
10752   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10753     return Lower256IntArith(Op, DAG);
10754
10755   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10756          "Only know how to lower V2I64/V4I64 multiply");
10757
10758   DebugLoc dl = Op.getDebugLoc();
10759
10760   //  Ahi = psrlqi(a, 32);
10761   //  Bhi = psrlqi(b, 32);
10762   //
10763   //  AloBlo = pmuludq(a, b);
10764   //  AloBhi = pmuludq(a, Bhi);
10765   //  AhiBlo = pmuludq(Ahi, b);
10766
10767   //  AloBhi = psllqi(AloBhi, 32);
10768   //  AhiBlo = psllqi(AhiBlo, 32);
10769   //  return AloBlo + AloBhi + AhiBlo;
10770
10771   SDValue A = Op.getOperand(0);
10772   SDValue B = Op.getOperand(1);
10773
10774   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10775
10776   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10777   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10778
10779   // Bit cast to 32-bit vectors for MULUDQ
10780   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10781   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10782   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10783   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10784   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10785
10786   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10787   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10788   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10789
10790   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10791   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10792
10793   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10794   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10795 }
10796
10797 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10798
10799   EVT VT = Op.getValueType();
10800   DebugLoc dl = Op.getDebugLoc();
10801   SDValue R = Op.getOperand(0);
10802   SDValue Amt = Op.getOperand(1);
10803   LLVMContext *Context = DAG.getContext();
10804
10805   if (!Subtarget->hasSSE2())
10806     return SDValue();
10807
10808   // Optimize shl/srl/sra with constant shift amount.
10809   if (isSplatVector(Amt.getNode())) {
10810     SDValue SclrAmt = Amt->getOperand(0);
10811     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10812       uint64_t ShiftAmt = C->getZExtValue();
10813
10814       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10815           (Subtarget->hasAVX2() &&
10816            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10817         if (Op.getOpcode() == ISD::SHL)
10818           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10819                              DAG.getConstant(ShiftAmt, MVT::i32));
10820         if (Op.getOpcode() == ISD::SRL)
10821           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10822                              DAG.getConstant(ShiftAmt, MVT::i32));
10823         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10824           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10825                              DAG.getConstant(ShiftAmt, MVT::i32));
10826       }
10827
10828       if (VT == MVT::v16i8) {
10829         if (Op.getOpcode() == ISD::SHL) {
10830           // Make a large shift.
10831           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10832                                     DAG.getConstant(ShiftAmt, MVT::i32));
10833           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10834           // Zero out the rightmost bits.
10835           SmallVector<SDValue, 16> V(16,
10836                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10837                                                      MVT::i8));
10838           return DAG.getNode(ISD::AND, dl, VT, SHL,
10839                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10840         }
10841         if (Op.getOpcode() == ISD::SRL) {
10842           // Make a large shift.
10843           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10844                                     DAG.getConstant(ShiftAmt, MVT::i32));
10845           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10846           // Zero out the leftmost bits.
10847           SmallVector<SDValue, 16> V(16,
10848                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10849                                                      MVT::i8));
10850           return DAG.getNode(ISD::AND, dl, VT, SRL,
10851                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10852         }
10853         if (Op.getOpcode() == ISD::SRA) {
10854           if (ShiftAmt == 7) {
10855             // R s>> 7  ===  R s< 0
10856             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10857             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10858           }
10859
10860           // R s>> a === ((R u>> a) ^ m) - m
10861           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10862           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10863                                                          MVT::i8));
10864           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10865           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10866           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10867           return Res;
10868         }
10869         llvm_unreachable("Unknown shift opcode.");
10870       }
10871
10872       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10873         if (Op.getOpcode() == ISD::SHL) {
10874           // Make a large shift.
10875           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10876                                     DAG.getConstant(ShiftAmt, MVT::i32));
10877           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10878           // Zero out the rightmost bits.
10879           SmallVector<SDValue, 32> V(32,
10880                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10881                                                      MVT::i8));
10882           return DAG.getNode(ISD::AND, dl, VT, SHL,
10883                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10884         }
10885         if (Op.getOpcode() == ISD::SRL) {
10886           // Make a large shift.
10887           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10888                                     DAG.getConstant(ShiftAmt, MVT::i32));
10889           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10890           // Zero out the leftmost bits.
10891           SmallVector<SDValue, 32> V(32,
10892                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10893                                                      MVT::i8));
10894           return DAG.getNode(ISD::AND, dl, VT, SRL,
10895                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10896         }
10897         if (Op.getOpcode() == ISD::SRA) {
10898           if (ShiftAmt == 7) {
10899             // R s>> 7  ===  R s< 0
10900             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10901             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10902           }
10903
10904           // R s>> a === ((R u>> a) ^ m) - m
10905           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10906           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10907                                                          MVT::i8));
10908           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10909           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10910           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10911           return Res;
10912         }
10913         llvm_unreachable("Unknown shift opcode.");
10914       }
10915     }
10916   }
10917
10918   // Lower SHL with variable shift amount.
10919   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10920     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10921                      DAG.getConstant(23, MVT::i32));
10922
10923     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10924     Constant *C = ConstantDataVector::get(*Context, CV);
10925     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10926     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10927                                  MachinePointerInfo::getConstantPool(),
10928                                  false, false, false, 16);
10929
10930     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10931     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10932     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10933     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10934   }
10935   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10936     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10937
10938     // a = a << 5;
10939     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10940                      DAG.getConstant(5, MVT::i32));
10941     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10942
10943     // Turn 'a' into a mask suitable for VSELECT
10944     SDValue VSelM = DAG.getConstant(0x80, VT);
10945     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10946     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10947
10948     SDValue CM1 = DAG.getConstant(0x0f, VT);
10949     SDValue CM2 = DAG.getConstant(0x3f, VT);
10950
10951     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10952     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10953     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10954                             DAG.getConstant(4, MVT::i32), DAG);
10955     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10956     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10957
10958     // a += a
10959     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10960     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10961     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10962
10963     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10964     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10965     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10966                             DAG.getConstant(2, MVT::i32), DAG);
10967     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10968     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10969
10970     // a += a
10971     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10972     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10973     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10974
10975     // return VSELECT(r, r+r, a);
10976     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10977                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10978     return R;
10979   }
10980
10981   // Decompose 256-bit shifts into smaller 128-bit shifts.
10982   if (VT.is256BitVector()) {
10983     unsigned NumElems = VT.getVectorNumElements();
10984     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10985     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10986
10987     // Extract the two vectors
10988     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10989     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10990
10991     // Recreate the shift amount vectors
10992     SDValue Amt1, Amt2;
10993     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10994       // Constant shift amount
10995       SmallVector<SDValue, 4> Amt1Csts;
10996       SmallVector<SDValue, 4> Amt2Csts;
10997       for (unsigned i = 0; i != NumElems/2; ++i)
10998         Amt1Csts.push_back(Amt->getOperand(i));
10999       for (unsigned i = NumElems/2; i != NumElems; ++i)
11000         Amt2Csts.push_back(Amt->getOperand(i));
11001
11002       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11003                                  &Amt1Csts[0], NumElems/2);
11004       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11005                                  &Amt2Csts[0], NumElems/2);
11006     } else {
11007       // Variable shift amount
11008       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11009       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11010     }
11011
11012     // Issue new vector shifts for the smaller types
11013     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11014     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11015
11016     // Concatenate the result back
11017     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11018   }
11019
11020   return SDValue();
11021 }
11022
11023 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11024   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11025   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11026   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11027   // has only one use.
11028   SDNode *N = Op.getNode();
11029   SDValue LHS = N->getOperand(0);
11030   SDValue RHS = N->getOperand(1);
11031   unsigned BaseOp = 0;
11032   unsigned Cond = 0;
11033   DebugLoc DL = Op.getDebugLoc();
11034   switch (Op.getOpcode()) {
11035   default: llvm_unreachable("Unknown ovf instruction!");
11036   case ISD::SADDO:
11037     // A subtract of one will be selected as a INC. Note that INC doesn't
11038     // set CF, so we can't do this for UADDO.
11039     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11040       if (C->isOne()) {
11041         BaseOp = X86ISD::INC;
11042         Cond = X86::COND_O;
11043         break;
11044       }
11045     BaseOp = X86ISD::ADD;
11046     Cond = X86::COND_O;
11047     break;
11048   case ISD::UADDO:
11049     BaseOp = X86ISD::ADD;
11050     Cond = X86::COND_B;
11051     break;
11052   case ISD::SSUBO:
11053     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11054     // set CF, so we can't do this for USUBO.
11055     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11056       if (C->isOne()) {
11057         BaseOp = X86ISD::DEC;
11058         Cond = X86::COND_O;
11059         break;
11060       }
11061     BaseOp = X86ISD::SUB;
11062     Cond = X86::COND_O;
11063     break;
11064   case ISD::USUBO:
11065     BaseOp = X86ISD::SUB;
11066     Cond = X86::COND_B;
11067     break;
11068   case ISD::SMULO:
11069     BaseOp = X86ISD::SMUL;
11070     Cond = X86::COND_O;
11071     break;
11072   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11073     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11074                                  MVT::i32);
11075     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11076
11077     SDValue SetCC =
11078       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11079                   DAG.getConstant(X86::COND_O, MVT::i32),
11080                   SDValue(Sum.getNode(), 2));
11081
11082     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11083   }
11084   }
11085
11086   // Also sets EFLAGS.
11087   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11088   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11089
11090   SDValue SetCC =
11091     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11092                 DAG.getConstant(Cond, MVT::i32),
11093                 SDValue(Sum.getNode(), 1));
11094
11095   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11096 }
11097
11098 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11099                                                   SelectionDAG &DAG) const {
11100   DebugLoc dl = Op.getDebugLoc();
11101   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11102   EVT VT = Op.getValueType();
11103
11104   if (!Subtarget->hasSSE2() || !VT.isVector())
11105     return SDValue();
11106
11107   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11108                       ExtraVT.getScalarType().getSizeInBits();
11109   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11110
11111   switch (VT.getSimpleVT().SimpleTy) {
11112     default: return SDValue();
11113     case MVT::v8i32:
11114     case MVT::v16i16:
11115       if (!Subtarget->hasAVX())
11116         return SDValue();
11117       if (!Subtarget->hasAVX2()) {
11118         // needs to be split
11119         unsigned NumElems = VT.getVectorNumElements();
11120
11121         // Extract the LHS vectors
11122         SDValue LHS = Op.getOperand(0);
11123         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11124         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11125
11126         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11127         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11128
11129         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11130         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11131         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11132                                    ExtraNumElems/2);
11133         SDValue Extra = DAG.getValueType(ExtraVT);
11134
11135         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11136         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11137
11138         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11139       }
11140       // fall through
11141     case MVT::v4i32:
11142     case MVT::v8i16: {
11143       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11144                                          Op.getOperand(0), ShAmt, DAG);
11145       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11146     }
11147   }
11148 }
11149
11150
11151 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11152                               SelectionDAG &DAG) {
11153   DebugLoc dl = Op.getDebugLoc();
11154
11155   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11156   // There isn't any reason to disable it if the target processor supports it.
11157   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11158     SDValue Chain = Op.getOperand(0);
11159     SDValue Zero = DAG.getConstant(0, MVT::i32);
11160     SDValue Ops[] = {
11161       DAG.getRegister(X86::ESP, MVT::i32), // Base
11162       DAG.getTargetConstant(1, MVT::i8),   // Scale
11163       DAG.getRegister(0, MVT::i32),        // Index
11164       DAG.getTargetConstant(0, MVT::i32),  // Disp
11165       DAG.getRegister(0, MVT::i32),        // Segment.
11166       Zero,
11167       Chain
11168     };
11169     SDNode *Res =
11170       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11171                           array_lengthof(Ops));
11172     return SDValue(Res, 0);
11173   }
11174
11175   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11176   if (!isDev)
11177     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11178
11179   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11180   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11181   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11182   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11183
11184   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11185   if (!Op1 && !Op2 && !Op3 && Op4)
11186     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11187
11188   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11189   if (Op1 && !Op2 && !Op3 && !Op4)
11190     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11191
11192   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11193   //           (MFENCE)>;
11194   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11195 }
11196
11197 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11198                                  SelectionDAG &DAG) {
11199   DebugLoc dl = Op.getDebugLoc();
11200   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11201     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11202   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11203     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11204
11205   // The only fence that needs an instruction is a sequentially-consistent
11206   // cross-thread fence.
11207   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11208     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11209     // no-sse2). There isn't any reason to disable it if the target processor
11210     // supports it.
11211     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11212       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11213
11214     SDValue Chain = Op.getOperand(0);
11215     SDValue Zero = DAG.getConstant(0, MVT::i32);
11216     SDValue Ops[] = {
11217       DAG.getRegister(X86::ESP, MVT::i32), // Base
11218       DAG.getTargetConstant(1, MVT::i8),   // Scale
11219       DAG.getRegister(0, MVT::i32),        // Index
11220       DAG.getTargetConstant(0, MVT::i32),  // Disp
11221       DAG.getRegister(0, MVT::i32),        // Segment.
11222       Zero,
11223       Chain
11224     };
11225     SDNode *Res =
11226       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11227                          array_lengthof(Ops));
11228     return SDValue(Res, 0);
11229   }
11230
11231   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11232   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11233 }
11234
11235
11236 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11237                              SelectionDAG &DAG) {
11238   EVT T = Op.getValueType();
11239   DebugLoc DL = Op.getDebugLoc();
11240   unsigned Reg = 0;
11241   unsigned size = 0;
11242   switch(T.getSimpleVT().SimpleTy) {
11243   default: llvm_unreachable("Invalid value type!");
11244   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11245   case MVT::i16: Reg = X86::AX;  size = 2; break;
11246   case MVT::i32: Reg = X86::EAX; size = 4; break;
11247   case MVT::i64:
11248     assert(Subtarget->is64Bit() && "Node not type legal!");
11249     Reg = X86::RAX; size = 8;
11250     break;
11251   }
11252   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11253                                     Op.getOperand(2), SDValue());
11254   SDValue Ops[] = { cpIn.getValue(0),
11255                     Op.getOperand(1),
11256                     Op.getOperand(3),
11257                     DAG.getTargetConstant(size, MVT::i8),
11258                     cpIn.getValue(1) };
11259   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11260   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11261   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11262                                            Ops, 5, T, MMO);
11263   SDValue cpOut =
11264     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11265   return cpOut;
11266 }
11267
11268 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11269                                      SelectionDAG &DAG) {
11270   assert(Subtarget->is64Bit() && "Result not type legalized?");
11271   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11272   SDValue TheChain = Op.getOperand(0);
11273   DebugLoc dl = Op.getDebugLoc();
11274   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11275   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11276   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11277                                    rax.getValue(2));
11278   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11279                             DAG.getConstant(32, MVT::i8));
11280   SDValue Ops[] = {
11281     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11282     rdx.getValue(1)
11283   };
11284   return DAG.getMergeValues(Ops, 2, dl);
11285 }
11286
11287 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11288   EVT SrcVT = Op.getOperand(0).getValueType();
11289   EVT DstVT = Op.getValueType();
11290   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11291          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11292   assert((DstVT == MVT::i64 ||
11293           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11294          "Unexpected custom BITCAST");
11295   // i64 <=> MMX conversions are Legal.
11296   if (SrcVT==MVT::i64 && DstVT.isVector())
11297     return Op;
11298   if (DstVT==MVT::i64 && SrcVT.isVector())
11299     return Op;
11300   // MMX <=> MMX conversions are Legal.
11301   if (SrcVT.isVector() && DstVT.isVector())
11302     return Op;
11303   // All other conversions need to be expanded.
11304   return SDValue();
11305 }
11306
11307 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11308   SDNode *Node = Op.getNode();
11309   DebugLoc dl = Node->getDebugLoc();
11310   EVT T = Node->getValueType(0);
11311   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11312                               DAG.getConstant(0, T), Node->getOperand(2));
11313   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11314                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11315                        Node->getOperand(0),
11316                        Node->getOperand(1), negOp,
11317                        cast<AtomicSDNode>(Node)->getSrcValue(),
11318                        cast<AtomicSDNode>(Node)->getAlignment(),
11319                        cast<AtomicSDNode>(Node)->getOrdering(),
11320                        cast<AtomicSDNode>(Node)->getSynchScope());
11321 }
11322
11323 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11324   SDNode *Node = Op.getNode();
11325   DebugLoc dl = Node->getDebugLoc();
11326   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11327
11328   // Convert seq_cst store -> xchg
11329   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11330   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11331   //        (The only way to get a 16-byte store is cmpxchg16b)
11332   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11333   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11334       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11335     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11336                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11337                                  Node->getOperand(0),
11338                                  Node->getOperand(1), Node->getOperand(2),
11339                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11340                                  cast<AtomicSDNode>(Node)->getOrdering(),
11341                                  cast<AtomicSDNode>(Node)->getSynchScope());
11342     return Swap.getValue(1);
11343   }
11344   // Other atomic stores have a simple pattern.
11345   return Op;
11346 }
11347
11348 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11349   EVT VT = Op.getNode()->getValueType(0);
11350
11351   // Let legalize expand this if it isn't a legal type yet.
11352   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11353     return SDValue();
11354
11355   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11356
11357   unsigned Opc;
11358   bool ExtraOp = false;
11359   switch (Op.getOpcode()) {
11360   default: llvm_unreachable("Invalid code");
11361   case ISD::ADDC: Opc = X86ISD::ADD; break;
11362   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11363   case ISD::SUBC: Opc = X86ISD::SUB; break;
11364   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11365   }
11366
11367   if (!ExtraOp)
11368     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11369                        Op.getOperand(1));
11370   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11371                      Op.getOperand(1), Op.getOperand(2));
11372 }
11373
11374 /// LowerOperation - Provide custom lowering hooks for some operations.
11375 ///
11376 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11377   switch (Op.getOpcode()) {
11378   default: llvm_unreachable("Should not custom lower this!");
11379   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11380   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11381   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11382   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11383   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11384   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11385   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11386   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11387   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11388   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11389   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11390   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11391   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11392   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11393   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11394   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11395   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11396   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11397   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11398   case ISD::SHL_PARTS:
11399   case ISD::SRA_PARTS:
11400   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11401   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11402   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11403   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11404   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11405   case ISD::FABS:               return LowerFABS(Op, DAG);
11406   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11407   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11408   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11409   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11410   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11411   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11412   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11413   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11414   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11415   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11416   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11417   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11418   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11419   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11420   case ISD::FRAME_TO_ARGS_OFFSET:
11421                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11422   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11423   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11424   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11425   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11426   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11427   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11428   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11429   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11430   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11431   case ISD::SRA:
11432   case ISD::SRL:
11433   case ISD::SHL:                return LowerShift(Op, DAG);
11434   case ISD::SADDO:
11435   case ISD::UADDO:
11436   case ISD::SSUBO:
11437   case ISD::USUBO:
11438   case ISD::SMULO:
11439   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11440   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11441   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11442   case ISD::ADDC:
11443   case ISD::ADDE:
11444   case ISD::SUBC:
11445   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11446   case ISD::ADD:                return LowerADD(Op, DAG);
11447   case ISD::SUB:                return LowerSUB(Op, DAG);
11448   }
11449 }
11450
11451 static void ReplaceATOMIC_LOAD(SDNode *Node,
11452                                   SmallVectorImpl<SDValue> &Results,
11453                                   SelectionDAG &DAG) {
11454   DebugLoc dl = Node->getDebugLoc();
11455   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11456
11457   // Convert wide load -> cmpxchg8b/cmpxchg16b
11458   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11459   //        (The only way to get a 16-byte load is cmpxchg16b)
11460   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11461   SDValue Zero = DAG.getConstant(0, VT);
11462   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11463                                Node->getOperand(0),
11464                                Node->getOperand(1), Zero, Zero,
11465                                cast<AtomicSDNode>(Node)->getMemOperand(),
11466                                cast<AtomicSDNode>(Node)->getOrdering(),
11467                                cast<AtomicSDNode>(Node)->getSynchScope());
11468   Results.push_back(Swap.getValue(0));
11469   Results.push_back(Swap.getValue(1));
11470 }
11471
11472 static void
11473 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11474                         SelectionDAG &DAG, unsigned NewOp) {
11475   DebugLoc dl = Node->getDebugLoc();
11476   assert (Node->getValueType(0) == MVT::i64 &&
11477           "Only know how to expand i64 atomics");
11478
11479   SDValue Chain = Node->getOperand(0);
11480   SDValue In1 = Node->getOperand(1);
11481   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11482                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11483   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11484                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11485   SDValue Ops[] = { Chain, In1, In2L, In2H };
11486   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11487   SDValue Result =
11488     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11489                             cast<MemSDNode>(Node)->getMemOperand());
11490   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11491   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11492   Results.push_back(Result.getValue(2));
11493 }
11494
11495 /// ReplaceNodeResults - Replace a node with an illegal result type
11496 /// with a new node built out of custom code.
11497 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11498                                            SmallVectorImpl<SDValue>&Results,
11499                                            SelectionDAG &DAG) const {
11500   DebugLoc dl = N->getDebugLoc();
11501   switch (N->getOpcode()) {
11502   default:
11503     llvm_unreachable("Do not know how to custom type legalize this operation!");
11504   case ISD::SIGN_EXTEND_INREG:
11505   case ISD::ADDC:
11506   case ISD::ADDE:
11507   case ISD::SUBC:
11508   case ISD::SUBE:
11509     // We don't want to expand or promote these.
11510     return;
11511   case ISD::FP_TO_SINT:
11512   case ISD::FP_TO_UINT: {
11513     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11514
11515     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11516       return;
11517
11518     std::pair<SDValue,SDValue> Vals =
11519         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11520     SDValue FIST = Vals.first, StackSlot = Vals.second;
11521     if (FIST.getNode() != 0) {
11522       EVT VT = N->getValueType(0);
11523       // Return a load from the stack slot.
11524       if (StackSlot.getNode() != 0)
11525         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11526                                       MachinePointerInfo(),
11527                                       false, false, false, 0));
11528       else
11529         Results.push_back(FIST);
11530     }
11531     return;
11532   }
11533   case ISD::READCYCLECOUNTER: {
11534     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11535     SDValue TheChain = N->getOperand(0);
11536     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11537     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11538                                      rd.getValue(1));
11539     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11540                                      eax.getValue(2));
11541     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11542     SDValue Ops[] = { eax, edx };
11543     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11544     Results.push_back(edx.getValue(1));
11545     return;
11546   }
11547   case ISD::ATOMIC_CMP_SWAP: {
11548     EVT T = N->getValueType(0);
11549     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11550     bool Regs64bit = T == MVT::i128;
11551     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11552     SDValue cpInL, cpInH;
11553     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11554                         DAG.getConstant(0, HalfT));
11555     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11556                         DAG.getConstant(1, HalfT));
11557     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11558                              Regs64bit ? X86::RAX : X86::EAX,
11559                              cpInL, SDValue());
11560     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11561                              Regs64bit ? X86::RDX : X86::EDX,
11562                              cpInH, cpInL.getValue(1));
11563     SDValue swapInL, swapInH;
11564     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11565                           DAG.getConstant(0, HalfT));
11566     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11567                           DAG.getConstant(1, HalfT));
11568     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11569                                Regs64bit ? X86::RBX : X86::EBX,
11570                                swapInL, cpInH.getValue(1));
11571     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11572                                Regs64bit ? X86::RCX : X86::ECX,
11573                                swapInH, swapInL.getValue(1));
11574     SDValue Ops[] = { swapInH.getValue(0),
11575                       N->getOperand(1),
11576                       swapInH.getValue(1) };
11577     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11578     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11579     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11580                                   X86ISD::LCMPXCHG8_DAG;
11581     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11582                                              Ops, 3, T, MMO);
11583     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11584                                         Regs64bit ? X86::RAX : X86::EAX,
11585                                         HalfT, Result.getValue(1));
11586     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11587                                         Regs64bit ? X86::RDX : X86::EDX,
11588                                         HalfT, cpOutL.getValue(2));
11589     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11590     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11591     Results.push_back(cpOutH.getValue(1));
11592     return;
11593   }
11594   case ISD::ATOMIC_LOAD_ADD:
11595   case ISD::ATOMIC_LOAD_AND:
11596   case ISD::ATOMIC_LOAD_NAND:
11597   case ISD::ATOMIC_LOAD_OR:
11598   case ISD::ATOMIC_LOAD_SUB:
11599   case ISD::ATOMIC_LOAD_XOR:
11600   case ISD::ATOMIC_LOAD_MAX:
11601   case ISD::ATOMIC_LOAD_MIN:
11602   case ISD::ATOMIC_LOAD_UMAX:
11603   case ISD::ATOMIC_LOAD_UMIN:
11604   case ISD::ATOMIC_SWAP: {
11605     unsigned Opc;
11606     switch (N->getOpcode()) {
11607     default: llvm_unreachable("Unexpected opcode");
11608     case ISD::ATOMIC_LOAD_ADD:
11609       Opc = X86ISD::ATOMADD64_DAG;
11610       break;
11611     case ISD::ATOMIC_LOAD_AND:
11612       Opc = X86ISD::ATOMAND64_DAG;
11613       break;
11614     case ISD::ATOMIC_LOAD_NAND:
11615       Opc = X86ISD::ATOMNAND64_DAG;
11616       break;
11617     case ISD::ATOMIC_LOAD_OR:
11618       Opc = X86ISD::ATOMOR64_DAG;
11619       break;
11620     case ISD::ATOMIC_LOAD_SUB:
11621       Opc = X86ISD::ATOMSUB64_DAG;
11622       break;
11623     case ISD::ATOMIC_LOAD_XOR:
11624       Opc = X86ISD::ATOMXOR64_DAG;
11625       break;
11626     case ISD::ATOMIC_LOAD_MAX:
11627       Opc = X86ISD::ATOMMAX64_DAG;
11628       break;
11629     case ISD::ATOMIC_LOAD_MIN:
11630       Opc = X86ISD::ATOMMIN64_DAG;
11631       break;
11632     case ISD::ATOMIC_LOAD_UMAX:
11633       Opc = X86ISD::ATOMUMAX64_DAG;
11634       break;
11635     case ISD::ATOMIC_LOAD_UMIN:
11636       Opc = X86ISD::ATOMUMIN64_DAG;
11637       break;
11638     case ISD::ATOMIC_SWAP:
11639       Opc = X86ISD::ATOMSWAP64_DAG;
11640       break;
11641     }
11642     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11643     return;
11644   }
11645   case ISD::ATOMIC_LOAD:
11646     ReplaceATOMIC_LOAD(N, Results, DAG);
11647   }
11648 }
11649
11650 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11651   switch (Opcode) {
11652   default: return NULL;
11653   case X86ISD::BSF:                return "X86ISD::BSF";
11654   case X86ISD::BSR:                return "X86ISD::BSR";
11655   case X86ISD::SHLD:               return "X86ISD::SHLD";
11656   case X86ISD::SHRD:               return "X86ISD::SHRD";
11657   case X86ISD::FAND:               return "X86ISD::FAND";
11658   case X86ISD::FOR:                return "X86ISD::FOR";
11659   case X86ISD::FXOR:               return "X86ISD::FXOR";
11660   case X86ISD::FSRL:               return "X86ISD::FSRL";
11661   case X86ISD::FILD:               return "X86ISD::FILD";
11662   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11663   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11664   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11665   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11666   case X86ISD::FLD:                return "X86ISD::FLD";
11667   case X86ISD::FST:                return "X86ISD::FST";
11668   case X86ISD::CALL:               return "X86ISD::CALL";
11669   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11670   case X86ISD::BT:                 return "X86ISD::BT";
11671   case X86ISD::CMP:                return "X86ISD::CMP";
11672   case X86ISD::COMI:               return "X86ISD::COMI";
11673   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11674   case X86ISD::SETCC:              return "X86ISD::SETCC";
11675   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11676   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11677   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11678   case X86ISD::CMOV:               return "X86ISD::CMOV";
11679   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11680   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11681   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11682   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11683   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11684   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11685   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11686   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11687   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11688   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11689   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11690   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11691   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11692   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11693   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11694   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11695   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11696   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11697   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11698   case X86ISD::HADD:               return "X86ISD::HADD";
11699   case X86ISD::HSUB:               return "X86ISD::HSUB";
11700   case X86ISD::FHADD:              return "X86ISD::FHADD";
11701   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11702   case X86ISD::FMAX:               return "X86ISD::FMAX";
11703   case X86ISD::FMIN:               return "X86ISD::FMIN";
11704   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11705   case X86ISD::FMINC:              return "X86ISD::FMINC";
11706   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11707   case X86ISD::FRCP:               return "X86ISD::FRCP";
11708   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11709   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11710   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11711   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11712   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11713   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11714   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11715   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11716   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11717   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11718   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11719   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11720   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11721   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11722   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11723   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11724   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11725   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11726   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11727   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11728   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11729   case X86ISD::VSHL:               return "X86ISD::VSHL";
11730   case X86ISD::VSRL:               return "X86ISD::VSRL";
11731   case X86ISD::VSRA:               return "X86ISD::VSRA";
11732   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11733   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11734   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11735   case X86ISD::CMPP:               return "X86ISD::CMPP";
11736   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11737   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11738   case X86ISD::ADD:                return "X86ISD::ADD";
11739   case X86ISD::SUB:                return "X86ISD::SUB";
11740   case X86ISD::ADC:                return "X86ISD::ADC";
11741   case X86ISD::SBB:                return "X86ISD::SBB";
11742   case X86ISD::SMUL:               return "X86ISD::SMUL";
11743   case X86ISD::UMUL:               return "X86ISD::UMUL";
11744   case X86ISD::INC:                return "X86ISD::INC";
11745   case X86ISD::DEC:                return "X86ISD::DEC";
11746   case X86ISD::OR:                 return "X86ISD::OR";
11747   case X86ISD::XOR:                return "X86ISD::XOR";
11748   case X86ISD::AND:                return "X86ISD::AND";
11749   case X86ISD::ANDN:               return "X86ISD::ANDN";
11750   case X86ISD::BLSI:               return "X86ISD::BLSI";
11751   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11752   case X86ISD::BLSR:               return "X86ISD::BLSR";
11753   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11754   case X86ISD::PTEST:              return "X86ISD::PTEST";
11755   case X86ISD::TESTP:              return "X86ISD::TESTP";
11756   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11757   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11758   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11759   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11760   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11761   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11762   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11763   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11764   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11765   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11766   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11767   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11768   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11769   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11770   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11771   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11772   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11773   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11774   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11775   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11776   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11777   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11778   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11779   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11780   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11781   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11782   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11783   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11784   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11785   case X86ISD::SAHF:               return "X86ISD::SAHF";
11786   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11787   case X86ISD::FMADD:              return "X86ISD::FMADD";
11788   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11789   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11790   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11791   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11792   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11793   }
11794 }
11795
11796 // isLegalAddressingMode - Return true if the addressing mode represented
11797 // by AM is legal for this target, for a load/store of the specified type.
11798 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11799                                               Type *Ty) const {
11800   // X86 supports extremely general addressing modes.
11801   CodeModel::Model M = getTargetMachine().getCodeModel();
11802   Reloc::Model R = getTargetMachine().getRelocationModel();
11803
11804   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11805   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11806     return false;
11807
11808   if (AM.BaseGV) {
11809     unsigned GVFlags =
11810       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11811
11812     // If a reference to this global requires an extra load, we can't fold it.
11813     if (isGlobalStubReference(GVFlags))
11814       return false;
11815
11816     // If BaseGV requires a register for the PIC base, we cannot also have a
11817     // BaseReg specified.
11818     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11819       return false;
11820
11821     // If lower 4G is not available, then we must use rip-relative addressing.
11822     if ((M != CodeModel::Small || R != Reloc::Static) &&
11823         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11824       return false;
11825   }
11826
11827   switch (AM.Scale) {
11828   case 0:
11829   case 1:
11830   case 2:
11831   case 4:
11832   case 8:
11833     // These scales always work.
11834     break;
11835   case 3:
11836   case 5:
11837   case 9:
11838     // These scales are formed with basereg+scalereg.  Only accept if there is
11839     // no basereg yet.
11840     if (AM.HasBaseReg)
11841       return false;
11842     break;
11843   default:  // Other stuff never works.
11844     return false;
11845   }
11846
11847   return true;
11848 }
11849
11850
11851 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11852   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11853     return false;
11854   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11855   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11856   if (NumBits1 <= NumBits2)
11857     return false;
11858   return true;
11859 }
11860
11861 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11862   return Imm == (int32_t)Imm;
11863 }
11864
11865 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11866   // Can also use sub to handle negated immediates.
11867   return Imm == (int32_t)Imm;
11868 }
11869
11870 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11871   if (!VT1.isInteger() || !VT2.isInteger())
11872     return false;
11873   unsigned NumBits1 = VT1.getSizeInBits();
11874   unsigned NumBits2 = VT2.getSizeInBits();
11875   if (NumBits1 <= NumBits2)
11876     return false;
11877   return true;
11878 }
11879
11880 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11881   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11882   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11883 }
11884
11885 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11886   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11887   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11888 }
11889
11890 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11891   // i16 instructions are longer (0x66 prefix) and potentially slower.
11892   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11893 }
11894
11895 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11896 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11897 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11898 /// are assumed to be legal.
11899 bool
11900 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11901                                       EVT VT) const {
11902   // Very little shuffling can be done for 64-bit vectors right now.
11903   if (VT.getSizeInBits() == 64)
11904     return false;
11905
11906   // FIXME: pshufb, blends, shifts.
11907   return (VT.getVectorNumElements() == 2 ||
11908           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11909           isMOVLMask(M, VT) ||
11910           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11911           isPSHUFDMask(M, VT) ||
11912           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11913           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11914           isPALIGNRMask(M, VT, Subtarget) ||
11915           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11916           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11917           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11918           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11919 }
11920
11921 bool
11922 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11923                                           EVT VT) const {
11924   unsigned NumElts = VT.getVectorNumElements();
11925   // FIXME: This collection of masks seems suspect.
11926   if (NumElts == 2)
11927     return true;
11928   if (NumElts == 4 && VT.is128BitVector()) {
11929     return (isMOVLMask(Mask, VT)  ||
11930             isCommutedMOVLMask(Mask, VT, true) ||
11931             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11932             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11933   }
11934   return false;
11935 }
11936
11937 //===----------------------------------------------------------------------===//
11938 //                           X86 Scheduler Hooks
11939 //===----------------------------------------------------------------------===//
11940
11941 // private utility function
11942
11943 // Get CMPXCHG opcode for the specified data type.
11944 static unsigned getCmpXChgOpcode(EVT VT) {
11945   switch (VT.getSimpleVT().SimpleTy) {
11946   case MVT::i8:  return X86::LCMPXCHG8;
11947   case MVT::i16: return X86::LCMPXCHG16;
11948   case MVT::i32: return X86::LCMPXCHG32;
11949   case MVT::i64: return X86::LCMPXCHG64;
11950   default:
11951     break;
11952   }
11953   llvm_unreachable("Invalid operand size!");
11954 }
11955
11956 // Get LOAD opcode for the specified data type.
11957 static unsigned getLoadOpcode(EVT VT) {
11958   switch (VT.getSimpleVT().SimpleTy) {
11959   case MVT::i8:  return X86::MOV8rm;
11960   case MVT::i16: return X86::MOV16rm;
11961   case MVT::i32: return X86::MOV32rm;
11962   case MVT::i64: return X86::MOV64rm;
11963   default:
11964     break;
11965   }
11966   llvm_unreachable("Invalid operand size!");
11967 }
11968
11969 // Get opcode of the non-atomic one from the specified atomic instruction.
11970 static unsigned getNonAtomicOpcode(unsigned Opc) {
11971   switch (Opc) {
11972   case X86::ATOMAND8:  return X86::AND8rr;
11973   case X86::ATOMAND16: return X86::AND16rr;
11974   case X86::ATOMAND32: return X86::AND32rr;
11975   case X86::ATOMAND64: return X86::AND64rr;
11976   case X86::ATOMOR8:   return X86::OR8rr;
11977   case X86::ATOMOR16:  return X86::OR16rr;
11978   case X86::ATOMOR32:  return X86::OR32rr;
11979   case X86::ATOMOR64:  return X86::OR64rr;
11980   case X86::ATOMXOR8:  return X86::XOR8rr;
11981   case X86::ATOMXOR16: return X86::XOR16rr;
11982   case X86::ATOMXOR32: return X86::XOR32rr;
11983   case X86::ATOMXOR64: return X86::XOR64rr;
11984   }
11985   llvm_unreachable("Unhandled atomic-load-op opcode!");
11986 }
11987
11988 // Get opcode of the non-atomic one from the specified atomic instruction with
11989 // extra opcode.
11990 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11991                                                unsigned &ExtraOpc) {
11992   switch (Opc) {
11993   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
11994   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
11995   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
11996   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
11997   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
11998   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
11999   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12000   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12001   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12002   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12003   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12004   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12005   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12006   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12007   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12008   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12009   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12010   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12011   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12012   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12013   }
12014   llvm_unreachable("Unhandled atomic-load-op opcode!");
12015 }
12016
12017 // Get opcode of the non-atomic one from the specified atomic instruction for
12018 // 64-bit data type on 32-bit target.
12019 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12020   switch (Opc) {
12021   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12022   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12023   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12024   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12025   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12026   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12027   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12028   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12029   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12030   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12031   }
12032   llvm_unreachable("Unhandled atomic-load-op opcode!");
12033 }
12034
12035 // Get opcode of the non-atomic one from the specified atomic instruction for
12036 // 64-bit data type on 32-bit target with extra opcode.
12037 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12038                                                    unsigned &HiOpc,
12039                                                    unsigned &ExtraOpc) {
12040   switch (Opc) {
12041   case X86::ATOMNAND6432:
12042     ExtraOpc = X86::NOT32r;
12043     HiOpc = X86::AND32rr;
12044     return X86::AND32rr;
12045   }
12046   llvm_unreachable("Unhandled atomic-load-op opcode!");
12047 }
12048
12049 // Get pseudo CMOV opcode from the specified data type.
12050 static unsigned getPseudoCMOVOpc(EVT VT) {
12051   switch (VT.getSimpleVT().SimpleTy) {
12052   case MVT::i8:  return X86::CMOV_GR8;
12053   case MVT::i16: return X86::CMOV_GR16;
12054   case MVT::i32: return X86::CMOV_GR32;
12055   default:
12056     break;
12057   }
12058   llvm_unreachable("Unknown CMOV opcode!");
12059 }
12060
12061 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12062 // They will be translated into a spin-loop or compare-exchange loop from
12063 //
12064 //    ...
12065 //    dst = atomic-fetch-op MI.addr, MI.val
12066 //    ...
12067 //
12068 // to
12069 //
12070 //    ...
12071 //    EAX = LOAD MI.addr
12072 // loop:
12073 //    t1 = OP MI.val, EAX
12074 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12075 //    JNE loop
12076 // sink:
12077 //    dst = EAX
12078 //    ...
12079 MachineBasicBlock *
12080 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12081                                        MachineBasicBlock *MBB) const {
12082   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12083   DebugLoc DL = MI->getDebugLoc();
12084
12085   MachineFunction *MF = MBB->getParent();
12086   MachineRegisterInfo &MRI = MF->getRegInfo();
12087
12088   const BasicBlock *BB = MBB->getBasicBlock();
12089   MachineFunction::iterator I = MBB;
12090   ++I;
12091
12092   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12093          "Unexpected number of operands");
12094
12095   assert(MI->hasOneMemOperand() &&
12096          "Expected atomic-load-op to have one memoperand");
12097
12098   // Memory Reference
12099   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12100   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12101
12102   unsigned DstReg, SrcReg;
12103   unsigned MemOpndSlot;
12104
12105   unsigned CurOp = 0;
12106
12107   DstReg = MI->getOperand(CurOp++).getReg();
12108   MemOpndSlot = CurOp;
12109   CurOp += X86::AddrNumOperands;
12110   SrcReg = MI->getOperand(CurOp++).getReg();
12111
12112   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12113   EVT VT = *RC->vt_begin();
12114   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12115
12116   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12117   unsigned LOADOpc = getLoadOpcode(VT);
12118
12119   // For the atomic load-arith operator, we generate
12120   //
12121   //  thisMBB:
12122   //    EAX = LOAD [MI.addr]
12123   //  mainMBB:
12124   //    t1 = OP MI.val, EAX
12125   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12126   //    JNE mainMBB
12127   //  sinkMBB:
12128
12129   MachineBasicBlock *thisMBB = MBB;
12130   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12131   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12132   MF->insert(I, mainMBB);
12133   MF->insert(I, sinkMBB);
12134
12135   MachineInstrBuilder MIB;
12136
12137   // Transfer the remainder of BB and its successor edges to sinkMBB.
12138   sinkMBB->splice(sinkMBB->begin(), MBB,
12139                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12140   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12141
12142   // thisMBB:
12143   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12144   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12145     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12146   MIB.setMemRefs(MMOBegin, MMOEnd);
12147
12148   thisMBB->addSuccessor(mainMBB);
12149
12150   // mainMBB:
12151   MachineBasicBlock *origMainMBB = mainMBB;
12152   mainMBB->addLiveIn(AccPhyReg);
12153
12154   // Copy AccPhyReg as it is used more than once.
12155   unsigned AccReg = MRI.createVirtualRegister(RC);
12156   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12157     .addReg(AccPhyReg);
12158
12159   unsigned t1 = MRI.createVirtualRegister(RC);
12160   unsigned Opc = MI->getOpcode();
12161   switch (Opc) {
12162   default:
12163     llvm_unreachable("Unhandled atomic-load-op opcode!");
12164   case X86::ATOMAND8:
12165   case X86::ATOMAND16:
12166   case X86::ATOMAND32:
12167   case X86::ATOMAND64:
12168   case X86::ATOMOR8:
12169   case X86::ATOMOR16:
12170   case X86::ATOMOR32:
12171   case X86::ATOMOR64:
12172   case X86::ATOMXOR8:
12173   case X86::ATOMXOR16:
12174   case X86::ATOMXOR32:
12175   case X86::ATOMXOR64: {
12176     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12177     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12178       .addReg(AccReg);
12179     break;
12180   }
12181   case X86::ATOMNAND8:
12182   case X86::ATOMNAND16:
12183   case X86::ATOMNAND32:
12184   case X86::ATOMNAND64: {
12185     unsigned t2 = MRI.createVirtualRegister(RC);
12186     unsigned NOTOpc;
12187     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12188     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12189       .addReg(AccReg);
12190     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12191     break;
12192   }
12193   case X86::ATOMMAX8:
12194   case X86::ATOMMAX16:
12195   case X86::ATOMMAX32:
12196   case X86::ATOMMAX64:
12197   case X86::ATOMMIN8:
12198   case X86::ATOMMIN16:
12199   case X86::ATOMMIN32:
12200   case X86::ATOMMIN64:
12201   case X86::ATOMUMAX8:
12202   case X86::ATOMUMAX16:
12203   case X86::ATOMUMAX32:
12204   case X86::ATOMUMAX64:
12205   case X86::ATOMUMIN8:
12206   case X86::ATOMUMIN16:
12207   case X86::ATOMUMIN32:
12208   case X86::ATOMUMIN64: {
12209     unsigned CMPOpc;
12210     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12211
12212     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12213       .addReg(SrcReg)
12214       .addReg(AccReg);
12215
12216     if (Subtarget->hasCMov()) {
12217       if (VT != MVT::i8) {
12218         // Native support
12219         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12220           .addReg(SrcReg)
12221           .addReg(AccReg);
12222       } else {
12223         // Promote i8 to i32 to use CMOV32
12224         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12225         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12226         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12227         unsigned t2 = MRI.createVirtualRegister(RC32);
12228
12229         unsigned Undef = MRI.createVirtualRegister(RC32);
12230         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12231
12232         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12233           .addReg(Undef)
12234           .addReg(SrcReg)
12235           .addImm(X86::sub_8bit);
12236         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12237           .addReg(Undef)
12238           .addReg(AccReg)
12239           .addImm(X86::sub_8bit);
12240
12241         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12242           .addReg(SrcReg32)
12243           .addReg(AccReg32);
12244
12245         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12246           .addReg(t2, 0, X86::sub_8bit);
12247       }
12248     } else {
12249       // Use pseudo select and lower them.
12250       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12251              "Invalid atomic-load-op transformation!");
12252       unsigned SelOpc = getPseudoCMOVOpc(VT);
12253       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12254       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12255       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12256               .addReg(SrcReg).addReg(AccReg)
12257               .addImm(CC);
12258       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12259     }
12260     break;
12261   }
12262   }
12263
12264   // Copy AccPhyReg back from virtual register.
12265   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12266     .addReg(AccReg);
12267
12268   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12269   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12270     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12271   MIB.addReg(t1);
12272   MIB.setMemRefs(MMOBegin, MMOEnd);
12273
12274   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12275
12276   mainMBB->addSuccessor(origMainMBB);
12277   mainMBB->addSuccessor(sinkMBB);
12278
12279   // sinkMBB:
12280   sinkMBB->addLiveIn(AccPhyReg);
12281
12282   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12283           TII->get(TargetOpcode::COPY), DstReg)
12284     .addReg(AccPhyReg);
12285
12286   MI->eraseFromParent();
12287   return sinkMBB;
12288 }
12289
12290 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12291 // instructions. They will be translated into a spin-loop or compare-exchange
12292 // loop from
12293 //
12294 //    ...
12295 //    dst = atomic-fetch-op MI.addr, MI.val
12296 //    ...
12297 //
12298 // to
12299 //
12300 //    ...
12301 //    EAX = LOAD [MI.addr + 0]
12302 //    EDX = LOAD [MI.addr + 4]
12303 // loop:
12304 //    EBX = OP MI.val.lo, EAX
12305 //    ECX = OP MI.val.hi, EDX
12306 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12307 //    JNE loop
12308 // sink:
12309 //    dst = EDX:EAX
12310 //    ...
12311 MachineBasicBlock *
12312 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12313                                            MachineBasicBlock *MBB) const {
12314   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12315   DebugLoc DL = MI->getDebugLoc();
12316
12317   MachineFunction *MF = MBB->getParent();
12318   MachineRegisterInfo &MRI = MF->getRegInfo();
12319
12320   const BasicBlock *BB = MBB->getBasicBlock();
12321   MachineFunction::iterator I = MBB;
12322   ++I;
12323
12324   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12325          "Unexpected number of operands");
12326
12327   assert(MI->hasOneMemOperand() &&
12328          "Expected atomic-load-op32 to have one memoperand");
12329
12330   // Memory Reference
12331   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12332   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12333
12334   unsigned DstLoReg, DstHiReg;
12335   unsigned SrcLoReg, SrcHiReg;
12336   unsigned MemOpndSlot;
12337
12338   unsigned CurOp = 0;
12339
12340   DstLoReg = MI->getOperand(CurOp++).getReg();
12341   DstHiReg = MI->getOperand(CurOp++).getReg();
12342   MemOpndSlot = CurOp;
12343   CurOp += X86::AddrNumOperands;
12344   SrcLoReg = MI->getOperand(CurOp++).getReg();
12345   SrcHiReg = MI->getOperand(CurOp++).getReg();
12346
12347   const TargetRegisterClass *RC = &X86::GR32RegClass;
12348   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12349
12350   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12351   unsigned LOADOpc = X86::MOV32rm;
12352
12353   // For the atomic load-arith operator, we generate
12354   //
12355   //  thisMBB:
12356   //    EAX = LOAD [MI.addr + 0]
12357   //    EDX = LOAD [MI.addr + 4]
12358   //  mainMBB:
12359   //    EBX = OP MI.vallo, EAX
12360   //    ECX = OP MI.valhi, EDX
12361   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12362   //    JNE mainMBB
12363   //  sinkMBB:
12364
12365   MachineBasicBlock *thisMBB = MBB;
12366   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12367   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12368   MF->insert(I, mainMBB);
12369   MF->insert(I, sinkMBB);
12370
12371   MachineInstrBuilder MIB;
12372
12373   // Transfer the remainder of BB and its successor edges to sinkMBB.
12374   sinkMBB->splice(sinkMBB->begin(), MBB,
12375                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12376   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12377
12378   // thisMBB:
12379   // Lo
12380   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12381   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12382     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12383   MIB.setMemRefs(MMOBegin, MMOEnd);
12384   // Hi
12385   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12386   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12387     if (i == X86::AddrDisp)
12388       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12389     else
12390       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12391   }
12392   MIB.setMemRefs(MMOBegin, MMOEnd);
12393
12394   thisMBB->addSuccessor(mainMBB);
12395
12396   // mainMBB:
12397   MachineBasicBlock *origMainMBB = mainMBB;
12398   mainMBB->addLiveIn(X86::EAX);
12399   mainMBB->addLiveIn(X86::EDX);
12400
12401   // Copy EDX:EAX as they are used more than once.
12402   unsigned LoReg = MRI.createVirtualRegister(RC);
12403   unsigned HiReg = MRI.createVirtualRegister(RC);
12404   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12405   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12406
12407   unsigned t1L = MRI.createVirtualRegister(RC);
12408   unsigned t1H = MRI.createVirtualRegister(RC);
12409
12410   unsigned Opc = MI->getOpcode();
12411   switch (Opc) {
12412   default:
12413     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12414   case X86::ATOMAND6432:
12415   case X86::ATOMOR6432:
12416   case X86::ATOMXOR6432:
12417   case X86::ATOMADD6432:
12418   case X86::ATOMSUB6432: {
12419     unsigned HiOpc;
12420     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12421     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12422     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12423     break;
12424   }
12425   case X86::ATOMNAND6432: {
12426     unsigned HiOpc, NOTOpc;
12427     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12428     unsigned t2L = MRI.createVirtualRegister(RC);
12429     unsigned t2H = MRI.createVirtualRegister(RC);
12430     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12431     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12432     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12433     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12434     break;
12435   }
12436   case X86::ATOMMAX6432:
12437   case X86::ATOMMIN6432:
12438   case X86::ATOMUMAX6432:
12439   case X86::ATOMUMIN6432: {
12440     unsigned HiOpc;
12441     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12442     unsigned cL = MRI.createVirtualRegister(RC8);
12443     unsigned cH = MRI.createVirtualRegister(RC8);
12444     unsigned cL32 = MRI.createVirtualRegister(RC);
12445     unsigned cH32 = MRI.createVirtualRegister(RC);
12446     unsigned cc = MRI.createVirtualRegister(RC);
12447     // cl := cmp src_lo, lo
12448     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12449       .addReg(SrcLoReg).addReg(LoReg);
12450     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12451     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12452     // ch := cmp src_hi, hi
12453     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12454       .addReg(SrcHiReg).addReg(HiReg);
12455     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12456     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12457     // cc := if (src_hi == hi) ? cl : ch;
12458     if (Subtarget->hasCMov()) {
12459       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12460         .addReg(cH32).addReg(cL32);
12461     } else {
12462       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12463               .addReg(cH32).addReg(cL32)
12464               .addImm(X86::COND_E);
12465       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12466     }
12467     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12468     if (Subtarget->hasCMov()) {
12469       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12470         .addReg(SrcLoReg).addReg(LoReg);
12471       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12472         .addReg(SrcHiReg).addReg(HiReg);
12473     } else {
12474       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12475               .addReg(SrcLoReg).addReg(LoReg)
12476               .addImm(X86::COND_NE);
12477       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12478       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12479               .addReg(SrcHiReg).addReg(HiReg)
12480               .addImm(X86::COND_NE);
12481       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12482     }
12483     break;
12484   }
12485   case X86::ATOMSWAP6432: {
12486     unsigned HiOpc;
12487     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12488     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12489     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12490     break;
12491   }
12492   }
12493
12494   // Copy EDX:EAX back from HiReg:LoReg
12495   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12496   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12497   // Copy ECX:EBX from t1H:t1L
12498   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12499   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12500
12501   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12502   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12503     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12504   MIB.setMemRefs(MMOBegin, MMOEnd);
12505
12506   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12507
12508   mainMBB->addSuccessor(origMainMBB);
12509   mainMBB->addSuccessor(sinkMBB);
12510
12511   // sinkMBB:
12512   sinkMBB->addLiveIn(X86::EAX);
12513   sinkMBB->addLiveIn(X86::EDX);
12514
12515   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12516           TII->get(TargetOpcode::COPY), DstLoReg)
12517     .addReg(X86::EAX);
12518   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12519           TII->get(TargetOpcode::COPY), DstHiReg)
12520     .addReg(X86::EDX);
12521
12522   MI->eraseFromParent();
12523   return sinkMBB;
12524 }
12525
12526 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12527 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12528 // in the .td file.
12529 MachineBasicBlock *
12530 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12531                             unsigned numArgs, bool memArg) const {
12532   assert(Subtarget->hasSSE42() &&
12533          "Target must have SSE4.2 or AVX features enabled");
12534
12535   DebugLoc dl = MI->getDebugLoc();
12536   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12537   unsigned Opc;
12538   if (!Subtarget->hasAVX()) {
12539     if (memArg)
12540       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12541     else
12542       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12543   } else {
12544     if (memArg)
12545       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12546     else
12547       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12548   }
12549
12550   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12551   for (unsigned i = 0; i < numArgs; ++i) {
12552     MachineOperand &Op = MI->getOperand(i+1);
12553     if (!(Op.isReg() && Op.isImplicit()))
12554       MIB.addOperand(Op);
12555   }
12556   BuildMI(*BB, MI, dl,
12557     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12558     .addReg(X86::XMM0);
12559
12560   MI->eraseFromParent();
12561   return BB;
12562 }
12563
12564 MachineBasicBlock *
12565 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12566   DebugLoc dl = MI->getDebugLoc();
12567   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12568
12569   // Address into RAX/EAX, other two args into ECX, EDX.
12570   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12571   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12572   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12573   for (int i = 0; i < X86::AddrNumOperands; ++i)
12574     MIB.addOperand(MI->getOperand(i));
12575
12576   unsigned ValOps = X86::AddrNumOperands;
12577   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12578     .addReg(MI->getOperand(ValOps).getReg());
12579   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12580     .addReg(MI->getOperand(ValOps+1).getReg());
12581
12582   // The instruction doesn't actually take any operands though.
12583   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12584
12585   MI->eraseFromParent(); // The pseudo is gone now.
12586   return BB;
12587 }
12588
12589 MachineBasicBlock *
12590 X86TargetLowering::EmitVAARG64WithCustomInserter(
12591                    MachineInstr *MI,
12592                    MachineBasicBlock *MBB) const {
12593   // Emit va_arg instruction on X86-64.
12594
12595   // Operands to this pseudo-instruction:
12596   // 0  ) Output        : destination address (reg)
12597   // 1-5) Input         : va_list address (addr, i64mem)
12598   // 6  ) ArgSize       : Size (in bytes) of vararg type
12599   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12600   // 8  ) Align         : Alignment of type
12601   // 9  ) EFLAGS (implicit-def)
12602
12603   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12604   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12605
12606   unsigned DestReg = MI->getOperand(0).getReg();
12607   MachineOperand &Base = MI->getOperand(1);
12608   MachineOperand &Scale = MI->getOperand(2);
12609   MachineOperand &Index = MI->getOperand(3);
12610   MachineOperand &Disp = MI->getOperand(4);
12611   MachineOperand &Segment = MI->getOperand(5);
12612   unsigned ArgSize = MI->getOperand(6).getImm();
12613   unsigned ArgMode = MI->getOperand(7).getImm();
12614   unsigned Align = MI->getOperand(8).getImm();
12615
12616   // Memory Reference
12617   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12618   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12619   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12620
12621   // Machine Information
12622   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12623   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12624   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12625   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12626   DebugLoc DL = MI->getDebugLoc();
12627
12628   // struct va_list {
12629   //   i32   gp_offset
12630   //   i32   fp_offset
12631   //   i64   overflow_area (address)
12632   //   i64   reg_save_area (address)
12633   // }
12634   // sizeof(va_list) = 24
12635   // alignment(va_list) = 8
12636
12637   unsigned TotalNumIntRegs = 6;
12638   unsigned TotalNumXMMRegs = 8;
12639   bool UseGPOffset = (ArgMode == 1);
12640   bool UseFPOffset = (ArgMode == 2);
12641   unsigned MaxOffset = TotalNumIntRegs * 8 +
12642                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12643
12644   /* Align ArgSize to a multiple of 8 */
12645   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12646   bool NeedsAlign = (Align > 8);
12647
12648   MachineBasicBlock *thisMBB = MBB;
12649   MachineBasicBlock *overflowMBB;
12650   MachineBasicBlock *offsetMBB;
12651   MachineBasicBlock *endMBB;
12652
12653   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12654   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12655   unsigned OffsetReg = 0;
12656
12657   if (!UseGPOffset && !UseFPOffset) {
12658     // If we only pull from the overflow region, we don't create a branch.
12659     // We don't need to alter control flow.
12660     OffsetDestReg = 0; // unused
12661     OverflowDestReg = DestReg;
12662
12663     offsetMBB = NULL;
12664     overflowMBB = thisMBB;
12665     endMBB = thisMBB;
12666   } else {
12667     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12668     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12669     // If not, pull from overflow_area. (branch to overflowMBB)
12670     //
12671     //       thisMBB
12672     //         |     .
12673     //         |        .
12674     //     offsetMBB   overflowMBB
12675     //         |        .
12676     //         |     .
12677     //        endMBB
12678
12679     // Registers for the PHI in endMBB
12680     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12681     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12682
12683     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12684     MachineFunction *MF = MBB->getParent();
12685     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12686     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12687     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12688
12689     MachineFunction::iterator MBBIter = MBB;
12690     ++MBBIter;
12691
12692     // Insert the new basic blocks
12693     MF->insert(MBBIter, offsetMBB);
12694     MF->insert(MBBIter, overflowMBB);
12695     MF->insert(MBBIter, endMBB);
12696
12697     // Transfer the remainder of MBB and its successor edges to endMBB.
12698     endMBB->splice(endMBB->begin(), thisMBB,
12699                     llvm::next(MachineBasicBlock::iterator(MI)),
12700                     thisMBB->end());
12701     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12702
12703     // Make offsetMBB and overflowMBB successors of thisMBB
12704     thisMBB->addSuccessor(offsetMBB);
12705     thisMBB->addSuccessor(overflowMBB);
12706
12707     // endMBB is a successor of both offsetMBB and overflowMBB
12708     offsetMBB->addSuccessor(endMBB);
12709     overflowMBB->addSuccessor(endMBB);
12710
12711     // Load the offset value into a register
12712     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12713     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12714       .addOperand(Base)
12715       .addOperand(Scale)
12716       .addOperand(Index)
12717       .addDisp(Disp, UseFPOffset ? 4 : 0)
12718       .addOperand(Segment)
12719       .setMemRefs(MMOBegin, MMOEnd);
12720
12721     // Check if there is enough room left to pull this argument.
12722     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12723       .addReg(OffsetReg)
12724       .addImm(MaxOffset + 8 - ArgSizeA8);
12725
12726     // Branch to "overflowMBB" if offset >= max
12727     // Fall through to "offsetMBB" otherwise
12728     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12729       .addMBB(overflowMBB);
12730   }
12731
12732   // In offsetMBB, emit code to use the reg_save_area.
12733   if (offsetMBB) {
12734     assert(OffsetReg != 0);
12735
12736     // Read the reg_save_area address.
12737     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12738     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12739       .addOperand(Base)
12740       .addOperand(Scale)
12741       .addOperand(Index)
12742       .addDisp(Disp, 16)
12743       .addOperand(Segment)
12744       .setMemRefs(MMOBegin, MMOEnd);
12745
12746     // Zero-extend the offset
12747     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12748       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12749         .addImm(0)
12750         .addReg(OffsetReg)
12751         .addImm(X86::sub_32bit);
12752
12753     // Add the offset to the reg_save_area to get the final address.
12754     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12755       .addReg(OffsetReg64)
12756       .addReg(RegSaveReg);
12757
12758     // Compute the offset for the next argument
12759     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12760     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12761       .addReg(OffsetReg)
12762       .addImm(UseFPOffset ? 16 : 8);
12763
12764     // Store it back into the va_list.
12765     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12766       .addOperand(Base)
12767       .addOperand(Scale)
12768       .addOperand(Index)
12769       .addDisp(Disp, UseFPOffset ? 4 : 0)
12770       .addOperand(Segment)
12771       .addReg(NextOffsetReg)
12772       .setMemRefs(MMOBegin, MMOEnd);
12773
12774     // Jump to endMBB
12775     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12776       .addMBB(endMBB);
12777   }
12778
12779   //
12780   // Emit code to use overflow area
12781   //
12782
12783   // Load the overflow_area address into a register.
12784   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12785   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12786     .addOperand(Base)
12787     .addOperand(Scale)
12788     .addOperand(Index)
12789     .addDisp(Disp, 8)
12790     .addOperand(Segment)
12791     .setMemRefs(MMOBegin, MMOEnd);
12792
12793   // If we need to align it, do so. Otherwise, just copy the address
12794   // to OverflowDestReg.
12795   if (NeedsAlign) {
12796     // Align the overflow address
12797     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12798     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12799
12800     // aligned_addr = (addr + (align-1)) & ~(align-1)
12801     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12802       .addReg(OverflowAddrReg)
12803       .addImm(Align-1);
12804
12805     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12806       .addReg(TmpReg)
12807       .addImm(~(uint64_t)(Align-1));
12808   } else {
12809     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12810       .addReg(OverflowAddrReg);
12811   }
12812
12813   // Compute the next overflow address after this argument.
12814   // (the overflow address should be kept 8-byte aligned)
12815   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12816   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12817     .addReg(OverflowDestReg)
12818     .addImm(ArgSizeA8);
12819
12820   // Store the new overflow address.
12821   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12822     .addOperand(Base)
12823     .addOperand(Scale)
12824     .addOperand(Index)
12825     .addDisp(Disp, 8)
12826     .addOperand(Segment)
12827     .addReg(NextAddrReg)
12828     .setMemRefs(MMOBegin, MMOEnd);
12829
12830   // If we branched, emit the PHI to the front of endMBB.
12831   if (offsetMBB) {
12832     BuildMI(*endMBB, endMBB->begin(), DL,
12833             TII->get(X86::PHI), DestReg)
12834       .addReg(OffsetDestReg).addMBB(offsetMBB)
12835       .addReg(OverflowDestReg).addMBB(overflowMBB);
12836   }
12837
12838   // Erase the pseudo instruction
12839   MI->eraseFromParent();
12840
12841   return endMBB;
12842 }
12843
12844 MachineBasicBlock *
12845 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12846                                                  MachineInstr *MI,
12847                                                  MachineBasicBlock *MBB) const {
12848   // Emit code to save XMM registers to the stack. The ABI says that the
12849   // number of registers to save is given in %al, so it's theoretically
12850   // possible to do an indirect jump trick to avoid saving all of them,
12851   // however this code takes a simpler approach and just executes all
12852   // of the stores if %al is non-zero. It's less code, and it's probably
12853   // easier on the hardware branch predictor, and stores aren't all that
12854   // expensive anyway.
12855
12856   // Create the new basic blocks. One block contains all the XMM stores,
12857   // and one block is the final destination regardless of whether any
12858   // stores were performed.
12859   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12860   MachineFunction *F = MBB->getParent();
12861   MachineFunction::iterator MBBIter = MBB;
12862   ++MBBIter;
12863   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12864   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12865   F->insert(MBBIter, XMMSaveMBB);
12866   F->insert(MBBIter, EndMBB);
12867
12868   // Transfer the remainder of MBB and its successor edges to EndMBB.
12869   EndMBB->splice(EndMBB->begin(), MBB,
12870                  llvm::next(MachineBasicBlock::iterator(MI)),
12871                  MBB->end());
12872   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12873
12874   // The original block will now fall through to the XMM save block.
12875   MBB->addSuccessor(XMMSaveMBB);
12876   // The XMMSaveMBB will fall through to the end block.
12877   XMMSaveMBB->addSuccessor(EndMBB);
12878
12879   // Now add the instructions.
12880   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12881   DebugLoc DL = MI->getDebugLoc();
12882
12883   unsigned CountReg = MI->getOperand(0).getReg();
12884   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12885   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12886
12887   if (!Subtarget->isTargetWin64()) {
12888     // If %al is 0, branch around the XMM save block.
12889     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12890     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12891     MBB->addSuccessor(EndMBB);
12892   }
12893
12894   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12895   // In the XMM save block, save all the XMM argument registers.
12896   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12897     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12898     MachineMemOperand *MMO =
12899       F->getMachineMemOperand(
12900           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12901         MachineMemOperand::MOStore,
12902         /*Size=*/16, /*Align=*/16);
12903     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12904       .addFrameIndex(RegSaveFrameIndex)
12905       .addImm(/*Scale=*/1)
12906       .addReg(/*IndexReg=*/0)
12907       .addImm(/*Disp=*/Offset)
12908       .addReg(/*Segment=*/0)
12909       .addReg(MI->getOperand(i).getReg())
12910       .addMemOperand(MMO);
12911   }
12912
12913   MI->eraseFromParent();   // The pseudo instruction is gone now.
12914
12915   return EndMBB;
12916 }
12917
12918 // The EFLAGS operand of SelectItr might be missing a kill marker
12919 // because there were multiple uses of EFLAGS, and ISel didn't know
12920 // which to mark. Figure out whether SelectItr should have had a
12921 // kill marker, and set it if it should. Returns the correct kill
12922 // marker value.
12923 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12924                                      MachineBasicBlock* BB,
12925                                      const TargetRegisterInfo* TRI) {
12926   // Scan forward through BB for a use/def of EFLAGS.
12927   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12928   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12929     const MachineInstr& mi = *miI;
12930     if (mi.readsRegister(X86::EFLAGS))
12931       return false;
12932     if (mi.definesRegister(X86::EFLAGS))
12933       break; // Should have kill-flag - update below.
12934   }
12935
12936   // If we hit the end of the block, check whether EFLAGS is live into a
12937   // successor.
12938   if (miI == BB->end()) {
12939     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12940                                           sEnd = BB->succ_end();
12941          sItr != sEnd; ++sItr) {
12942       MachineBasicBlock* succ = *sItr;
12943       if (succ->isLiveIn(X86::EFLAGS))
12944         return false;
12945     }
12946   }
12947
12948   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12949   // out. SelectMI should have a kill flag on EFLAGS.
12950   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12951   return true;
12952 }
12953
12954 MachineBasicBlock *
12955 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12956                                      MachineBasicBlock *BB) const {
12957   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12958   DebugLoc DL = MI->getDebugLoc();
12959
12960   // To "insert" a SELECT_CC instruction, we actually have to insert the
12961   // diamond control-flow pattern.  The incoming instruction knows the
12962   // destination vreg to set, the condition code register to branch on, the
12963   // true/false values to select between, and a branch opcode to use.
12964   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12965   MachineFunction::iterator It = BB;
12966   ++It;
12967
12968   //  thisMBB:
12969   //  ...
12970   //   TrueVal = ...
12971   //   cmpTY ccX, r1, r2
12972   //   bCC copy1MBB
12973   //   fallthrough --> copy0MBB
12974   MachineBasicBlock *thisMBB = BB;
12975   MachineFunction *F = BB->getParent();
12976   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12977   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12978   F->insert(It, copy0MBB);
12979   F->insert(It, sinkMBB);
12980
12981   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12982   // live into the sink and copy blocks.
12983   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12984   if (!MI->killsRegister(X86::EFLAGS) &&
12985       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12986     copy0MBB->addLiveIn(X86::EFLAGS);
12987     sinkMBB->addLiveIn(X86::EFLAGS);
12988   }
12989
12990   // Transfer the remainder of BB and its successor edges to sinkMBB.
12991   sinkMBB->splice(sinkMBB->begin(), BB,
12992                   llvm::next(MachineBasicBlock::iterator(MI)),
12993                   BB->end());
12994   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12995
12996   // Add the true and fallthrough blocks as its successors.
12997   BB->addSuccessor(copy0MBB);
12998   BB->addSuccessor(sinkMBB);
12999
13000   // Create the conditional branch instruction.
13001   unsigned Opc =
13002     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13003   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13004
13005   //  copy0MBB:
13006   //   %FalseValue = ...
13007   //   # fallthrough to sinkMBB
13008   copy0MBB->addSuccessor(sinkMBB);
13009
13010   //  sinkMBB:
13011   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13012   //  ...
13013   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13014           TII->get(X86::PHI), MI->getOperand(0).getReg())
13015     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13016     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13017
13018   MI->eraseFromParent();   // The pseudo instruction is gone now.
13019   return sinkMBB;
13020 }
13021
13022 MachineBasicBlock *
13023 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13024                                         bool Is64Bit) const {
13025   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13026   DebugLoc DL = MI->getDebugLoc();
13027   MachineFunction *MF = BB->getParent();
13028   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13029
13030   assert(getTargetMachine().Options.EnableSegmentedStacks);
13031
13032   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13033   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13034
13035   // BB:
13036   //  ... [Till the alloca]
13037   // If stacklet is not large enough, jump to mallocMBB
13038   //
13039   // bumpMBB:
13040   //  Allocate by subtracting from RSP
13041   //  Jump to continueMBB
13042   //
13043   // mallocMBB:
13044   //  Allocate by call to runtime
13045   //
13046   // continueMBB:
13047   //  ...
13048   //  [rest of original BB]
13049   //
13050
13051   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13052   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13053   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13054
13055   MachineRegisterInfo &MRI = MF->getRegInfo();
13056   const TargetRegisterClass *AddrRegClass =
13057     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13058
13059   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13060     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13061     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13062     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13063     sizeVReg = MI->getOperand(1).getReg(),
13064     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13065
13066   MachineFunction::iterator MBBIter = BB;
13067   ++MBBIter;
13068
13069   MF->insert(MBBIter, bumpMBB);
13070   MF->insert(MBBIter, mallocMBB);
13071   MF->insert(MBBIter, continueMBB);
13072
13073   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13074                       (MachineBasicBlock::iterator(MI)), BB->end());
13075   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13076
13077   // Add code to the main basic block to check if the stack limit has been hit,
13078   // and if so, jump to mallocMBB otherwise to bumpMBB.
13079   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13080   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13081     .addReg(tmpSPVReg).addReg(sizeVReg);
13082   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13083     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13084     .addReg(SPLimitVReg);
13085   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13086
13087   // bumpMBB simply decreases the stack pointer, since we know the current
13088   // stacklet has enough space.
13089   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13090     .addReg(SPLimitVReg);
13091   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13092     .addReg(SPLimitVReg);
13093   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13094
13095   // Calls into a routine in libgcc to allocate more space from the heap.
13096   const uint32_t *RegMask =
13097     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13098   if (Is64Bit) {
13099     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13100       .addReg(sizeVReg);
13101     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13102       .addExternalSymbol("__morestack_allocate_stack_space")
13103       .addRegMask(RegMask)
13104       .addReg(X86::RDI, RegState::Implicit)
13105       .addReg(X86::RAX, RegState::ImplicitDefine);
13106   } else {
13107     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13108       .addImm(12);
13109     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13110     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13111       .addExternalSymbol("__morestack_allocate_stack_space")
13112       .addRegMask(RegMask)
13113       .addReg(X86::EAX, RegState::ImplicitDefine);
13114   }
13115
13116   if (!Is64Bit)
13117     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13118       .addImm(16);
13119
13120   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13121     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13122   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13123
13124   // Set up the CFG correctly.
13125   BB->addSuccessor(bumpMBB);
13126   BB->addSuccessor(mallocMBB);
13127   mallocMBB->addSuccessor(continueMBB);
13128   bumpMBB->addSuccessor(continueMBB);
13129
13130   // Take care of the PHI nodes.
13131   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13132           MI->getOperand(0).getReg())
13133     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13134     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13135
13136   // Delete the original pseudo instruction.
13137   MI->eraseFromParent();
13138
13139   // And we're done.
13140   return continueMBB;
13141 }
13142
13143 MachineBasicBlock *
13144 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13145                                           MachineBasicBlock *BB) const {
13146   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13147   DebugLoc DL = MI->getDebugLoc();
13148
13149   assert(!Subtarget->isTargetEnvMacho());
13150
13151   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13152   // non-trivial part is impdef of ESP.
13153
13154   if (Subtarget->isTargetWin64()) {
13155     if (Subtarget->isTargetCygMing()) {
13156       // ___chkstk(Mingw64):
13157       // Clobbers R10, R11, RAX and EFLAGS.
13158       // Updates RSP.
13159       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13160         .addExternalSymbol("___chkstk")
13161         .addReg(X86::RAX, RegState::Implicit)
13162         .addReg(X86::RSP, RegState::Implicit)
13163         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13164         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13165         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13166     } else {
13167       // __chkstk(MSVCRT): does not update stack pointer.
13168       // Clobbers R10, R11 and EFLAGS.
13169       // FIXME: RAX(allocated size) might be reused and not killed.
13170       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13171         .addExternalSymbol("__chkstk")
13172         .addReg(X86::RAX, RegState::Implicit)
13173         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13174       // RAX has the offset to subtracted from RSP.
13175       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13176         .addReg(X86::RSP)
13177         .addReg(X86::RAX);
13178     }
13179   } else {
13180     const char *StackProbeSymbol =
13181       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13182
13183     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13184       .addExternalSymbol(StackProbeSymbol)
13185       .addReg(X86::EAX, RegState::Implicit)
13186       .addReg(X86::ESP, RegState::Implicit)
13187       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13188       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13189       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13190   }
13191
13192   MI->eraseFromParent();   // The pseudo instruction is gone now.
13193   return BB;
13194 }
13195
13196 MachineBasicBlock *
13197 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13198                                       MachineBasicBlock *BB) const {
13199   // This is pretty easy.  We're taking the value that we received from
13200   // our load from the relocation, sticking it in either RDI (x86-64)
13201   // or EAX and doing an indirect call.  The return value will then
13202   // be in the normal return register.
13203   const X86InstrInfo *TII
13204     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13205   DebugLoc DL = MI->getDebugLoc();
13206   MachineFunction *F = BB->getParent();
13207
13208   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13209   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13210
13211   // Get a register mask for the lowered call.
13212   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13213   // proper register mask.
13214   const uint32_t *RegMask =
13215     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13216   if (Subtarget->is64Bit()) {
13217     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13218                                       TII->get(X86::MOV64rm), X86::RDI)
13219     .addReg(X86::RIP)
13220     .addImm(0).addReg(0)
13221     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13222                       MI->getOperand(3).getTargetFlags())
13223     .addReg(0);
13224     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13225     addDirectMem(MIB, X86::RDI);
13226     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13227   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13228     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13229                                       TII->get(X86::MOV32rm), X86::EAX)
13230     .addReg(0)
13231     .addImm(0).addReg(0)
13232     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13233                       MI->getOperand(3).getTargetFlags())
13234     .addReg(0);
13235     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13236     addDirectMem(MIB, X86::EAX);
13237     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13238   } else {
13239     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13240                                       TII->get(X86::MOV32rm), X86::EAX)
13241     .addReg(TII->getGlobalBaseReg(F))
13242     .addImm(0).addReg(0)
13243     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13244                       MI->getOperand(3).getTargetFlags())
13245     .addReg(0);
13246     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13247     addDirectMem(MIB, X86::EAX);
13248     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13249   }
13250
13251   MI->eraseFromParent(); // The pseudo instruction is gone now.
13252   return BB;
13253 }
13254
13255 MachineBasicBlock *
13256 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13257                                                MachineBasicBlock *BB) const {
13258   switch (MI->getOpcode()) {
13259   default: llvm_unreachable("Unexpected instr type to insert");
13260   case X86::TAILJMPd64:
13261   case X86::TAILJMPr64:
13262   case X86::TAILJMPm64:
13263     llvm_unreachable("TAILJMP64 would not be touched here.");
13264   case X86::TCRETURNdi64:
13265   case X86::TCRETURNri64:
13266   case X86::TCRETURNmi64:
13267     return BB;
13268   case X86::WIN_ALLOCA:
13269     return EmitLoweredWinAlloca(MI, BB);
13270   case X86::SEG_ALLOCA_32:
13271     return EmitLoweredSegAlloca(MI, BB, false);
13272   case X86::SEG_ALLOCA_64:
13273     return EmitLoweredSegAlloca(MI, BB, true);
13274   case X86::TLSCall_32:
13275   case X86::TLSCall_64:
13276     return EmitLoweredTLSCall(MI, BB);
13277   case X86::CMOV_GR8:
13278   case X86::CMOV_FR32:
13279   case X86::CMOV_FR64:
13280   case X86::CMOV_V4F32:
13281   case X86::CMOV_V2F64:
13282   case X86::CMOV_V2I64:
13283   case X86::CMOV_V8F32:
13284   case X86::CMOV_V4F64:
13285   case X86::CMOV_V4I64:
13286   case X86::CMOV_GR16:
13287   case X86::CMOV_GR32:
13288   case X86::CMOV_RFP32:
13289   case X86::CMOV_RFP64:
13290   case X86::CMOV_RFP80:
13291     return EmitLoweredSelect(MI, BB);
13292
13293   case X86::FP32_TO_INT16_IN_MEM:
13294   case X86::FP32_TO_INT32_IN_MEM:
13295   case X86::FP32_TO_INT64_IN_MEM:
13296   case X86::FP64_TO_INT16_IN_MEM:
13297   case X86::FP64_TO_INT32_IN_MEM:
13298   case X86::FP64_TO_INT64_IN_MEM:
13299   case X86::FP80_TO_INT16_IN_MEM:
13300   case X86::FP80_TO_INT32_IN_MEM:
13301   case X86::FP80_TO_INT64_IN_MEM: {
13302     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13303     DebugLoc DL = MI->getDebugLoc();
13304
13305     // Change the floating point control register to use "round towards zero"
13306     // mode when truncating to an integer value.
13307     MachineFunction *F = BB->getParent();
13308     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13309     addFrameReference(BuildMI(*BB, MI, DL,
13310                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13311
13312     // Load the old value of the high byte of the control word...
13313     unsigned OldCW =
13314       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13315     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13316                       CWFrameIdx);
13317
13318     // Set the high part to be round to zero...
13319     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13320       .addImm(0xC7F);
13321
13322     // Reload the modified control word now...
13323     addFrameReference(BuildMI(*BB, MI, DL,
13324                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13325
13326     // Restore the memory image of control word to original value
13327     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13328       .addReg(OldCW);
13329
13330     // Get the X86 opcode to use.
13331     unsigned Opc;
13332     switch (MI->getOpcode()) {
13333     default: llvm_unreachable("illegal opcode!");
13334     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13335     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13336     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13337     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13338     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13339     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13340     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13341     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13342     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13343     }
13344
13345     X86AddressMode AM;
13346     MachineOperand &Op = MI->getOperand(0);
13347     if (Op.isReg()) {
13348       AM.BaseType = X86AddressMode::RegBase;
13349       AM.Base.Reg = Op.getReg();
13350     } else {
13351       AM.BaseType = X86AddressMode::FrameIndexBase;
13352       AM.Base.FrameIndex = Op.getIndex();
13353     }
13354     Op = MI->getOperand(1);
13355     if (Op.isImm())
13356       AM.Scale = Op.getImm();
13357     Op = MI->getOperand(2);
13358     if (Op.isImm())
13359       AM.IndexReg = Op.getImm();
13360     Op = MI->getOperand(3);
13361     if (Op.isGlobal()) {
13362       AM.GV = Op.getGlobal();
13363     } else {
13364       AM.Disp = Op.getImm();
13365     }
13366     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13367                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13368
13369     // Reload the original control word now.
13370     addFrameReference(BuildMI(*BB, MI, DL,
13371                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13372
13373     MI->eraseFromParent();   // The pseudo instruction is gone now.
13374     return BB;
13375   }
13376     // String/text processing lowering.
13377   case X86::PCMPISTRM128REG:
13378   case X86::VPCMPISTRM128REG:
13379   case X86::PCMPISTRM128MEM:
13380   case X86::VPCMPISTRM128MEM:
13381   case X86::PCMPESTRM128REG:
13382   case X86::VPCMPESTRM128REG:
13383   case X86::PCMPESTRM128MEM:
13384   case X86::VPCMPESTRM128MEM: {
13385     unsigned NumArgs;
13386     bool MemArg;
13387     switch (MI->getOpcode()) {
13388     default: llvm_unreachable("illegal opcode!");
13389     case X86::PCMPISTRM128REG:
13390     case X86::VPCMPISTRM128REG:
13391       NumArgs = 3; MemArg = false; break;
13392     case X86::PCMPISTRM128MEM:
13393     case X86::VPCMPISTRM128MEM:
13394       NumArgs = 3; MemArg = true; break;
13395     case X86::PCMPESTRM128REG:
13396     case X86::VPCMPESTRM128REG:
13397       NumArgs = 5; MemArg = false; break;
13398     case X86::PCMPESTRM128MEM:
13399     case X86::VPCMPESTRM128MEM:
13400       NumArgs = 5; MemArg = true; break;
13401     }
13402     return EmitPCMP(MI, BB, NumArgs, MemArg);
13403   }
13404
13405     // Thread synchronization.
13406   case X86::MONITOR:
13407     return EmitMonitor(MI, BB);
13408
13409     // Atomic Lowering.
13410   case X86::ATOMAND8:
13411   case X86::ATOMAND16:
13412   case X86::ATOMAND32:
13413   case X86::ATOMAND64:
13414     // Fall through
13415   case X86::ATOMOR8:
13416   case X86::ATOMOR16:
13417   case X86::ATOMOR32:
13418   case X86::ATOMOR64:
13419     // Fall through
13420   case X86::ATOMXOR16:
13421   case X86::ATOMXOR8:
13422   case X86::ATOMXOR32:
13423   case X86::ATOMXOR64:
13424     // Fall through
13425   case X86::ATOMNAND8:
13426   case X86::ATOMNAND16:
13427   case X86::ATOMNAND32:
13428   case X86::ATOMNAND64:
13429     // Fall through
13430   case X86::ATOMMAX8:
13431   case X86::ATOMMAX16:
13432   case X86::ATOMMAX32:
13433   case X86::ATOMMAX64:
13434     // Fall through
13435   case X86::ATOMMIN8:
13436   case X86::ATOMMIN16:
13437   case X86::ATOMMIN32:
13438   case X86::ATOMMIN64:
13439     // Fall through
13440   case X86::ATOMUMAX8:
13441   case X86::ATOMUMAX16:
13442   case X86::ATOMUMAX32:
13443   case X86::ATOMUMAX64:
13444     // Fall through
13445   case X86::ATOMUMIN8:
13446   case X86::ATOMUMIN16:
13447   case X86::ATOMUMIN32:
13448   case X86::ATOMUMIN64:
13449     return EmitAtomicLoadArith(MI, BB);
13450
13451   // This group does 64-bit operations on a 32-bit host.
13452   case X86::ATOMAND6432:
13453   case X86::ATOMOR6432:
13454   case X86::ATOMXOR6432:
13455   case X86::ATOMNAND6432:
13456   case X86::ATOMADD6432:
13457   case X86::ATOMSUB6432:
13458   case X86::ATOMMAX6432:
13459   case X86::ATOMMIN6432:
13460   case X86::ATOMUMAX6432:
13461   case X86::ATOMUMIN6432:
13462   case X86::ATOMSWAP6432:
13463     return EmitAtomicLoadArith6432(MI, BB);
13464
13465   case X86::VASTART_SAVE_XMM_REGS:
13466     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13467
13468   case X86::VAARG_64:
13469     return EmitVAARG64WithCustomInserter(MI, BB);
13470   }
13471 }
13472
13473 //===----------------------------------------------------------------------===//
13474 //                           X86 Optimization Hooks
13475 //===----------------------------------------------------------------------===//
13476
13477 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13478                                                        APInt &KnownZero,
13479                                                        APInt &KnownOne,
13480                                                        const SelectionDAG &DAG,
13481                                                        unsigned Depth) const {
13482   unsigned BitWidth = KnownZero.getBitWidth();
13483   unsigned Opc = Op.getOpcode();
13484   assert((Opc >= ISD::BUILTIN_OP_END ||
13485           Opc == ISD::INTRINSIC_WO_CHAIN ||
13486           Opc == ISD::INTRINSIC_W_CHAIN ||
13487           Opc == ISD::INTRINSIC_VOID) &&
13488          "Should use MaskedValueIsZero if you don't know whether Op"
13489          " is a target node!");
13490
13491   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13492   switch (Opc) {
13493   default: break;
13494   case X86ISD::ADD:
13495   case X86ISD::SUB:
13496   case X86ISD::ADC:
13497   case X86ISD::SBB:
13498   case X86ISD::SMUL:
13499   case X86ISD::UMUL:
13500   case X86ISD::INC:
13501   case X86ISD::DEC:
13502   case X86ISD::OR:
13503   case X86ISD::XOR:
13504   case X86ISD::AND:
13505     // These nodes' second result is a boolean.
13506     if (Op.getResNo() == 0)
13507       break;
13508     // Fallthrough
13509   case X86ISD::SETCC:
13510     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13511     break;
13512   case ISD::INTRINSIC_WO_CHAIN: {
13513     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13514     unsigned NumLoBits = 0;
13515     switch (IntId) {
13516     default: break;
13517     case Intrinsic::x86_sse_movmsk_ps:
13518     case Intrinsic::x86_avx_movmsk_ps_256:
13519     case Intrinsic::x86_sse2_movmsk_pd:
13520     case Intrinsic::x86_avx_movmsk_pd_256:
13521     case Intrinsic::x86_mmx_pmovmskb:
13522     case Intrinsic::x86_sse2_pmovmskb_128:
13523     case Intrinsic::x86_avx2_pmovmskb: {
13524       // High bits of movmskp{s|d}, pmovmskb are known zero.
13525       switch (IntId) {
13526         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13527         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13528         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13529         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13530         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13531         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13532         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13533         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13534       }
13535       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13536       break;
13537     }
13538     }
13539     break;
13540   }
13541   }
13542 }
13543
13544 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13545                                                          unsigned Depth) const {
13546   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13547   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13548     return Op.getValueType().getScalarType().getSizeInBits();
13549
13550   // Fallback case.
13551   return 1;
13552 }
13553
13554 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13555 /// node is a GlobalAddress + offset.
13556 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13557                                        const GlobalValue* &GA,
13558                                        int64_t &Offset) const {
13559   if (N->getOpcode() == X86ISD::Wrapper) {
13560     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13561       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13562       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13563       return true;
13564     }
13565   }
13566   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13567 }
13568
13569 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13570 /// same as extracting the high 128-bit part of 256-bit vector and then
13571 /// inserting the result into the low part of a new 256-bit vector
13572 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13573   EVT VT = SVOp->getValueType(0);
13574   unsigned NumElems = VT.getVectorNumElements();
13575
13576   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13577   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13578     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13579         SVOp->getMaskElt(j) >= 0)
13580       return false;
13581
13582   return true;
13583 }
13584
13585 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13586 /// same as extracting the low 128-bit part of 256-bit vector and then
13587 /// inserting the result into the high part of a new 256-bit vector
13588 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13589   EVT VT = SVOp->getValueType(0);
13590   unsigned NumElems = VT.getVectorNumElements();
13591
13592   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13593   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13594     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13595         SVOp->getMaskElt(j) >= 0)
13596       return false;
13597
13598   return true;
13599 }
13600
13601 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13602 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13603                                         TargetLowering::DAGCombinerInfo &DCI,
13604                                         const X86Subtarget* Subtarget) {
13605   DebugLoc dl = N->getDebugLoc();
13606   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13607   SDValue V1 = SVOp->getOperand(0);
13608   SDValue V2 = SVOp->getOperand(1);
13609   EVT VT = SVOp->getValueType(0);
13610   unsigned NumElems = VT.getVectorNumElements();
13611
13612   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13613       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13614     //
13615     //                   0,0,0,...
13616     //                      |
13617     //    V      UNDEF    BUILD_VECTOR    UNDEF
13618     //     \      /           \           /
13619     //  CONCAT_VECTOR         CONCAT_VECTOR
13620     //         \                  /
13621     //          \                /
13622     //          RESULT: V + zero extended
13623     //
13624     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13625         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13626         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13627       return SDValue();
13628
13629     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13630       return SDValue();
13631
13632     // To match the shuffle mask, the first half of the mask should
13633     // be exactly the first vector, and all the rest a splat with the
13634     // first element of the second one.
13635     for (unsigned i = 0; i != NumElems/2; ++i)
13636       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13637           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13638         return SDValue();
13639
13640     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13641     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13642       if (Ld->hasNUsesOfValue(1, 0)) {
13643         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13644         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13645         SDValue ResNode =
13646           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13647                                   Ld->getMemoryVT(),
13648                                   Ld->getPointerInfo(),
13649                                   Ld->getAlignment(),
13650                                   false/*isVolatile*/, true/*ReadMem*/,
13651                                   false/*WriteMem*/);
13652         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13653       }
13654     }
13655
13656     // Emit a zeroed vector and insert the desired subvector on its
13657     // first half.
13658     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13659     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13660     return DCI.CombineTo(N, InsV);
13661   }
13662
13663   //===--------------------------------------------------------------------===//
13664   // Combine some shuffles into subvector extracts and inserts:
13665   //
13666
13667   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13668   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13669     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13670     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13671     return DCI.CombineTo(N, InsV);
13672   }
13673
13674   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13675   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13676     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13677     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13678     return DCI.CombineTo(N, InsV);
13679   }
13680
13681   return SDValue();
13682 }
13683
13684 /// PerformShuffleCombine - Performs several different shuffle combines.
13685 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13686                                      TargetLowering::DAGCombinerInfo &DCI,
13687                                      const X86Subtarget *Subtarget) {
13688   DebugLoc dl = N->getDebugLoc();
13689   EVT VT = N->getValueType(0);
13690
13691   // Don't create instructions with illegal types after legalize types has run.
13692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13693   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13694     return SDValue();
13695
13696   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13697   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13698       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13699     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13700
13701   // Only handle 128 wide vector from here on.
13702   if (!VT.is128BitVector())
13703     return SDValue();
13704
13705   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13706   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13707   // consecutive, non-overlapping, and in the right order.
13708   SmallVector<SDValue, 16> Elts;
13709   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13710     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13711
13712   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13713 }
13714
13715
13716 /// PerformTruncateCombine - Converts truncate operation to
13717 /// a sequence of vector shuffle operations.
13718 /// It is possible when we truncate 256-bit vector to 128-bit vector
13719 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13720                                       TargetLowering::DAGCombinerInfo &DCI,
13721                                       const X86Subtarget *Subtarget)  {
13722   if (!DCI.isBeforeLegalizeOps())
13723     return SDValue();
13724
13725   if (!Subtarget->hasAVX())
13726     return SDValue();
13727
13728   EVT VT = N->getValueType(0);
13729   SDValue Op = N->getOperand(0);
13730   EVT OpVT = Op.getValueType();
13731   DebugLoc dl = N->getDebugLoc();
13732
13733   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13734
13735     if (Subtarget->hasAVX2()) {
13736       // AVX2: v4i64 -> v4i32
13737
13738       // VPERMD
13739       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13740
13741       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13742       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13743                                 ShufMask);
13744
13745       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13746                          DAG.getIntPtrConstant(0));
13747     }
13748
13749     // AVX: v4i64 -> v4i32
13750     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13751                                DAG.getIntPtrConstant(0));
13752
13753     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13754                                DAG.getIntPtrConstant(2));
13755
13756     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13757     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13758
13759     // PSHUFD
13760     static const int ShufMask1[] = {0, 2, 0, 0};
13761
13762     SDValue Undef = DAG.getUNDEF(VT);
13763     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13764     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13765
13766     // MOVLHPS
13767     static const int ShufMask2[] = {0, 1, 4, 5};
13768
13769     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13770   }
13771
13772   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13773
13774     if (Subtarget->hasAVX2()) {
13775       // AVX2: v8i32 -> v8i16
13776
13777       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13778
13779       // PSHUFB
13780       SmallVector<SDValue,32> pshufbMask;
13781       for (unsigned i = 0; i < 2; ++i) {
13782         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13783         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13784         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13785         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13786         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13787         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13788         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13789         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13790         for (unsigned j = 0; j < 8; ++j)
13791           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13792       }
13793       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13794                                &pshufbMask[0], 32);
13795       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13796
13797       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13798
13799       static const int ShufMask[] = {0,  2,  -1,  -1};
13800       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13801                                 &ShufMask[0]);
13802
13803       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13804                        DAG.getIntPtrConstant(0));
13805
13806       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13807     }
13808
13809     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13810                                DAG.getIntPtrConstant(0));
13811
13812     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13813                                DAG.getIntPtrConstant(4));
13814
13815     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13816     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13817
13818     // PSHUFB
13819     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13820                                    -1, -1, -1, -1, -1, -1, -1, -1};
13821
13822     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13823     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13824     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13825
13826     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13827     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13828
13829     // MOVLHPS
13830     static const int ShufMask2[] = {0, 1, 4, 5};
13831
13832     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13833     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13834   }
13835
13836   return SDValue();
13837 }
13838
13839 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13840 /// specific shuffle of a load can be folded into a single element load.
13841 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13842 /// shuffles have been customed lowered so we need to handle those here.
13843 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13844                                          TargetLowering::DAGCombinerInfo &DCI) {
13845   if (DCI.isBeforeLegalizeOps())
13846     return SDValue();
13847
13848   SDValue InVec = N->getOperand(0);
13849   SDValue EltNo = N->getOperand(1);
13850
13851   if (!isa<ConstantSDNode>(EltNo))
13852     return SDValue();
13853
13854   EVT VT = InVec.getValueType();
13855
13856   bool HasShuffleIntoBitcast = false;
13857   if (InVec.getOpcode() == ISD::BITCAST) {
13858     // Don't duplicate a load with other uses.
13859     if (!InVec.hasOneUse())
13860       return SDValue();
13861     EVT BCVT = InVec.getOperand(0).getValueType();
13862     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13863       return SDValue();
13864     InVec = InVec.getOperand(0);
13865     HasShuffleIntoBitcast = true;
13866   }
13867
13868   if (!isTargetShuffle(InVec.getOpcode()))
13869     return SDValue();
13870
13871   // Don't duplicate a load with other uses.
13872   if (!InVec.hasOneUse())
13873     return SDValue();
13874
13875   SmallVector<int, 16> ShuffleMask;
13876   bool UnaryShuffle;
13877   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13878                             UnaryShuffle))
13879     return SDValue();
13880
13881   // Select the input vector, guarding against out of range extract vector.
13882   unsigned NumElems = VT.getVectorNumElements();
13883   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13884   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13885   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13886                                          : InVec.getOperand(1);
13887
13888   // If inputs to shuffle are the same for both ops, then allow 2 uses
13889   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13890
13891   if (LdNode.getOpcode() == ISD::BITCAST) {
13892     // Don't duplicate a load with other uses.
13893     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13894       return SDValue();
13895
13896     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13897     LdNode = LdNode.getOperand(0);
13898   }
13899
13900   if (!ISD::isNormalLoad(LdNode.getNode()))
13901     return SDValue();
13902
13903   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13904
13905   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13906     return SDValue();
13907
13908   if (HasShuffleIntoBitcast) {
13909     // If there's a bitcast before the shuffle, check if the load type and
13910     // alignment is valid.
13911     unsigned Align = LN0->getAlignment();
13912     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13913     unsigned NewAlign = TLI.getTargetData()->
13914       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13915
13916     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13917       return SDValue();
13918   }
13919
13920   // All checks match so transform back to vector_shuffle so that DAG combiner
13921   // can finish the job
13922   DebugLoc dl = N->getDebugLoc();
13923
13924   // Create shuffle node taking into account the case that its a unary shuffle
13925   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13926   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13927                                  InVec.getOperand(0), Shuffle,
13928                                  &ShuffleMask[0]);
13929   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13930   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13931                      EltNo);
13932 }
13933
13934 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13935 /// generation and convert it from being a bunch of shuffles and extracts
13936 /// to a simple store and scalar loads to extract the elements.
13937 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13938                                          TargetLowering::DAGCombinerInfo &DCI) {
13939   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13940   if (NewOp.getNode())
13941     return NewOp;
13942
13943   SDValue InputVector = N->getOperand(0);
13944
13945   // Only operate on vectors of 4 elements, where the alternative shuffling
13946   // gets to be more expensive.
13947   if (InputVector.getValueType() != MVT::v4i32)
13948     return SDValue();
13949
13950   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13951   // single use which is a sign-extend or zero-extend, and all elements are
13952   // used.
13953   SmallVector<SDNode *, 4> Uses;
13954   unsigned ExtractedElements = 0;
13955   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13956        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13957     if (UI.getUse().getResNo() != InputVector.getResNo())
13958       return SDValue();
13959
13960     SDNode *Extract = *UI;
13961     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13962       return SDValue();
13963
13964     if (Extract->getValueType(0) != MVT::i32)
13965       return SDValue();
13966     if (!Extract->hasOneUse())
13967       return SDValue();
13968     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13969         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13970       return SDValue();
13971     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13972       return SDValue();
13973
13974     // Record which element was extracted.
13975     ExtractedElements |=
13976       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13977
13978     Uses.push_back(Extract);
13979   }
13980
13981   // If not all the elements were used, this may not be worthwhile.
13982   if (ExtractedElements != 15)
13983     return SDValue();
13984
13985   // Ok, we've now decided to do the transformation.
13986   DebugLoc dl = InputVector.getDebugLoc();
13987
13988   // Store the value to a temporary stack slot.
13989   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13990   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13991                             MachinePointerInfo(), false, false, 0);
13992
13993   // Replace each use (extract) with a load of the appropriate element.
13994   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13995        UE = Uses.end(); UI != UE; ++UI) {
13996     SDNode *Extract = *UI;
13997
13998     // cOMpute the element's address.
13999     SDValue Idx = Extract->getOperand(1);
14000     unsigned EltSize =
14001         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14002     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14003     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14004     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14005
14006     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14007                                      StackPtr, OffsetVal);
14008
14009     // Load the scalar.
14010     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14011                                      ScalarAddr, MachinePointerInfo(),
14012                                      false, false, false, 0);
14013
14014     // Replace the exact with the load.
14015     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14016   }
14017
14018   // The replacement was made in place; don't return anything.
14019   return SDValue();
14020 }
14021
14022 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14023 /// nodes.
14024 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14025                                     TargetLowering::DAGCombinerInfo &DCI,
14026                                     const X86Subtarget *Subtarget) {
14027   DebugLoc DL = N->getDebugLoc();
14028   SDValue Cond = N->getOperand(0);
14029   // Get the LHS/RHS of the select.
14030   SDValue LHS = N->getOperand(1);
14031   SDValue RHS = N->getOperand(2);
14032   EVT VT = LHS.getValueType();
14033
14034   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14035   // instructions match the semantics of the common C idiom x<y?x:y but not
14036   // x<=y?x:y, because of how they handle negative zero (which can be
14037   // ignored in unsafe-math mode).
14038   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14039       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14040       (Subtarget->hasSSE2() ||
14041        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14042     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14043
14044     unsigned Opcode = 0;
14045     // Check for x CC y ? x : y.
14046     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14047         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14048       switch (CC) {
14049       default: break;
14050       case ISD::SETULT:
14051         // Converting this to a min would handle NaNs incorrectly, and swapping
14052         // the operands would cause it to handle comparisons between positive
14053         // and negative zero incorrectly.
14054         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14055           if (!DAG.getTarget().Options.UnsafeFPMath &&
14056               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14057             break;
14058           std::swap(LHS, RHS);
14059         }
14060         Opcode = X86ISD::FMIN;
14061         break;
14062       case ISD::SETOLE:
14063         // Converting this to a min would handle comparisons between positive
14064         // and negative zero incorrectly.
14065         if (!DAG.getTarget().Options.UnsafeFPMath &&
14066             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14067           break;
14068         Opcode = X86ISD::FMIN;
14069         break;
14070       case ISD::SETULE:
14071         // Converting this to a min would handle both negative zeros and NaNs
14072         // incorrectly, but we can swap the operands to fix both.
14073         std::swap(LHS, RHS);
14074       case ISD::SETOLT:
14075       case ISD::SETLT:
14076       case ISD::SETLE:
14077         Opcode = X86ISD::FMIN;
14078         break;
14079
14080       case ISD::SETOGE:
14081         // Converting this to a max would handle comparisons between positive
14082         // and negative zero incorrectly.
14083         if (!DAG.getTarget().Options.UnsafeFPMath &&
14084             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14085           break;
14086         Opcode = X86ISD::FMAX;
14087         break;
14088       case ISD::SETUGT:
14089         // Converting this to a max would handle NaNs incorrectly, and swapping
14090         // the operands would cause it to handle comparisons between positive
14091         // and negative zero incorrectly.
14092         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14093           if (!DAG.getTarget().Options.UnsafeFPMath &&
14094               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14095             break;
14096           std::swap(LHS, RHS);
14097         }
14098         Opcode = X86ISD::FMAX;
14099         break;
14100       case ISD::SETUGE:
14101         // Converting this to a max would handle both negative zeros and NaNs
14102         // incorrectly, but we can swap the operands to fix both.
14103         std::swap(LHS, RHS);
14104       case ISD::SETOGT:
14105       case ISD::SETGT:
14106       case ISD::SETGE:
14107         Opcode = X86ISD::FMAX;
14108         break;
14109       }
14110     // Check for x CC y ? y : x -- a min/max with reversed arms.
14111     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14112                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14113       switch (CC) {
14114       default: break;
14115       case ISD::SETOGE:
14116         // Converting this to a min would handle comparisons between positive
14117         // and negative zero incorrectly, and swapping the operands would
14118         // cause it to handle NaNs incorrectly.
14119         if (!DAG.getTarget().Options.UnsafeFPMath &&
14120             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14121           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14122             break;
14123           std::swap(LHS, RHS);
14124         }
14125         Opcode = X86ISD::FMIN;
14126         break;
14127       case ISD::SETUGT:
14128         // Converting this to a min would handle NaNs incorrectly.
14129         if (!DAG.getTarget().Options.UnsafeFPMath &&
14130             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14131           break;
14132         Opcode = X86ISD::FMIN;
14133         break;
14134       case ISD::SETUGE:
14135         // Converting this to a min would handle both negative zeros and NaNs
14136         // incorrectly, but we can swap the operands to fix both.
14137         std::swap(LHS, RHS);
14138       case ISD::SETOGT:
14139       case ISD::SETGT:
14140       case ISD::SETGE:
14141         Opcode = X86ISD::FMIN;
14142         break;
14143
14144       case ISD::SETULT:
14145         // Converting this to a max would handle NaNs incorrectly.
14146         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14147           break;
14148         Opcode = X86ISD::FMAX;
14149         break;
14150       case ISD::SETOLE:
14151         // Converting this to a max would handle comparisons between positive
14152         // and negative zero incorrectly, and swapping the operands would
14153         // cause it to handle NaNs incorrectly.
14154         if (!DAG.getTarget().Options.UnsafeFPMath &&
14155             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14156           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14157             break;
14158           std::swap(LHS, RHS);
14159         }
14160         Opcode = X86ISD::FMAX;
14161         break;
14162       case ISD::SETULE:
14163         // Converting this to a max would handle both negative zeros and NaNs
14164         // incorrectly, but we can swap the operands to fix both.
14165         std::swap(LHS, RHS);
14166       case ISD::SETOLT:
14167       case ISD::SETLT:
14168       case ISD::SETLE:
14169         Opcode = X86ISD::FMAX;
14170         break;
14171       }
14172     }
14173
14174     if (Opcode)
14175       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14176   }
14177
14178   // If this is a select between two integer constants, try to do some
14179   // optimizations.
14180   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14181     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14182       // Don't do this for crazy integer types.
14183       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14184         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14185         // so that TrueC (the true value) is larger than FalseC.
14186         bool NeedsCondInvert = false;
14187
14188         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14189             // Efficiently invertible.
14190             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14191              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14192               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14193           NeedsCondInvert = true;
14194           std::swap(TrueC, FalseC);
14195         }
14196
14197         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14198         if (FalseC->getAPIntValue() == 0 &&
14199             TrueC->getAPIntValue().isPowerOf2()) {
14200           if (NeedsCondInvert) // Invert the condition if needed.
14201             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14202                                DAG.getConstant(1, Cond.getValueType()));
14203
14204           // Zero extend the condition if needed.
14205           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14206
14207           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14208           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14209                              DAG.getConstant(ShAmt, MVT::i8));
14210         }
14211
14212         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14213         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14214           if (NeedsCondInvert) // Invert the condition if needed.
14215             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14216                                DAG.getConstant(1, Cond.getValueType()));
14217
14218           // Zero extend the condition if needed.
14219           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14220                              FalseC->getValueType(0), Cond);
14221           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14222                              SDValue(FalseC, 0));
14223         }
14224
14225         // Optimize cases that will turn into an LEA instruction.  This requires
14226         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14227         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14228           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14229           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14230
14231           bool isFastMultiplier = false;
14232           if (Diff < 10) {
14233             switch ((unsigned char)Diff) {
14234               default: break;
14235               case 1:  // result = add base, cond
14236               case 2:  // result = lea base(    , cond*2)
14237               case 3:  // result = lea base(cond, cond*2)
14238               case 4:  // result = lea base(    , cond*4)
14239               case 5:  // result = lea base(cond, cond*4)
14240               case 8:  // result = lea base(    , cond*8)
14241               case 9:  // result = lea base(cond, cond*8)
14242                 isFastMultiplier = true;
14243                 break;
14244             }
14245           }
14246
14247           if (isFastMultiplier) {
14248             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14249             if (NeedsCondInvert) // Invert the condition if needed.
14250               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14251                                  DAG.getConstant(1, Cond.getValueType()));
14252
14253             // Zero extend the condition if needed.
14254             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14255                                Cond);
14256             // Scale the condition by the difference.
14257             if (Diff != 1)
14258               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14259                                  DAG.getConstant(Diff, Cond.getValueType()));
14260
14261             // Add the base if non-zero.
14262             if (FalseC->getAPIntValue() != 0)
14263               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14264                                  SDValue(FalseC, 0));
14265             return Cond;
14266           }
14267         }
14268       }
14269   }
14270
14271   // Canonicalize max and min:
14272   // (x > y) ? x : y -> (x >= y) ? x : y
14273   // (x < y) ? x : y -> (x <= y) ? x : y
14274   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14275   // the need for an extra compare
14276   // against zero. e.g.
14277   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14278   // subl   %esi, %edi
14279   // testl  %edi, %edi
14280   // movl   $0, %eax
14281   // cmovgl %edi, %eax
14282   // =>
14283   // xorl   %eax, %eax
14284   // subl   %esi, $edi
14285   // cmovsl %eax, %edi
14286   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14287       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14288       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14289     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14290     switch (CC) {
14291     default: break;
14292     case ISD::SETLT:
14293     case ISD::SETGT: {
14294       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14295       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14296                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14297       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14298     }
14299     }
14300   }
14301
14302   // If we know that this node is legal then we know that it is going to be
14303   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14304   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14305   // to simplify previous instructions.
14306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14307   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14308       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14309     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14310
14311     // Don't optimize vector selects that map to mask-registers.
14312     if (BitWidth == 1)
14313       return SDValue();
14314
14315     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14316     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14317
14318     APInt KnownZero, KnownOne;
14319     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14320                                           DCI.isBeforeLegalizeOps());
14321     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14322         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14323       DCI.CommitTargetLoweringOpt(TLO);
14324   }
14325
14326   return SDValue();
14327 }
14328
14329 // Check whether a boolean test is testing a boolean value generated by
14330 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14331 // code.
14332 //
14333 // Simplify the following patterns:
14334 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14335 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14336 // to (Op EFLAGS Cond)
14337 //
14338 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14339 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14340 // to (Op EFLAGS !Cond)
14341 //
14342 // where Op could be BRCOND or CMOV.
14343 //
14344 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14345   // Quit if not CMP and SUB with its value result used.
14346   if (Cmp.getOpcode() != X86ISD::CMP &&
14347       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14348       return SDValue();
14349
14350   // Quit if not used as a boolean value.
14351   if (CC != X86::COND_E && CC != X86::COND_NE)
14352     return SDValue();
14353
14354   // Check CMP operands. One of them should be 0 or 1 and the other should be
14355   // an SetCC or extended from it.
14356   SDValue Op1 = Cmp.getOperand(0);
14357   SDValue Op2 = Cmp.getOperand(1);
14358
14359   SDValue SetCC;
14360   const ConstantSDNode* C = 0;
14361   bool needOppositeCond = (CC == X86::COND_E);
14362
14363   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14364     SetCC = Op2;
14365   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14366     SetCC = Op1;
14367   else // Quit if all operands are not constants.
14368     return SDValue();
14369
14370   if (C->getZExtValue() == 1)
14371     needOppositeCond = !needOppositeCond;
14372   else if (C->getZExtValue() != 0)
14373     // Quit if the constant is neither 0 or 1.
14374     return SDValue();
14375
14376   // Skip 'zext' node.
14377   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14378     SetCC = SetCC.getOperand(0);
14379
14380   switch (SetCC.getOpcode()) {
14381   case X86ISD::SETCC:
14382     // Set the condition code or opposite one if necessary.
14383     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14384     if (needOppositeCond)
14385       CC = X86::GetOppositeBranchCondition(CC);
14386     return SetCC.getOperand(1);
14387   case X86ISD::CMOV: {
14388     // Check whether false/true value has canonical one, i.e. 0 or 1.
14389     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14390     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14391     // Quit if true value is not a constant.
14392     if (!TVal)
14393       return SDValue();
14394     // Quit if false value is not a constant.
14395     if (!FVal) {
14396       // A special case for rdrand, where 0 is set if false cond is found.
14397       SDValue Op = SetCC.getOperand(0);
14398       if (Op.getOpcode() != X86ISD::RDRAND)
14399         return SDValue();
14400     }
14401     // Quit if false value is not the constant 0 or 1.
14402     bool FValIsFalse = true;
14403     if (FVal && FVal->getZExtValue() != 0) {
14404       if (FVal->getZExtValue() != 1)
14405         return SDValue();
14406       // If FVal is 1, opposite cond is needed.
14407       needOppositeCond = !needOppositeCond;
14408       FValIsFalse = false;
14409     }
14410     // Quit if TVal is not the constant opposite of FVal.
14411     if (FValIsFalse && TVal->getZExtValue() != 1)
14412       return SDValue();
14413     if (!FValIsFalse && TVal->getZExtValue() != 0)
14414       return SDValue();
14415     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14416     if (needOppositeCond)
14417       CC = X86::GetOppositeBranchCondition(CC);
14418     return SetCC.getOperand(3);
14419   }
14420   }
14421
14422   return SDValue();
14423 }
14424
14425 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14426 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14427                                   TargetLowering::DAGCombinerInfo &DCI,
14428                                   const X86Subtarget *Subtarget) {
14429   DebugLoc DL = N->getDebugLoc();
14430
14431   // If the flag operand isn't dead, don't touch this CMOV.
14432   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14433     return SDValue();
14434
14435   SDValue FalseOp = N->getOperand(0);
14436   SDValue TrueOp = N->getOperand(1);
14437   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14438   SDValue Cond = N->getOperand(3);
14439
14440   if (CC == X86::COND_E || CC == X86::COND_NE) {
14441     switch (Cond.getOpcode()) {
14442     default: break;
14443     case X86ISD::BSR:
14444     case X86ISD::BSF:
14445       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14446       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14447         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14448     }
14449   }
14450
14451   SDValue Flags;
14452
14453   Flags = checkBoolTestSetCCCombine(Cond, CC);
14454   if (Flags.getNode() &&
14455       // Extra check as FCMOV only supports a subset of X86 cond.
14456       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14457     SDValue Ops[] = { FalseOp, TrueOp,
14458                       DAG.getConstant(CC, MVT::i8), Flags };
14459     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14460                        Ops, array_lengthof(Ops));
14461   }
14462
14463   // If this is a select between two integer constants, try to do some
14464   // optimizations.  Note that the operands are ordered the opposite of SELECT
14465   // operands.
14466   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14467     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14468       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14469       // larger than FalseC (the false value).
14470       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14471         CC = X86::GetOppositeBranchCondition(CC);
14472         std::swap(TrueC, FalseC);
14473       }
14474
14475       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14476       // This is efficient for any integer data type (including i8/i16) and
14477       // shift amount.
14478       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14479         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14480                            DAG.getConstant(CC, MVT::i8), Cond);
14481
14482         // Zero extend the condition if needed.
14483         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14484
14485         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14486         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14487                            DAG.getConstant(ShAmt, MVT::i8));
14488         if (N->getNumValues() == 2)  // Dead flag value?
14489           return DCI.CombineTo(N, Cond, SDValue());
14490         return Cond;
14491       }
14492
14493       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14494       // for any integer data type, including i8/i16.
14495       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14496         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14497                            DAG.getConstant(CC, MVT::i8), Cond);
14498
14499         // Zero extend the condition if needed.
14500         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14501                            FalseC->getValueType(0), Cond);
14502         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14503                            SDValue(FalseC, 0));
14504
14505         if (N->getNumValues() == 2)  // Dead flag value?
14506           return DCI.CombineTo(N, Cond, SDValue());
14507         return Cond;
14508       }
14509
14510       // Optimize cases that will turn into an LEA instruction.  This requires
14511       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14512       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14513         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14514         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14515
14516         bool isFastMultiplier = false;
14517         if (Diff < 10) {
14518           switch ((unsigned char)Diff) {
14519           default: break;
14520           case 1:  // result = add base, cond
14521           case 2:  // result = lea base(    , cond*2)
14522           case 3:  // result = lea base(cond, cond*2)
14523           case 4:  // result = lea base(    , cond*4)
14524           case 5:  // result = lea base(cond, cond*4)
14525           case 8:  // result = lea base(    , cond*8)
14526           case 9:  // result = lea base(cond, cond*8)
14527             isFastMultiplier = true;
14528             break;
14529           }
14530         }
14531
14532         if (isFastMultiplier) {
14533           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14534           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14535                              DAG.getConstant(CC, MVT::i8), Cond);
14536           // Zero extend the condition if needed.
14537           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14538                              Cond);
14539           // Scale the condition by the difference.
14540           if (Diff != 1)
14541             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14542                                DAG.getConstant(Diff, Cond.getValueType()));
14543
14544           // Add the base if non-zero.
14545           if (FalseC->getAPIntValue() != 0)
14546             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14547                                SDValue(FalseC, 0));
14548           if (N->getNumValues() == 2)  // Dead flag value?
14549             return DCI.CombineTo(N, Cond, SDValue());
14550           return Cond;
14551         }
14552       }
14553     }
14554   }
14555   return SDValue();
14556 }
14557
14558
14559 /// PerformMulCombine - Optimize a single multiply with constant into two
14560 /// in order to implement it with two cheaper instructions, e.g.
14561 /// LEA + SHL, LEA + LEA.
14562 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14563                                  TargetLowering::DAGCombinerInfo &DCI) {
14564   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14565     return SDValue();
14566
14567   EVT VT = N->getValueType(0);
14568   if (VT != MVT::i64)
14569     return SDValue();
14570
14571   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14572   if (!C)
14573     return SDValue();
14574   uint64_t MulAmt = C->getZExtValue();
14575   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14576     return SDValue();
14577
14578   uint64_t MulAmt1 = 0;
14579   uint64_t MulAmt2 = 0;
14580   if ((MulAmt % 9) == 0) {
14581     MulAmt1 = 9;
14582     MulAmt2 = MulAmt / 9;
14583   } else if ((MulAmt % 5) == 0) {
14584     MulAmt1 = 5;
14585     MulAmt2 = MulAmt / 5;
14586   } else if ((MulAmt % 3) == 0) {
14587     MulAmt1 = 3;
14588     MulAmt2 = MulAmt / 3;
14589   }
14590   if (MulAmt2 &&
14591       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14592     DebugLoc DL = N->getDebugLoc();
14593
14594     if (isPowerOf2_64(MulAmt2) &&
14595         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14596       // If second multiplifer is pow2, issue it first. We want the multiply by
14597       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14598       // is an add.
14599       std::swap(MulAmt1, MulAmt2);
14600
14601     SDValue NewMul;
14602     if (isPowerOf2_64(MulAmt1))
14603       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14604                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14605     else
14606       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14607                            DAG.getConstant(MulAmt1, VT));
14608
14609     if (isPowerOf2_64(MulAmt2))
14610       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14611                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14612     else
14613       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14614                            DAG.getConstant(MulAmt2, VT));
14615
14616     // Do not add new nodes to DAG combiner worklist.
14617     DCI.CombineTo(N, NewMul, false);
14618   }
14619   return SDValue();
14620 }
14621
14622 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14623   SDValue N0 = N->getOperand(0);
14624   SDValue N1 = N->getOperand(1);
14625   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14626   EVT VT = N0.getValueType();
14627
14628   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14629   // since the result of setcc_c is all zero's or all ones.
14630   if (VT.isInteger() && !VT.isVector() &&
14631       N1C && N0.getOpcode() == ISD::AND &&
14632       N0.getOperand(1).getOpcode() == ISD::Constant) {
14633     SDValue N00 = N0.getOperand(0);
14634     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14635         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14636           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14637          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14638       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14639       APInt ShAmt = N1C->getAPIntValue();
14640       Mask = Mask.shl(ShAmt);
14641       if (Mask != 0)
14642         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14643                            N00, DAG.getConstant(Mask, VT));
14644     }
14645   }
14646
14647
14648   // Hardware support for vector shifts is sparse which makes us scalarize the
14649   // vector operations in many cases. Also, on sandybridge ADD is faster than
14650   // shl.
14651   // (shl V, 1) -> add V,V
14652   if (isSplatVector(N1.getNode())) {
14653     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14654     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14655     // We shift all of the values by one. In many cases we do not have
14656     // hardware support for this operation. This is better expressed as an ADD
14657     // of two values.
14658     if (N1C && (1 == N1C->getZExtValue())) {
14659       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14660     }
14661   }
14662
14663   return SDValue();
14664 }
14665
14666 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14667 ///                       when possible.
14668 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14669                                    TargetLowering::DAGCombinerInfo &DCI,
14670                                    const X86Subtarget *Subtarget) {
14671   EVT VT = N->getValueType(0);
14672   if (N->getOpcode() == ISD::SHL) {
14673     SDValue V = PerformSHLCombine(N, DAG);
14674     if (V.getNode()) return V;
14675   }
14676
14677   // On X86 with SSE2 support, we can transform this to a vector shift if
14678   // all elements are shifted by the same amount.  We can't do this in legalize
14679   // because the a constant vector is typically transformed to a constant pool
14680   // so we have no knowledge of the shift amount.
14681   if (!Subtarget->hasSSE2())
14682     return SDValue();
14683
14684   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14685       (!Subtarget->hasAVX2() ||
14686        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14687     return SDValue();
14688
14689   SDValue ShAmtOp = N->getOperand(1);
14690   EVT EltVT = VT.getVectorElementType();
14691   DebugLoc DL = N->getDebugLoc();
14692   SDValue BaseShAmt = SDValue();
14693   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14694     unsigned NumElts = VT.getVectorNumElements();
14695     unsigned i = 0;
14696     for (; i != NumElts; ++i) {
14697       SDValue Arg = ShAmtOp.getOperand(i);
14698       if (Arg.getOpcode() == ISD::UNDEF) continue;
14699       BaseShAmt = Arg;
14700       break;
14701     }
14702     // Handle the case where the build_vector is all undef
14703     // FIXME: Should DAG allow this?
14704     if (i == NumElts)
14705       return SDValue();
14706
14707     for (; i != NumElts; ++i) {
14708       SDValue Arg = ShAmtOp.getOperand(i);
14709       if (Arg.getOpcode() == ISD::UNDEF) continue;
14710       if (Arg != BaseShAmt) {
14711         return SDValue();
14712       }
14713     }
14714   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14715              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14716     SDValue InVec = ShAmtOp.getOperand(0);
14717     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14718       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14719       unsigned i = 0;
14720       for (; i != NumElts; ++i) {
14721         SDValue Arg = InVec.getOperand(i);
14722         if (Arg.getOpcode() == ISD::UNDEF) continue;
14723         BaseShAmt = Arg;
14724         break;
14725       }
14726     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14727        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14728          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14729          if (C->getZExtValue() == SplatIdx)
14730            BaseShAmt = InVec.getOperand(1);
14731        }
14732     }
14733     if (BaseShAmt.getNode() == 0) {
14734       // Don't create instructions with illegal types after legalize
14735       // types has run.
14736       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14737           !DCI.isBeforeLegalize())
14738         return SDValue();
14739
14740       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14741                               DAG.getIntPtrConstant(0));
14742     }
14743   } else
14744     return SDValue();
14745
14746   // The shift amount is an i32.
14747   if (EltVT.bitsGT(MVT::i32))
14748     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14749   else if (EltVT.bitsLT(MVT::i32))
14750     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14751
14752   // The shift amount is identical so we can do a vector shift.
14753   SDValue  ValOp = N->getOperand(0);
14754   switch (N->getOpcode()) {
14755   default:
14756     llvm_unreachable("Unknown shift opcode!");
14757   case ISD::SHL:
14758     switch (VT.getSimpleVT().SimpleTy) {
14759     default: return SDValue();
14760     case MVT::v2i64:
14761     case MVT::v4i32:
14762     case MVT::v8i16:
14763     case MVT::v4i64:
14764     case MVT::v8i32:
14765     case MVT::v16i16:
14766       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14767     }
14768   case ISD::SRA:
14769     switch (VT.getSimpleVT().SimpleTy) {
14770     default: return SDValue();
14771     case MVT::v4i32:
14772     case MVT::v8i16:
14773     case MVT::v8i32:
14774     case MVT::v16i16:
14775       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14776     }
14777   case ISD::SRL:
14778     switch (VT.getSimpleVT().SimpleTy) {
14779     default: return SDValue();
14780     case MVT::v2i64:
14781     case MVT::v4i32:
14782     case MVT::v8i16:
14783     case MVT::v4i64:
14784     case MVT::v8i32:
14785     case MVT::v16i16:
14786       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14787     }
14788   }
14789 }
14790
14791
14792 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14793 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14794 // and friends.  Likewise for OR -> CMPNEQSS.
14795 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14796                             TargetLowering::DAGCombinerInfo &DCI,
14797                             const X86Subtarget *Subtarget) {
14798   unsigned opcode;
14799
14800   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14801   // we're requiring SSE2 for both.
14802   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14803     SDValue N0 = N->getOperand(0);
14804     SDValue N1 = N->getOperand(1);
14805     SDValue CMP0 = N0->getOperand(1);
14806     SDValue CMP1 = N1->getOperand(1);
14807     DebugLoc DL = N->getDebugLoc();
14808
14809     // The SETCCs should both refer to the same CMP.
14810     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14811       return SDValue();
14812
14813     SDValue CMP00 = CMP0->getOperand(0);
14814     SDValue CMP01 = CMP0->getOperand(1);
14815     EVT     VT    = CMP00.getValueType();
14816
14817     if (VT == MVT::f32 || VT == MVT::f64) {
14818       bool ExpectingFlags = false;
14819       // Check for any users that want flags:
14820       for (SDNode::use_iterator UI = N->use_begin(),
14821              UE = N->use_end();
14822            !ExpectingFlags && UI != UE; ++UI)
14823         switch (UI->getOpcode()) {
14824         default:
14825         case ISD::BR_CC:
14826         case ISD::BRCOND:
14827         case ISD::SELECT:
14828           ExpectingFlags = true;
14829           break;
14830         case ISD::CopyToReg:
14831         case ISD::SIGN_EXTEND:
14832         case ISD::ZERO_EXTEND:
14833         case ISD::ANY_EXTEND:
14834           break;
14835         }
14836
14837       if (!ExpectingFlags) {
14838         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14839         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14840
14841         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14842           X86::CondCode tmp = cc0;
14843           cc0 = cc1;
14844           cc1 = tmp;
14845         }
14846
14847         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14848             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14849           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14850           X86ISD::NodeType NTOperator = is64BitFP ?
14851             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14852           // FIXME: need symbolic constants for these magic numbers.
14853           // See X86ATTInstPrinter.cpp:printSSECC().
14854           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14855           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14856                                               DAG.getConstant(x86cc, MVT::i8));
14857           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14858                                               OnesOrZeroesF);
14859           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14860                                       DAG.getConstant(1, MVT::i32));
14861           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14862           return OneBitOfTruth;
14863         }
14864       }
14865     }
14866   }
14867   return SDValue();
14868 }
14869
14870 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14871 /// so it can be folded inside ANDNP.
14872 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14873   EVT VT = N->getValueType(0);
14874
14875   // Match direct AllOnes for 128 and 256-bit vectors
14876   if (ISD::isBuildVectorAllOnes(N))
14877     return true;
14878
14879   // Look through a bit convert.
14880   if (N->getOpcode() == ISD::BITCAST)
14881     N = N->getOperand(0).getNode();
14882
14883   // Sometimes the operand may come from a insert_subvector building a 256-bit
14884   // allones vector
14885   if (VT.is256BitVector() &&
14886       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14887     SDValue V1 = N->getOperand(0);
14888     SDValue V2 = N->getOperand(1);
14889
14890     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14891         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14892         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14893         ISD::isBuildVectorAllOnes(V2.getNode()))
14894       return true;
14895   }
14896
14897   return false;
14898 }
14899
14900 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14901                                  TargetLowering::DAGCombinerInfo &DCI,
14902                                  const X86Subtarget *Subtarget) {
14903   if (DCI.isBeforeLegalizeOps())
14904     return SDValue();
14905
14906   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14907   if (R.getNode())
14908     return R;
14909
14910   EVT VT = N->getValueType(0);
14911
14912   // Create ANDN, BLSI, and BLSR instructions
14913   // BLSI is X & (-X)
14914   // BLSR is X & (X-1)
14915   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14916     SDValue N0 = N->getOperand(0);
14917     SDValue N1 = N->getOperand(1);
14918     DebugLoc DL = N->getDebugLoc();
14919
14920     // Check LHS for not
14921     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14922       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14923     // Check RHS for not
14924     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14925       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14926
14927     // Check LHS for neg
14928     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14929         isZero(N0.getOperand(0)))
14930       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14931
14932     // Check RHS for neg
14933     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14934         isZero(N1.getOperand(0)))
14935       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14936
14937     // Check LHS for X-1
14938     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14939         isAllOnes(N0.getOperand(1)))
14940       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14941
14942     // Check RHS for X-1
14943     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14944         isAllOnes(N1.getOperand(1)))
14945       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14946
14947     return SDValue();
14948   }
14949
14950   // Want to form ANDNP nodes:
14951   // 1) In the hopes of then easily combining them with OR and AND nodes
14952   //    to form PBLEND/PSIGN.
14953   // 2) To match ANDN packed intrinsics
14954   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14955     return SDValue();
14956
14957   SDValue N0 = N->getOperand(0);
14958   SDValue N1 = N->getOperand(1);
14959   DebugLoc DL = N->getDebugLoc();
14960
14961   // Check LHS for vnot
14962   if (N0.getOpcode() == ISD::XOR &&
14963       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14964       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14965     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14966
14967   // Check RHS for vnot
14968   if (N1.getOpcode() == ISD::XOR &&
14969       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14970       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14971     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14972
14973   return SDValue();
14974 }
14975
14976 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14977                                 TargetLowering::DAGCombinerInfo &DCI,
14978                                 const X86Subtarget *Subtarget) {
14979   if (DCI.isBeforeLegalizeOps())
14980     return SDValue();
14981
14982   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14983   if (R.getNode())
14984     return R;
14985
14986   EVT VT = N->getValueType(0);
14987
14988   SDValue N0 = N->getOperand(0);
14989   SDValue N1 = N->getOperand(1);
14990
14991   // look for psign/blend
14992   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14993     if (!Subtarget->hasSSSE3() ||
14994         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14995       return SDValue();
14996
14997     // Canonicalize pandn to RHS
14998     if (N0.getOpcode() == X86ISD::ANDNP)
14999       std::swap(N0, N1);
15000     // or (and (m, y), (pandn m, x))
15001     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15002       SDValue Mask = N1.getOperand(0);
15003       SDValue X    = N1.getOperand(1);
15004       SDValue Y;
15005       if (N0.getOperand(0) == Mask)
15006         Y = N0.getOperand(1);
15007       if (N0.getOperand(1) == Mask)
15008         Y = N0.getOperand(0);
15009
15010       // Check to see if the mask appeared in both the AND and ANDNP and
15011       if (!Y.getNode())
15012         return SDValue();
15013
15014       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15015       // Look through mask bitcast.
15016       if (Mask.getOpcode() == ISD::BITCAST)
15017         Mask = Mask.getOperand(0);
15018       if (X.getOpcode() == ISD::BITCAST)
15019         X = X.getOperand(0);
15020       if (Y.getOpcode() == ISD::BITCAST)
15021         Y = Y.getOperand(0);
15022
15023       EVT MaskVT = Mask.getValueType();
15024
15025       // Validate that the Mask operand is a vector sra node.
15026       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15027       // there is no psrai.b
15028       if (Mask.getOpcode() != X86ISD::VSRAI)
15029         return SDValue();
15030
15031       // Check that the SRA is all signbits.
15032       SDValue SraC = Mask.getOperand(1);
15033       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15034       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15035       if ((SraAmt + 1) != EltBits)
15036         return SDValue();
15037
15038       DebugLoc DL = N->getDebugLoc();
15039
15040       // Now we know we at least have a plendvb with the mask val.  See if
15041       // we can form a psignb/w/d.
15042       // psign = x.type == y.type == mask.type && y = sub(0, x);
15043       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15044           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15045           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15046         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15047                "Unsupported VT for PSIGN");
15048         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15049         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15050       }
15051       // PBLENDVB only available on SSE 4.1
15052       if (!Subtarget->hasSSE41())
15053         return SDValue();
15054
15055       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15056
15057       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15058       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15059       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15060       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15061       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15062     }
15063   }
15064
15065   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15066     return SDValue();
15067
15068   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15069   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15070     std::swap(N0, N1);
15071   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15072     return SDValue();
15073   if (!N0.hasOneUse() || !N1.hasOneUse())
15074     return SDValue();
15075
15076   SDValue ShAmt0 = N0.getOperand(1);
15077   if (ShAmt0.getValueType() != MVT::i8)
15078     return SDValue();
15079   SDValue ShAmt1 = N1.getOperand(1);
15080   if (ShAmt1.getValueType() != MVT::i8)
15081     return SDValue();
15082   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15083     ShAmt0 = ShAmt0.getOperand(0);
15084   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15085     ShAmt1 = ShAmt1.getOperand(0);
15086
15087   DebugLoc DL = N->getDebugLoc();
15088   unsigned Opc = X86ISD::SHLD;
15089   SDValue Op0 = N0.getOperand(0);
15090   SDValue Op1 = N1.getOperand(0);
15091   if (ShAmt0.getOpcode() == ISD::SUB) {
15092     Opc = X86ISD::SHRD;
15093     std::swap(Op0, Op1);
15094     std::swap(ShAmt0, ShAmt1);
15095   }
15096
15097   unsigned Bits = VT.getSizeInBits();
15098   if (ShAmt1.getOpcode() == ISD::SUB) {
15099     SDValue Sum = ShAmt1.getOperand(0);
15100     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15101       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15102       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15103         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15104       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15105         return DAG.getNode(Opc, DL, VT,
15106                            Op0, Op1,
15107                            DAG.getNode(ISD::TRUNCATE, DL,
15108                                        MVT::i8, ShAmt0));
15109     }
15110   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15111     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15112     if (ShAmt0C &&
15113         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15114       return DAG.getNode(Opc, DL, VT,
15115                          N0.getOperand(0), N1.getOperand(0),
15116                          DAG.getNode(ISD::TRUNCATE, DL,
15117                                        MVT::i8, ShAmt0));
15118   }
15119
15120   return SDValue();
15121 }
15122
15123 // Generate NEG and CMOV for integer abs.
15124 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15125   EVT VT = N->getValueType(0);
15126
15127   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15128   // 8-bit integer abs to NEG and CMOV.
15129   if (VT.isInteger() && VT.getSizeInBits() == 8)
15130     return SDValue();
15131
15132   SDValue N0 = N->getOperand(0);
15133   SDValue N1 = N->getOperand(1);
15134   DebugLoc DL = N->getDebugLoc();
15135
15136   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15137   // and change it to SUB and CMOV.
15138   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15139       N0.getOpcode() == ISD::ADD &&
15140       N0.getOperand(1) == N1 &&
15141       N1.getOpcode() == ISD::SRA &&
15142       N1.getOperand(0) == N0.getOperand(0))
15143     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15144       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15145         // Generate SUB & CMOV.
15146         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15147                                   DAG.getConstant(0, VT), N0.getOperand(0));
15148
15149         SDValue Ops[] = { N0.getOperand(0), Neg,
15150                           DAG.getConstant(X86::COND_GE, MVT::i8),
15151                           SDValue(Neg.getNode(), 1) };
15152         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15153                            Ops, array_lengthof(Ops));
15154       }
15155   return SDValue();
15156 }
15157
15158 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15159 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15160                                  TargetLowering::DAGCombinerInfo &DCI,
15161                                  const X86Subtarget *Subtarget) {
15162   if (DCI.isBeforeLegalizeOps())
15163     return SDValue();
15164
15165   if (Subtarget->hasCMov()) {
15166     SDValue RV = performIntegerAbsCombine(N, DAG);
15167     if (RV.getNode())
15168       return RV;
15169   }
15170
15171   // Try forming BMI if it is available.
15172   if (!Subtarget->hasBMI())
15173     return SDValue();
15174
15175   EVT VT = N->getValueType(0);
15176
15177   if (VT != MVT::i32 && VT != MVT::i64)
15178     return SDValue();
15179
15180   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15181
15182   // Create BLSMSK instructions by finding X ^ (X-1)
15183   SDValue N0 = N->getOperand(0);
15184   SDValue N1 = N->getOperand(1);
15185   DebugLoc DL = N->getDebugLoc();
15186
15187   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15188       isAllOnes(N0.getOperand(1)))
15189     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15190
15191   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15192       isAllOnes(N1.getOperand(1)))
15193     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15194
15195   return SDValue();
15196 }
15197
15198 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15199 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15200                                   TargetLowering::DAGCombinerInfo &DCI,
15201                                   const X86Subtarget *Subtarget) {
15202   LoadSDNode *Ld = cast<LoadSDNode>(N);
15203   EVT RegVT = Ld->getValueType(0);
15204   EVT MemVT = Ld->getMemoryVT();
15205   DebugLoc dl = Ld->getDebugLoc();
15206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15207
15208   ISD::LoadExtType Ext = Ld->getExtensionType();
15209
15210   // If this is a vector EXT Load then attempt to optimize it using a
15211   // shuffle. We need SSE4 for the shuffles.
15212   // TODO: It is possible to support ZExt by zeroing the undef values
15213   // during the shuffle phase or after the shuffle.
15214   if (RegVT.isVector() && RegVT.isInteger() &&
15215       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15216     assert(MemVT != RegVT && "Cannot extend to the same type");
15217     assert(MemVT.isVector() && "Must load a vector from memory");
15218
15219     unsigned NumElems = RegVT.getVectorNumElements();
15220     unsigned RegSz = RegVT.getSizeInBits();
15221     unsigned MemSz = MemVT.getSizeInBits();
15222     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15223
15224     // All sizes must be a power of two.
15225     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15226       return SDValue();
15227
15228     // Attempt to load the original value using scalar loads.
15229     // Find the largest scalar type that divides the total loaded size.
15230     MVT SclrLoadTy = MVT::i8;
15231     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15232          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15233       MVT Tp = (MVT::SimpleValueType)tp;
15234       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15235         SclrLoadTy = Tp;
15236       }
15237     }
15238
15239     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15240     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15241         (64 <= MemSz))
15242       SclrLoadTy = MVT::f64;
15243
15244     // Calculate the number of scalar loads that we need to perform
15245     // in order to load our vector from memory.
15246     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15247
15248     // Represent our vector as a sequence of elements which are the
15249     // largest scalar that we can load.
15250     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15251       RegSz/SclrLoadTy.getSizeInBits());
15252
15253     // Represent the data using the same element type that is stored in
15254     // memory. In practice, we ''widen'' MemVT.
15255     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15256                                   RegSz/MemVT.getScalarType().getSizeInBits());
15257
15258     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15259       "Invalid vector type");
15260
15261     // We can't shuffle using an illegal type.
15262     if (!TLI.isTypeLegal(WideVecVT))
15263       return SDValue();
15264
15265     SmallVector<SDValue, 8> Chains;
15266     SDValue Ptr = Ld->getBasePtr();
15267     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15268                                         TLI.getPointerTy());
15269     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15270
15271     for (unsigned i = 0; i < NumLoads; ++i) {
15272       // Perform a single load.
15273       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15274                                        Ptr, Ld->getPointerInfo(),
15275                                        Ld->isVolatile(), Ld->isNonTemporal(),
15276                                        Ld->isInvariant(), Ld->getAlignment());
15277       Chains.push_back(ScalarLoad.getValue(1));
15278       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15279       // another round of DAGCombining.
15280       if (i == 0)
15281         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15282       else
15283         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15284                           ScalarLoad, DAG.getIntPtrConstant(i));
15285
15286       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15287     }
15288
15289     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15290                                Chains.size());
15291
15292     // Bitcast the loaded value to a vector of the original element type, in
15293     // the size of the target vector type.
15294     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15295     unsigned SizeRatio = RegSz/MemSz;
15296
15297     // Redistribute the loaded elements into the different locations.
15298     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15299     for (unsigned i = 0; i != NumElems; ++i)
15300       ShuffleVec[i*SizeRatio] = i;
15301
15302     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15303                                          DAG.getUNDEF(WideVecVT),
15304                                          &ShuffleVec[0]);
15305
15306     // Bitcast to the requested type.
15307     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15308     // Replace the original load with the new sequence
15309     // and return the new chain.
15310     return DCI.CombineTo(N, Shuff, TF, true);
15311   }
15312
15313   return SDValue();
15314 }
15315
15316 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15317 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15318                                    const X86Subtarget *Subtarget) {
15319   StoreSDNode *St = cast<StoreSDNode>(N);
15320   EVT VT = St->getValue().getValueType();
15321   EVT StVT = St->getMemoryVT();
15322   DebugLoc dl = St->getDebugLoc();
15323   SDValue StoredVal = St->getOperand(1);
15324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15325
15326   // If we are saving a concatenation of two XMM registers, perform two stores.
15327   // On Sandy Bridge, 256-bit memory operations are executed by two
15328   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15329   // memory  operation.
15330   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15331       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15332       StoredVal.getNumOperands() == 2) {
15333     SDValue Value0 = StoredVal.getOperand(0);
15334     SDValue Value1 = StoredVal.getOperand(1);
15335
15336     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15337     SDValue Ptr0 = St->getBasePtr();
15338     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15339
15340     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15341                                 St->getPointerInfo(), St->isVolatile(),
15342                                 St->isNonTemporal(), St->getAlignment());
15343     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15344                                 St->getPointerInfo(), St->isVolatile(),
15345                                 St->isNonTemporal(), St->getAlignment());
15346     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15347   }
15348
15349   // Optimize trunc store (of multiple scalars) to shuffle and store.
15350   // First, pack all of the elements in one place. Next, store to memory
15351   // in fewer chunks.
15352   if (St->isTruncatingStore() && VT.isVector()) {
15353     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15354     unsigned NumElems = VT.getVectorNumElements();
15355     assert(StVT != VT && "Cannot truncate to the same type");
15356     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15357     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15358
15359     // From, To sizes and ElemCount must be pow of two
15360     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15361     // We are going to use the original vector elt for storing.
15362     // Accumulated smaller vector elements must be a multiple of the store size.
15363     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15364
15365     unsigned SizeRatio  = FromSz / ToSz;
15366
15367     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15368
15369     // Create a type on which we perform the shuffle
15370     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15371             StVT.getScalarType(), NumElems*SizeRatio);
15372
15373     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15374
15375     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15376     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15377     for (unsigned i = 0; i != NumElems; ++i)
15378       ShuffleVec[i] = i * SizeRatio;
15379
15380     // Can't shuffle using an illegal type.
15381     if (!TLI.isTypeLegal(WideVecVT))
15382       return SDValue();
15383
15384     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15385                                          DAG.getUNDEF(WideVecVT),
15386                                          &ShuffleVec[0]);
15387     // At this point all of the data is stored at the bottom of the
15388     // register. We now need to save it to mem.
15389
15390     // Find the largest store unit
15391     MVT StoreType = MVT::i8;
15392     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15393          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15394       MVT Tp = (MVT::SimpleValueType)tp;
15395       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15396         StoreType = Tp;
15397     }
15398
15399     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15400     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15401         (64 <= NumElems * ToSz))
15402       StoreType = MVT::f64;
15403
15404     // Bitcast the original vector into a vector of store-size units
15405     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15406             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15407     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15408     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15409     SmallVector<SDValue, 8> Chains;
15410     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15411                                         TLI.getPointerTy());
15412     SDValue Ptr = St->getBasePtr();
15413
15414     // Perform one or more big stores into memory.
15415     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15416       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15417                                    StoreType, ShuffWide,
15418                                    DAG.getIntPtrConstant(i));
15419       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15420                                 St->getPointerInfo(), St->isVolatile(),
15421                                 St->isNonTemporal(), St->getAlignment());
15422       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15423       Chains.push_back(Ch);
15424     }
15425
15426     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15427                                Chains.size());
15428   }
15429
15430
15431   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15432   // the FP state in cases where an emms may be missing.
15433   // A preferable solution to the general problem is to figure out the right
15434   // places to insert EMMS.  This qualifies as a quick hack.
15435
15436   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15437   if (VT.getSizeInBits() != 64)
15438     return SDValue();
15439
15440   const Function *F = DAG.getMachineFunction().getFunction();
15441   bool NoImplicitFloatOps = F->getFnAttributes().hasNoImplicitFloatAttr();
15442   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15443                      && Subtarget->hasSSE2();
15444   if ((VT.isVector() ||
15445        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15446       isa<LoadSDNode>(St->getValue()) &&
15447       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15448       St->getChain().hasOneUse() && !St->isVolatile()) {
15449     SDNode* LdVal = St->getValue().getNode();
15450     LoadSDNode *Ld = 0;
15451     int TokenFactorIndex = -1;
15452     SmallVector<SDValue, 8> Ops;
15453     SDNode* ChainVal = St->getChain().getNode();
15454     // Must be a store of a load.  We currently handle two cases:  the load
15455     // is a direct child, and it's under an intervening TokenFactor.  It is
15456     // possible to dig deeper under nested TokenFactors.
15457     if (ChainVal == LdVal)
15458       Ld = cast<LoadSDNode>(St->getChain());
15459     else if (St->getValue().hasOneUse() &&
15460              ChainVal->getOpcode() == ISD::TokenFactor) {
15461       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15462         if (ChainVal->getOperand(i).getNode() == LdVal) {
15463           TokenFactorIndex = i;
15464           Ld = cast<LoadSDNode>(St->getValue());
15465         } else
15466           Ops.push_back(ChainVal->getOperand(i));
15467       }
15468     }
15469
15470     if (!Ld || !ISD::isNormalLoad(Ld))
15471       return SDValue();
15472
15473     // If this is not the MMX case, i.e. we are just turning i64 load/store
15474     // into f64 load/store, avoid the transformation if there are multiple
15475     // uses of the loaded value.
15476     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15477       return SDValue();
15478
15479     DebugLoc LdDL = Ld->getDebugLoc();
15480     DebugLoc StDL = N->getDebugLoc();
15481     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15482     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15483     // pair instead.
15484     if (Subtarget->is64Bit() || F64IsLegal) {
15485       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15486       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15487                                   Ld->getPointerInfo(), Ld->isVolatile(),
15488                                   Ld->isNonTemporal(), Ld->isInvariant(),
15489                                   Ld->getAlignment());
15490       SDValue NewChain = NewLd.getValue(1);
15491       if (TokenFactorIndex != -1) {
15492         Ops.push_back(NewChain);
15493         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15494                                Ops.size());
15495       }
15496       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15497                           St->getPointerInfo(),
15498                           St->isVolatile(), St->isNonTemporal(),
15499                           St->getAlignment());
15500     }
15501
15502     // Otherwise, lower to two pairs of 32-bit loads / stores.
15503     SDValue LoAddr = Ld->getBasePtr();
15504     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15505                                  DAG.getConstant(4, MVT::i32));
15506
15507     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15508                                Ld->getPointerInfo(),
15509                                Ld->isVolatile(), Ld->isNonTemporal(),
15510                                Ld->isInvariant(), Ld->getAlignment());
15511     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15512                                Ld->getPointerInfo().getWithOffset(4),
15513                                Ld->isVolatile(), Ld->isNonTemporal(),
15514                                Ld->isInvariant(),
15515                                MinAlign(Ld->getAlignment(), 4));
15516
15517     SDValue NewChain = LoLd.getValue(1);
15518     if (TokenFactorIndex != -1) {
15519       Ops.push_back(LoLd);
15520       Ops.push_back(HiLd);
15521       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15522                              Ops.size());
15523     }
15524
15525     LoAddr = St->getBasePtr();
15526     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15527                          DAG.getConstant(4, MVT::i32));
15528
15529     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15530                                 St->getPointerInfo(),
15531                                 St->isVolatile(), St->isNonTemporal(),
15532                                 St->getAlignment());
15533     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15534                                 St->getPointerInfo().getWithOffset(4),
15535                                 St->isVolatile(),
15536                                 St->isNonTemporal(),
15537                                 MinAlign(St->getAlignment(), 4));
15538     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15539   }
15540   return SDValue();
15541 }
15542
15543 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15544 /// and return the operands for the horizontal operation in LHS and RHS.  A
15545 /// horizontal operation performs the binary operation on successive elements
15546 /// of its first operand, then on successive elements of its second operand,
15547 /// returning the resulting values in a vector.  For example, if
15548 ///   A = < float a0, float a1, float a2, float a3 >
15549 /// and
15550 ///   B = < float b0, float b1, float b2, float b3 >
15551 /// then the result of doing a horizontal operation on A and B is
15552 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15553 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15554 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15555 /// set to A, RHS to B, and the routine returns 'true'.
15556 /// Note that the binary operation should have the property that if one of the
15557 /// operands is UNDEF then the result is UNDEF.
15558 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15559   // Look for the following pattern: if
15560   //   A = < float a0, float a1, float a2, float a3 >
15561   //   B = < float b0, float b1, float b2, float b3 >
15562   // and
15563   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15564   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15565   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15566   // which is A horizontal-op B.
15567
15568   // At least one of the operands should be a vector shuffle.
15569   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15570       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15571     return false;
15572
15573   EVT VT = LHS.getValueType();
15574
15575   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15576          "Unsupported vector type for horizontal add/sub");
15577
15578   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15579   // operate independently on 128-bit lanes.
15580   unsigned NumElts = VT.getVectorNumElements();
15581   unsigned NumLanes = VT.getSizeInBits()/128;
15582   unsigned NumLaneElts = NumElts / NumLanes;
15583   assert((NumLaneElts % 2 == 0) &&
15584          "Vector type should have an even number of elements in each lane");
15585   unsigned HalfLaneElts = NumLaneElts/2;
15586
15587   // View LHS in the form
15588   //   LHS = VECTOR_SHUFFLE A, B, LMask
15589   // If LHS is not a shuffle then pretend it is the shuffle
15590   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15591   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15592   // type VT.
15593   SDValue A, B;
15594   SmallVector<int, 16> LMask(NumElts);
15595   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15596     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15597       A = LHS.getOperand(0);
15598     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15599       B = LHS.getOperand(1);
15600     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15601     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15602   } else {
15603     if (LHS.getOpcode() != ISD::UNDEF)
15604       A = LHS;
15605     for (unsigned i = 0; i != NumElts; ++i)
15606       LMask[i] = i;
15607   }
15608
15609   // Likewise, view RHS in the form
15610   //   RHS = VECTOR_SHUFFLE C, D, RMask
15611   SDValue C, D;
15612   SmallVector<int, 16> RMask(NumElts);
15613   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15614     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15615       C = RHS.getOperand(0);
15616     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15617       D = RHS.getOperand(1);
15618     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15619     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15620   } else {
15621     if (RHS.getOpcode() != ISD::UNDEF)
15622       C = RHS;
15623     for (unsigned i = 0; i != NumElts; ++i)
15624       RMask[i] = i;
15625   }
15626
15627   // Check that the shuffles are both shuffling the same vectors.
15628   if (!(A == C && B == D) && !(A == D && B == C))
15629     return false;
15630
15631   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15632   if (!A.getNode() && !B.getNode())
15633     return false;
15634
15635   // If A and B occur in reverse order in RHS, then "swap" them (which means
15636   // rewriting the mask).
15637   if (A != C)
15638     CommuteVectorShuffleMask(RMask, NumElts);
15639
15640   // At this point LHS and RHS are equivalent to
15641   //   LHS = VECTOR_SHUFFLE A, B, LMask
15642   //   RHS = VECTOR_SHUFFLE A, B, RMask
15643   // Check that the masks correspond to performing a horizontal operation.
15644   for (unsigned i = 0; i != NumElts; ++i) {
15645     int LIdx = LMask[i], RIdx = RMask[i];
15646
15647     // Ignore any UNDEF components.
15648     if (LIdx < 0 || RIdx < 0 ||
15649         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15650         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15651       continue;
15652
15653     // Check that successive elements are being operated on.  If not, this is
15654     // not a horizontal operation.
15655     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15656     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15657     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15658     if (!(LIdx == Index && RIdx == Index + 1) &&
15659         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15660       return false;
15661   }
15662
15663   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15664   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15665   return true;
15666 }
15667
15668 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15669 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15670                                   const X86Subtarget *Subtarget) {
15671   EVT VT = N->getValueType(0);
15672   SDValue LHS = N->getOperand(0);
15673   SDValue RHS = N->getOperand(1);
15674
15675   // Try to synthesize horizontal adds from adds of shuffles.
15676   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15677        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15678       isHorizontalBinOp(LHS, RHS, true))
15679     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15680   return SDValue();
15681 }
15682
15683 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15684 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15685                                   const X86Subtarget *Subtarget) {
15686   EVT VT = N->getValueType(0);
15687   SDValue LHS = N->getOperand(0);
15688   SDValue RHS = N->getOperand(1);
15689
15690   // Try to synthesize horizontal subs from subs of shuffles.
15691   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15692        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15693       isHorizontalBinOp(LHS, RHS, false))
15694     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15695   return SDValue();
15696 }
15697
15698 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15699 /// X86ISD::FXOR nodes.
15700 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15701   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15702   // F[X]OR(0.0, x) -> x
15703   // F[X]OR(x, 0.0) -> x
15704   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15705     if (C->getValueAPF().isPosZero())
15706       return N->getOperand(1);
15707   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15708     if (C->getValueAPF().isPosZero())
15709       return N->getOperand(0);
15710   return SDValue();
15711 }
15712
15713 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15714 /// X86ISD::FMAX nodes.
15715 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15716   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15717
15718   // Only perform optimizations if UnsafeMath is used.
15719   if (!DAG.getTarget().Options.UnsafeFPMath)
15720     return SDValue();
15721
15722   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15723   // into FMINC and FMAXC, which are Commutative operations.
15724   unsigned NewOp = 0;
15725   switch (N->getOpcode()) {
15726     default: llvm_unreachable("unknown opcode");
15727     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15728     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15729   }
15730
15731   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15732                      N->getOperand(0), N->getOperand(1));
15733 }
15734
15735
15736 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15737 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15738   // FAND(0.0, x) -> 0.0
15739   // FAND(x, 0.0) -> 0.0
15740   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15741     if (C->getValueAPF().isPosZero())
15742       return N->getOperand(0);
15743   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15744     if (C->getValueAPF().isPosZero())
15745       return N->getOperand(1);
15746   return SDValue();
15747 }
15748
15749 static SDValue PerformBTCombine(SDNode *N,
15750                                 SelectionDAG &DAG,
15751                                 TargetLowering::DAGCombinerInfo &DCI) {
15752   // BT ignores high bits in the bit index operand.
15753   SDValue Op1 = N->getOperand(1);
15754   if (Op1.hasOneUse()) {
15755     unsigned BitWidth = Op1.getValueSizeInBits();
15756     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15757     APInt KnownZero, KnownOne;
15758     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15759                                           !DCI.isBeforeLegalizeOps());
15760     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15761     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15762         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15763       DCI.CommitTargetLoweringOpt(TLO);
15764   }
15765   return SDValue();
15766 }
15767
15768 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15769   SDValue Op = N->getOperand(0);
15770   if (Op.getOpcode() == ISD::BITCAST)
15771     Op = Op.getOperand(0);
15772   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15773   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15774       VT.getVectorElementType().getSizeInBits() ==
15775       OpVT.getVectorElementType().getSizeInBits()) {
15776     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15777   }
15778   return SDValue();
15779 }
15780
15781 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15782                                   TargetLowering::DAGCombinerInfo &DCI,
15783                                   const X86Subtarget *Subtarget) {
15784   if (!DCI.isBeforeLegalizeOps())
15785     return SDValue();
15786
15787   if (!Subtarget->hasAVX())
15788     return SDValue();
15789
15790   EVT VT = N->getValueType(0);
15791   SDValue Op = N->getOperand(0);
15792   EVT OpVT = Op.getValueType();
15793   DebugLoc dl = N->getDebugLoc();
15794
15795   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15796       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15797
15798     if (Subtarget->hasAVX2())
15799       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15800
15801     // Optimize vectors in AVX mode
15802     // Sign extend  v8i16 to v8i32 and
15803     //              v4i32 to v4i64
15804     //
15805     // Divide input vector into two parts
15806     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15807     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15808     // concat the vectors to original VT
15809
15810     unsigned NumElems = OpVT.getVectorNumElements();
15811     SDValue Undef = DAG.getUNDEF(OpVT);
15812
15813     SmallVector<int,8> ShufMask1(NumElems, -1);
15814     for (unsigned i = 0; i != NumElems/2; ++i)
15815       ShufMask1[i] = i;
15816
15817     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15818
15819     SmallVector<int,8> ShufMask2(NumElems, -1);
15820     for (unsigned i = 0; i != NumElems/2; ++i)
15821       ShufMask2[i] = i + NumElems/2;
15822
15823     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15824
15825     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15826                                   VT.getVectorNumElements()/2);
15827
15828     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15829     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15830
15831     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15832   }
15833   return SDValue();
15834 }
15835
15836 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15837                                  const X86Subtarget* Subtarget) {
15838   DebugLoc dl = N->getDebugLoc();
15839   EVT VT = N->getValueType(0);
15840
15841   // Let legalize expand this if it isn't a legal type yet.
15842   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15843     return SDValue();
15844
15845   EVT ScalarVT = VT.getScalarType();
15846   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15847       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15848     return SDValue();
15849
15850   SDValue A = N->getOperand(0);
15851   SDValue B = N->getOperand(1);
15852   SDValue C = N->getOperand(2);
15853
15854   bool NegA = (A.getOpcode() == ISD::FNEG);
15855   bool NegB = (B.getOpcode() == ISD::FNEG);
15856   bool NegC = (C.getOpcode() == ISD::FNEG);
15857
15858   // Negative multiplication when NegA xor NegB
15859   bool NegMul = (NegA != NegB);
15860   if (NegA)
15861     A = A.getOperand(0);
15862   if (NegB)
15863     B = B.getOperand(0);
15864   if (NegC)
15865     C = C.getOperand(0);
15866
15867   unsigned Opcode;
15868   if (!NegMul)
15869     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15870   else
15871     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15872
15873   return DAG.getNode(Opcode, dl, VT, A, B, C);
15874 }
15875
15876 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15877                                   TargetLowering::DAGCombinerInfo &DCI,
15878                                   const X86Subtarget *Subtarget) {
15879   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15880   //           (and (i32 x86isd::setcc_carry), 1)
15881   // This eliminates the zext. This transformation is necessary because
15882   // ISD::SETCC is always legalized to i8.
15883   DebugLoc dl = N->getDebugLoc();
15884   SDValue N0 = N->getOperand(0);
15885   EVT VT = N->getValueType(0);
15886   EVT OpVT = N0.getValueType();
15887
15888   if (N0.getOpcode() == ISD::AND &&
15889       N0.hasOneUse() &&
15890       N0.getOperand(0).hasOneUse()) {
15891     SDValue N00 = N0.getOperand(0);
15892     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15893       return SDValue();
15894     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15895     if (!C || C->getZExtValue() != 1)
15896       return SDValue();
15897     return DAG.getNode(ISD::AND, dl, VT,
15898                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15899                                    N00.getOperand(0), N00.getOperand(1)),
15900                        DAG.getConstant(1, VT));
15901   }
15902
15903   // Optimize vectors in AVX mode:
15904   //
15905   //   v8i16 -> v8i32
15906   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15907   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15908   //   Concat upper and lower parts.
15909   //
15910   //   v4i32 -> v4i64
15911   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15912   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15913   //   Concat upper and lower parts.
15914   //
15915   if (!DCI.isBeforeLegalizeOps())
15916     return SDValue();
15917
15918   if (!Subtarget->hasAVX())
15919     return SDValue();
15920
15921   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15922       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15923
15924     if (Subtarget->hasAVX2())
15925       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15926
15927     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15928     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15929     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15930
15931     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15932                                VT.getVectorNumElements()/2);
15933
15934     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15935     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15936
15937     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15938   }
15939
15940   return SDValue();
15941 }
15942
15943 // Optimize x == -y --> x+y == 0
15944 //          x != -y --> x+y != 0
15945 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15946   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15947   SDValue LHS = N->getOperand(0);
15948   SDValue RHS = N->getOperand(1);
15949
15950   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15952       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15953         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15954                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15955         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15956                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15957       }
15958   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15959     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15960       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15961         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15962                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15963         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15964                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15965       }
15966   return SDValue();
15967 }
15968
15969 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15970 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15971                                    TargetLowering::DAGCombinerInfo &DCI,
15972                                    const X86Subtarget *Subtarget) {
15973   DebugLoc DL = N->getDebugLoc();
15974   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15975   SDValue EFLAGS = N->getOperand(1);
15976
15977   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15978   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15979   // cases.
15980   if (CC == X86::COND_B)
15981     return DAG.getNode(ISD::AND, DL, MVT::i8,
15982                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15983                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15984                        DAG.getConstant(1, MVT::i8));
15985
15986   SDValue Flags;
15987
15988   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15989   if (Flags.getNode()) {
15990     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15991     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15992   }
15993
15994   return SDValue();
15995 }
15996
15997 // Optimize branch condition evaluation.
15998 //
15999 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16000                                     TargetLowering::DAGCombinerInfo &DCI,
16001                                     const X86Subtarget *Subtarget) {
16002   DebugLoc DL = N->getDebugLoc();
16003   SDValue Chain = N->getOperand(0);
16004   SDValue Dest = N->getOperand(1);
16005   SDValue EFLAGS = N->getOperand(3);
16006   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16007
16008   SDValue Flags;
16009
16010   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16011   if (Flags.getNode()) {
16012     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16013     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16014                        Flags);
16015   }
16016
16017   return SDValue();
16018 }
16019
16020 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16021   SDValue Op0 = N->getOperand(0);
16022   EVT InVT = Op0->getValueType(0);
16023
16024   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16025   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16026     DebugLoc dl = N->getDebugLoc();
16027     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16028     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16029     // Notice that we use SINT_TO_FP because we know that the high bits
16030     // are zero and SINT_TO_FP is better supported by the hardware.
16031     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16032   }
16033
16034   return SDValue();
16035 }
16036
16037 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16038                                         const X86TargetLowering *XTLI) {
16039   SDValue Op0 = N->getOperand(0);
16040   EVT InVT = Op0->getValueType(0);
16041
16042   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16043   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16044     DebugLoc dl = N->getDebugLoc();
16045     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16046     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16047     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16048   }
16049
16050   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16051   // a 32-bit target where SSE doesn't support i64->FP operations.
16052   if (Op0.getOpcode() == ISD::LOAD) {
16053     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16054     EVT VT = Ld->getValueType(0);
16055     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16056         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16057         !XTLI->getSubtarget()->is64Bit() &&
16058         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16059       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16060                                           Ld->getChain(), Op0, DAG);
16061       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16062       return FILDChain;
16063     }
16064   }
16065   return SDValue();
16066 }
16067
16068 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
16069   EVT VT = N->getValueType(0);
16070
16071   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
16072   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
16073     DebugLoc dl = N->getDebugLoc();
16074     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16075     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
16076     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
16077   }
16078
16079   return SDValue();
16080 }
16081
16082 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16083 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16084                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16085   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16086   // the result is either zero or one (depending on the input carry bit).
16087   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16088   if (X86::isZeroNode(N->getOperand(0)) &&
16089       X86::isZeroNode(N->getOperand(1)) &&
16090       // We don't have a good way to replace an EFLAGS use, so only do this when
16091       // dead right now.
16092       SDValue(N, 1).use_empty()) {
16093     DebugLoc DL = N->getDebugLoc();
16094     EVT VT = N->getValueType(0);
16095     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16096     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16097                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16098                                            DAG.getConstant(X86::COND_B,MVT::i8),
16099                                            N->getOperand(2)),
16100                                DAG.getConstant(1, VT));
16101     return DCI.CombineTo(N, Res1, CarryOut);
16102   }
16103
16104   return SDValue();
16105 }
16106
16107 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16108 //      (add Y, (setne X, 0)) -> sbb -1, Y
16109 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16110 //      (sub (setne X, 0), Y) -> adc -1, Y
16111 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16112   DebugLoc DL = N->getDebugLoc();
16113
16114   // Look through ZExts.
16115   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16116   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16117     return SDValue();
16118
16119   SDValue SetCC = Ext.getOperand(0);
16120   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16121     return SDValue();
16122
16123   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16124   if (CC != X86::COND_E && CC != X86::COND_NE)
16125     return SDValue();
16126
16127   SDValue Cmp = SetCC.getOperand(1);
16128   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16129       !X86::isZeroNode(Cmp.getOperand(1)) ||
16130       !Cmp.getOperand(0).getValueType().isInteger())
16131     return SDValue();
16132
16133   SDValue CmpOp0 = Cmp.getOperand(0);
16134   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16135                                DAG.getConstant(1, CmpOp0.getValueType()));
16136
16137   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16138   if (CC == X86::COND_NE)
16139     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16140                        DL, OtherVal.getValueType(), OtherVal,
16141                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16142   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16143                      DL, OtherVal.getValueType(), OtherVal,
16144                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16145 }
16146
16147 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16148 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16149                                  const X86Subtarget *Subtarget) {
16150   EVT VT = N->getValueType(0);
16151   SDValue Op0 = N->getOperand(0);
16152   SDValue Op1 = N->getOperand(1);
16153
16154   // Try to synthesize horizontal adds from adds of shuffles.
16155   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16156        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16157       isHorizontalBinOp(Op0, Op1, true))
16158     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16159
16160   return OptimizeConditionalInDecrement(N, DAG);
16161 }
16162
16163 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16164                                  const X86Subtarget *Subtarget) {
16165   SDValue Op0 = N->getOperand(0);
16166   SDValue Op1 = N->getOperand(1);
16167
16168   // X86 can't encode an immediate LHS of a sub. See if we can push the
16169   // negation into a preceding instruction.
16170   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16171     // If the RHS of the sub is a XOR with one use and a constant, invert the
16172     // immediate. Then add one to the LHS of the sub so we can turn
16173     // X-Y -> X+~Y+1, saving one register.
16174     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16175         isa<ConstantSDNode>(Op1.getOperand(1))) {
16176       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16177       EVT VT = Op0.getValueType();
16178       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16179                                    Op1.getOperand(0),
16180                                    DAG.getConstant(~XorC, VT));
16181       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16182                          DAG.getConstant(C->getAPIntValue()+1, VT));
16183     }
16184   }
16185
16186   // Try to synthesize horizontal adds from adds of shuffles.
16187   EVT VT = N->getValueType(0);
16188   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16189        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16190       isHorizontalBinOp(Op0, Op1, true))
16191     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16192
16193   return OptimizeConditionalInDecrement(N, DAG);
16194 }
16195
16196 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16197                                              DAGCombinerInfo &DCI) const {
16198   SelectionDAG &DAG = DCI.DAG;
16199   switch (N->getOpcode()) {
16200   default: break;
16201   case ISD::EXTRACT_VECTOR_ELT:
16202     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16203   case ISD::VSELECT:
16204   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16205   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16206   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16207   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16208   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16209   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16210   case ISD::SHL:
16211   case ISD::SRA:
16212   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16213   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16214   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16215   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16216   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16217   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16218   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16219   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16220   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16221   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16222   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16223   case X86ISD::FXOR:
16224   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16225   case X86ISD::FMIN:
16226   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16227   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16228   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16229   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16230   case ISD::ANY_EXTEND:
16231   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16232   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16233   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16234   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16235   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16236   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16237   case X86ISD::SHUFP:       // Handle all target specific shuffles
16238   case X86ISD::PALIGN:
16239   case X86ISD::UNPCKH:
16240   case X86ISD::UNPCKL:
16241   case X86ISD::MOVHLPS:
16242   case X86ISD::MOVLHPS:
16243   case X86ISD::PSHUFD:
16244   case X86ISD::PSHUFHW:
16245   case X86ISD::PSHUFLW:
16246   case X86ISD::MOVSS:
16247   case X86ISD::MOVSD:
16248   case X86ISD::VPERMILP:
16249   case X86ISD::VPERM2X128:
16250   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16251   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16252   }
16253
16254   return SDValue();
16255 }
16256
16257 /// isTypeDesirableForOp - Return true if the target has native support for
16258 /// the specified value type and it is 'desirable' to use the type for the
16259 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16260 /// instruction encodings are longer and some i16 instructions are slow.
16261 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16262   if (!isTypeLegal(VT))
16263     return false;
16264   if (VT != MVT::i16)
16265     return true;
16266
16267   switch (Opc) {
16268   default:
16269     return true;
16270   case ISD::LOAD:
16271   case ISD::SIGN_EXTEND:
16272   case ISD::ZERO_EXTEND:
16273   case ISD::ANY_EXTEND:
16274   case ISD::SHL:
16275   case ISD::SRL:
16276   case ISD::SUB:
16277   case ISD::ADD:
16278   case ISD::MUL:
16279   case ISD::AND:
16280   case ISD::OR:
16281   case ISD::XOR:
16282     return false;
16283   }
16284 }
16285
16286 /// IsDesirableToPromoteOp - This method query the target whether it is
16287 /// beneficial for dag combiner to promote the specified node. If true, it
16288 /// should return the desired promotion type by reference.
16289 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16290   EVT VT = Op.getValueType();
16291   if (VT != MVT::i16)
16292     return false;
16293
16294   bool Promote = false;
16295   bool Commute = false;
16296   switch (Op.getOpcode()) {
16297   default: break;
16298   case ISD::LOAD: {
16299     LoadSDNode *LD = cast<LoadSDNode>(Op);
16300     // If the non-extending load has a single use and it's not live out, then it
16301     // might be folded.
16302     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16303                                                      Op.hasOneUse()*/) {
16304       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16305              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16306         // The only case where we'd want to promote LOAD (rather then it being
16307         // promoted as an operand is when it's only use is liveout.
16308         if (UI->getOpcode() != ISD::CopyToReg)
16309           return false;
16310       }
16311     }
16312     Promote = true;
16313     break;
16314   }
16315   case ISD::SIGN_EXTEND:
16316   case ISD::ZERO_EXTEND:
16317   case ISD::ANY_EXTEND:
16318     Promote = true;
16319     break;
16320   case ISD::SHL:
16321   case ISD::SRL: {
16322     SDValue N0 = Op.getOperand(0);
16323     // Look out for (store (shl (load), x)).
16324     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16325       return false;
16326     Promote = true;
16327     break;
16328   }
16329   case ISD::ADD:
16330   case ISD::MUL:
16331   case ISD::AND:
16332   case ISD::OR:
16333   case ISD::XOR:
16334     Commute = true;
16335     // fallthrough
16336   case ISD::SUB: {
16337     SDValue N0 = Op.getOperand(0);
16338     SDValue N1 = Op.getOperand(1);
16339     if (!Commute && MayFoldLoad(N1))
16340       return false;
16341     // Avoid disabling potential load folding opportunities.
16342     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16343       return false;
16344     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16345       return false;
16346     Promote = true;
16347   }
16348   }
16349
16350   PVT = MVT::i32;
16351   return Promote;
16352 }
16353
16354 //===----------------------------------------------------------------------===//
16355 //                           X86 Inline Assembly Support
16356 //===----------------------------------------------------------------------===//
16357
16358 namespace {
16359   // Helper to match a string separated by whitespace.
16360   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16361     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16362
16363     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16364       StringRef piece(*args[i]);
16365       if (!s.startswith(piece)) // Check if the piece matches.
16366         return false;
16367
16368       s = s.substr(piece.size());
16369       StringRef::size_type pos = s.find_first_not_of(" \t");
16370       if (pos == 0) // We matched a prefix.
16371         return false;
16372
16373       s = s.substr(pos);
16374     }
16375
16376     return s.empty();
16377   }
16378   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16379 }
16380
16381 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16382   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16383
16384   std::string AsmStr = IA->getAsmString();
16385
16386   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16387   if (!Ty || Ty->getBitWidth() % 16 != 0)
16388     return false;
16389
16390   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16391   SmallVector<StringRef, 4> AsmPieces;
16392   SplitString(AsmStr, AsmPieces, ";\n");
16393
16394   switch (AsmPieces.size()) {
16395   default: return false;
16396   case 1:
16397     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16398     // we will turn this bswap into something that will be lowered to logical
16399     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16400     // lower so don't worry about this.
16401     // bswap $0
16402     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16403         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16404         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16405         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16406         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16407         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16408       // No need to check constraints, nothing other than the equivalent of
16409       // "=r,0" would be valid here.
16410       return IntrinsicLowering::LowerToByteSwap(CI);
16411     }
16412
16413     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16414     if (CI->getType()->isIntegerTy(16) &&
16415         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16416         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16417          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16418       AsmPieces.clear();
16419       const std::string &ConstraintsStr = IA->getConstraintString();
16420       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16421       std::sort(AsmPieces.begin(), AsmPieces.end());
16422       if (AsmPieces.size() == 4 &&
16423           AsmPieces[0] == "~{cc}" &&
16424           AsmPieces[1] == "~{dirflag}" &&
16425           AsmPieces[2] == "~{flags}" &&
16426           AsmPieces[3] == "~{fpsr}")
16427       return IntrinsicLowering::LowerToByteSwap(CI);
16428     }
16429     break;
16430   case 3:
16431     if (CI->getType()->isIntegerTy(32) &&
16432         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16433         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16434         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16435         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16436       AsmPieces.clear();
16437       const std::string &ConstraintsStr = IA->getConstraintString();
16438       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16439       std::sort(AsmPieces.begin(), AsmPieces.end());
16440       if (AsmPieces.size() == 4 &&
16441           AsmPieces[0] == "~{cc}" &&
16442           AsmPieces[1] == "~{dirflag}" &&
16443           AsmPieces[2] == "~{flags}" &&
16444           AsmPieces[3] == "~{fpsr}")
16445         return IntrinsicLowering::LowerToByteSwap(CI);
16446     }
16447
16448     if (CI->getType()->isIntegerTy(64)) {
16449       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16450       if (Constraints.size() >= 2 &&
16451           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16452           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16453         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16454         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16455             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16456             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16457           return IntrinsicLowering::LowerToByteSwap(CI);
16458       }
16459     }
16460     break;
16461   }
16462   return false;
16463 }
16464
16465
16466
16467 /// getConstraintType - Given a constraint letter, return the type of
16468 /// constraint it is for this target.
16469 X86TargetLowering::ConstraintType
16470 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16471   if (Constraint.size() == 1) {
16472     switch (Constraint[0]) {
16473     case 'R':
16474     case 'q':
16475     case 'Q':
16476     case 'f':
16477     case 't':
16478     case 'u':
16479     case 'y':
16480     case 'x':
16481     case 'Y':
16482     case 'l':
16483       return C_RegisterClass;
16484     case 'a':
16485     case 'b':
16486     case 'c':
16487     case 'd':
16488     case 'S':
16489     case 'D':
16490     case 'A':
16491       return C_Register;
16492     case 'I':
16493     case 'J':
16494     case 'K':
16495     case 'L':
16496     case 'M':
16497     case 'N':
16498     case 'G':
16499     case 'C':
16500     case 'e':
16501     case 'Z':
16502       return C_Other;
16503     default:
16504       break;
16505     }
16506   }
16507   return TargetLowering::getConstraintType(Constraint);
16508 }
16509
16510 /// Examine constraint type and operand type and determine a weight value.
16511 /// This object must already have been set up with the operand type
16512 /// and the current alternative constraint selected.
16513 TargetLowering::ConstraintWeight
16514   X86TargetLowering::getSingleConstraintMatchWeight(
16515     AsmOperandInfo &info, const char *constraint) const {
16516   ConstraintWeight weight = CW_Invalid;
16517   Value *CallOperandVal = info.CallOperandVal;
16518     // If we don't have a value, we can't do a match,
16519     // but allow it at the lowest weight.
16520   if (CallOperandVal == NULL)
16521     return CW_Default;
16522   Type *type = CallOperandVal->getType();
16523   // Look at the constraint type.
16524   switch (*constraint) {
16525   default:
16526     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16527   case 'R':
16528   case 'q':
16529   case 'Q':
16530   case 'a':
16531   case 'b':
16532   case 'c':
16533   case 'd':
16534   case 'S':
16535   case 'D':
16536   case 'A':
16537     if (CallOperandVal->getType()->isIntegerTy())
16538       weight = CW_SpecificReg;
16539     break;
16540   case 'f':
16541   case 't':
16542   case 'u':
16543       if (type->isFloatingPointTy())
16544         weight = CW_SpecificReg;
16545       break;
16546   case 'y':
16547       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16548         weight = CW_SpecificReg;
16549       break;
16550   case 'x':
16551   case 'Y':
16552     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16553         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16554       weight = CW_Register;
16555     break;
16556   case 'I':
16557     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16558       if (C->getZExtValue() <= 31)
16559         weight = CW_Constant;
16560     }
16561     break;
16562   case 'J':
16563     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16564       if (C->getZExtValue() <= 63)
16565         weight = CW_Constant;
16566     }
16567     break;
16568   case 'K':
16569     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16570       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16571         weight = CW_Constant;
16572     }
16573     break;
16574   case 'L':
16575     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16576       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16577         weight = CW_Constant;
16578     }
16579     break;
16580   case 'M':
16581     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16582       if (C->getZExtValue() <= 3)
16583         weight = CW_Constant;
16584     }
16585     break;
16586   case 'N':
16587     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16588       if (C->getZExtValue() <= 0xff)
16589         weight = CW_Constant;
16590     }
16591     break;
16592   case 'G':
16593   case 'C':
16594     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16595       weight = CW_Constant;
16596     }
16597     break;
16598   case 'e':
16599     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16600       if ((C->getSExtValue() >= -0x80000000LL) &&
16601           (C->getSExtValue() <= 0x7fffffffLL))
16602         weight = CW_Constant;
16603     }
16604     break;
16605   case 'Z':
16606     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16607       if (C->getZExtValue() <= 0xffffffff)
16608         weight = CW_Constant;
16609     }
16610     break;
16611   }
16612   return weight;
16613 }
16614
16615 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16616 /// with another that has more specific requirements based on the type of the
16617 /// corresponding operand.
16618 const char *X86TargetLowering::
16619 LowerXConstraint(EVT ConstraintVT) const {
16620   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16621   // 'f' like normal targets.
16622   if (ConstraintVT.isFloatingPoint()) {
16623     if (Subtarget->hasSSE2())
16624       return "Y";
16625     if (Subtarget->hasSSE1())
16626       return "x";
16627   }
16628
16629   return TargetLowering::LowerXConstraint(ConstraintVT);
16630 }
16631
16632 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16633 /// vector.  If it is invalid, don't add anything to Ops.
16634 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16635                                                      std::string &Constraint,
16636                                                      std::vector<SDValue>&Ops,
16637                                                      SelectionDAG &DAG) const {
16638   SDValue Result(0, 0);
16639
16640   // Only support length 1 constraints for now.
16641   if (Constraint.length() > 1) return;
16642
16643   char ConstraintLetter = Constraint[0];
16644   switch (ConstraintLetter) {
16645   default: break;
16646   case 'I':
16647     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16648       if (C->getZExtValue() <= 31) {
16649         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16650         break;
16651       }
16652     }
16653     return;
16654   case 'J':
16655     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16656       if (C->getZExtValue() <= 63) {
16657         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16658         break;
16659       }
16660     }
16661     return;
16662   case 'K':
16663     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16664       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16665         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16666         break;
16667       }
16668     }
16669     return;
16670   case 'N':
16671     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16672       if (C->getZExtValue() <= 255) {
16673         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16674         break;
16675       }
16676     }
16677     return;
16678   case 'e': {
16679     // 32-bit signed value
16680     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16681       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16682                                            C->getSExtValue())) {
16683         // Widen to 64 bits here to get it sign extended.
16684         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16685         break;
16686       }
16687     // FIXME gcc accepts some relocatable values here too, but only in certain
16688     // memory models; it's complicated.
16689     }
16690     return;
16691   }
16692   case 'Z': {
16693     // 32-bit unsigned value
16694     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16695       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16696                                            C->getZExtValue())) {
16697         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16698         break;
16699       }
16700     }
16701     // FIXME gcc accepts some relocatable values here too, but only in certain
16702     // memory models; it's complicated.
16703     return;
16704   }
16705   case 'i': {
16706     // Literal immediates are always ok.
16707     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16708       // Widen to 64 bits here to get it sign extended.
16709       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16710       break;
16711     }
16712
16713     // In any sort of PIC mode addresses need to be computed at runtime by
16714     // adding in a register or some sort of table lookup.  These can't
16715     // be used as immediates.
16716     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16717       return;
16718
16719     // If we are in non-pic codegen mode, we allow the address of a global (with
16720     // an optional displacement) to be used with 'i'.
16721     GlobalAddressSDNode *GA = 0;
16722     int64_t Offset = 0;
16723
16724     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16725     while (1) {
16726       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16727         Offset += GA->getOffset();
16728         break;
16729       } else if (Op.getOpcode() == ISD::ADD) {
16730         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16731           Offset += C->getZExtValue();
16732           Op = Op.getOperand(0);
16733           continue;
16734         }
16735       } else if (Op.getOpcode() == ISD::SUB) {
16736         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16737           Offset += -C->getZExtValue();
16738           Op = Op.getOperand(0);
16739           continue;
16740         }
16741       }
16742
16743       // Otherwise, this isn't something we can handle, reject it.
16744       return;
16745     }
16746
16747     const GlobalValue *GV = GA->getGlobal();
16748     // If we require an extra load to get this address, as in PIC mode, we
16749     // can't accept it.
16750     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16751                                                         getTargetMachine())))
16752       return;
16753
16754     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16755                                         GA->getValueType(0), Offset);
16756     break;
16757   }
16758   }
16759
16760   if (Result.getNode()) {
16761     Ops.push_back(Result);
16762     return;
16763   }
16764   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16765 }
16766
16767 std::pair<unsigned, const TargetRegisterClass*>
16768 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16769                                                 EVT VT) const {
16770   // First, see if this is a constraint that directly corresponds to an LLVM
16771   // register class.
16772   if (Constraint.size() == 1) {
16773     // GCC Constraint Letters
16774     switch (Constraint[0]) {
16775     default: break;
16776       // TODO: Slight differences here in allocation order and leaving
16777       // RIP in the class. Do they matter any more here than they do
16778       // in the normal allocation?
16779     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16780       if (Subtarget->is64Bit()) {
16781         if (VT == MVT::i32 || VT == MVT::f32)
16782           return std::make_pair(0U, &X86::GR32RegClass);
16783         if (VT == MVT::i16)
16784           return std::make_pair(0U, &X86::GR16RegClass);
16785         if (VT == MVT::i8 || VT == MVT::i1)
16786           return std::make_pair(0U, &X86::GR8RegClass);
16787         if (VT == MVT::i64 || VT == MVT::f64)
16788           return std::make_pair(0U, &X86::GR64RegClass);
16789         break;
16790       }
16791       // 32-bit fallthrough
16792     case 'Q':   // Q_REGS
16793       if (VT == MVT::i32 || VT == MVT::f32)
16794         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16795       if (VT == MVT::i16)
16796         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16797       if (VT == MVT::i8 || VT == MVT::i1)
16798         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16799       if (VT == MVT::i64)
16800         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16801       break;
16802     case 'r':   // GENERAL_REGS
16803     case 'l':   // INDEX_REGS
16804       if (VT == MVT::i8 || VT == MVT::i1)
16805         return std::make_pair(0U, &X86::GR8RegClass);
16806       if (VT == MVT::i16)
16807         return std::make_pair(0U, &X86::GR16RegClass);
16808       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16809         return std::make_pair(0U, &X86::GR32RegClass);
16810       return std::make_pair(0U, &X86::GR64RegClass);
16811     case 'R':   // LEGACY_REGS
16812       if (VT == MVT::i8 || VT == MVT::i1)
16813         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16814       if (VT == MVT::i16)
16815         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16816       if (VT == MVT::i32 || !Subtarget->is64Bit())
16817         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16818       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16819     case 'f':  // FP Stack registers.
16820       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16821       // value to the correct fpstack register class.
16822       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16823         return std::make_pair(0U, &X86::RFP32RegClass);
16824       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16825         return std::make_pair(0U, &X86::RFP64RegClass);
16826       return std::make_pair(0U, &X86::RFP80RegClass);
16827     case 'y':   // MMX_REGS if MMX allowed.
16828       if (!Subtarget->hasMMX()) break;
16829       return std::make_pair(0U, &X86::VR64RegClass);
16830     case 'Y':   // SSE_REGS if SSE2 allowed
16831       if (!Subtarget->hasSSE2()) break;
16832       // FALL THROUGH.
16833     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16834       if (!Subtarget->hasSSE1()) break;
16835
16836       switch (VT.getSimpleVT().SimpleTy) {
16837       default: break;
16838       // Scalar SSE types.
16839       case MVT::f32:
16840       case MVT::i32:
16841         return std::make_pair(0U, &X86::FR32RegClass);
16842       case MVT::f64:
16843       case MVT::i64:
16844         return std::make_pair(0U, &X86::FR64RegClass);
16845       // Vector types.
16846       case MVT::v16i8:
16847       case MVT::v8i16:
16848       case MVT::v4i32:
16849       case MVT::v2i64:
16850       case MVT::v4f32:
16851       case MVT::v2f64:
16852         return std::make_pair(0U, &X86::VR128RegClass);
16853       // AVX types.
16854       case MVT::v32i8:
16855       case MVT::v16i16:
16856       case MVT::v8i32:
16857       case MVT::v4i64:
16858       case MVT::v8f32:
16859       case MVT::v4f64:
16860         return std::make_pair(0U, &X86::VR256RegClass);
16861       }
16862       break;
16863     }
16864   }
16865
16866   // Use the default implementation in TargetLowering to convert the register
16867   // constraint into a member of a register class.
16868   std::pair<unsigned, const TargetRegisterClass*> Res;
16869   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16870
16871   // Not found as a standard register?
16872   if (Res.second == 0) {
16873     // Map st(0) -> st(7) -> ST0
16874     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16875         tolower(Constraint[1]) == 's' &&
16876         tolower(Constraint[2]) == 't' &&
16877         Constraint[3] == '(' &&
16878         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16879         Constraint[5] == ')' &&
16880         Constraint[6] == '}') {
16881
16882       Res.first = X86::ST0+Constraint[4]-'0';
16883       Res.second = &X86::RFP80RegClass;
16884       return Res;
16885     }
16886
16887     // GCC allows "st(0)" to be called just plain "st".
16888     if (StringRef("{st}").equals_lower(Constraint)) {
16889       Res.first = X86::ST0;
16890       Res.second = &X86::RFP80RegClass;
16891       return Res;
16892     }
16893
16894     // flags -> EFLAGS
16895     if (StringRef("{flags}").equals_lower(Constraint)) {
16896       Res.first = X86::EFLAGS;
16897       Res.second = &X86::CCRRegClass;
16898       return Res;
16899     }
16900
16901     // 'A' means EAX + EDX.
16902     if (Constraint == "A") {
16903       Res.first = X86::EAX;
16904       Res.second = &X86::GR32_ADRegClass;
16905       return Res;
16906     }
16907     return Res;
16908   }
16909
16910   // Otherwise, check to see if this is a register class of the wrong value
16911   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16912   // turn into {ax},{dx}.
16913   if (Res.second->hasType(VT))
16914     return Res;   // Correct type already, nothing to do.
16915
16916   // All of the single-register GCC register classes map their values onto
16917   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16918   // really want an 8-bit or 32-bit register, map to the appropriate register
16919   // class and return the appropriate register.
16920   if (Res.second == &X86::GR16RegClass) {
16921     if (VT == MVT::i8) {
16922       unsigned DestReg = 0;
16923       switch (Res.first) {
16924       default: break;
16925       case X86::AX: DestReg = X86::AL; break;
16926       case X86::DX: DestReg = X86::DL; break;
16927       case X86::CX: DestReg = X86::CL; break;
16928       case X86::BX: DestReg = X86::BL; break;
16929       }
16930       if (DestReg) {
16931         Res.first = DestReg;
16932         Res.second = &X86::GR8RegClass;
16933       }
16934     } else if (VT == MVT::i32) {
16935       unsigned DestReg = 0;
16936       switch (Res.first) {
16937       default: break;
16938       case X86::AX: DestReg = X86::EAX; break;
16939       case X86::DX: DestReg = X86::EDX; break;
16940       case X86::CX: DestReg = X86::ECX; break;
16941       case X86::BX: DestReg = X86::EBX; break;
16942       case X86::SI: DestReg = X86::ESI; break;
16943       case X86::DI: DestReg = X86::EDI; break;
16944       case X86::BP: DestReg = X86::EBP; break;
16945       case X86::SP: DestReg = X86::ESP; break;
16946       }
16947       if (DestReg) {
16948         Res.first = DestReg;
16949         Res.second = &X86::GR32RegClass;
16950       }
16951     } else if (VT == MVT::i64) {
16952       unsigned DestReg = 0;
16953       switch (Res.first) {
16954       default: break;
16955       case X86::AX: DestReg = X86::RAX; break;
16956       case X86::DX: DestReg = X86::RDX; break;
16957       case X86::CX: DestReg = X86::RCX; break;
16958       case X86::BX: DestReg = X86::RBX; break;
16959       case X86::SI: DestReg = X86::RSI; break;
16960       case X86::DI: DestReg = X86::RDI; break;
16961       case X86::BP: DestReg = X86::RBP; break;
16962       case X86::SP: DestReg = X86::RSP; break;
16963       }
16964       if (DestReg) {
16965         Res.first = DestReg;
16966         Res.second = &X86::GR64RegClass;
16967       }
16968     }
16969   } else if (Res.second == &X86::FR32RegClass ||
16970              Res.second == &X86::FR64RegClass ||
16971              Res.second == &X86::VR128RegClass) {
16972     // Handle references to XMM physical registers that got mapped into the
16973     // wrong class.  This can happen with constraints like {xmm0} where the
16974     // target independent register mapper will just pick the first match it can
16975     // find, ignoring the required type.
16976
16977     if (VT == MVT::f32 || VT == MVT::i32)
16978       Res.second = &X86::FR32RegClass;
16979     else if (VT == MVT::f64 || VT == MVT::i64)
16980       Res.second = &X86::FR64RegClass;
16981     else if (X86::VR128RegClass.hasType(VT))
16982       Res.second = &X86::VR128RegClass;
16983     else if (X86::VR256RegClass.hasType(VT))
16984       Res.second = &X86::VR256RegClass;
16985   }
16986
16987   return Res;
16988 }