Lower BUILD_VECTOR to SHUFFLE + INSERT_VECTOR_ELT for X86
[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 = getDataLayout();
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     addBypassSlowDiv(32, 8);
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   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462   // support continuation, user-level threading, and etc.. As a result, no
463   // other SjLj exception interfaces are implemented and please don't build
464   // your own exception handling based on them.
465   // LLVM/Clang supports zero-cost DWARF exception handling.
466   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
468
469   // Darwin ABI issue.
470   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
471   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
472   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
473   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
474   if (Subtarget->is64Bit())
475     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
477   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
478   if (Subtarget->is64Bit()) {
479     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
480     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
481     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
482     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
483     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
484   }
485   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
487   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
488   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
489   if (Subtarget->is64Bit()) {
490     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
491     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
492     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
493   }
494
495   if (Subtarget->hasSSE1())
496     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
497
498   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
499   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
500
501   // On X86 and X86-64, atomic operations are lowered to locked instructions.
502   // Locked instructions, in turn, have implicit fence semantics (all memory
503   // operations are flushed before issuing the locked instruction, and they
504   // are not buffered), so we can fold away the common pattern of
505   // fence-atomic-fence.
506   setShouldFoldAtomicFences(true);
507
508   // Expand certain atomics
509   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510     MVT VT = IntVTs[i];
511     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
514   }
515
516   if (!Subtarget->is64Bit()) {
517     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
529   }
530
531   if (Subtarget->hasCmpxchg16b()) {
532     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
533   }
534
535   // FIXME - use subtarget debug flags
536   if (!Subtarget->isTargetDarwin() &&
537       !Subtarget->isTargetELF() &&
538       !Subtarget->isTargetCygMing()) {
539     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
540   }
541
542   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
544   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
546   if (Subtarget->is64Bit()) {
547     setExceptionPointerRegister(X86::RAX);
548     setExceptionSelectorRegister(X86::RDX);
549   } else {
550     setExceptionPointerRegister(X86::EAX);
551     setExceptionSelectorRegister(X86::EDX);
552   }
553   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555
556   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558
559   setOperationAction(ISD::TRAP, MVT::Other, Legal);
560
561   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
563   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
564   if (Subtarget->is64Bit()) {
565     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
566     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
567   } else {
568     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
569     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
570   }
571
572   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
573   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
574
575   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577                        MVT::i64 : MVT::i32, Custom);
578   else if (TM.Options.EnableSegmentedStacks)
579     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580                        MVT::i64 : MVT::i32, Custom);
581   else
582     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583                        MVT::i64 : MVT::i32, Expand);
584
585   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586     // f32 and f64 use SSE.
587     // Set up the FP register classes.
588     addRegisterClass(MVT::f32, &X86::FR32RegClass);
589     addRegisterClass(MVT::f64, &X86::FR64RegClass);
590
591     // Use ANDPD to simulate FABS.
592     setOperationAction(ISD::FABS , MVT::f64, Custom);
593     setOperationAction(ISD::FABS , MVT::f32, Custom);
594
595     // Use XORP to simulate FNEG.
596     setOperationAction(ISD::FNEG , MVT::f64, Custom);
597     setOperationAction(ISD::FNEG , MVT::f32, Custom);
598
599     // Use ANDPD and ORPD to simulate FCOPYSIGN.
600     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
602
603     // Lower this to FGETSIGNx86 plus an AND.
604     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
606
607     // We don't support sin/cos/fmod
608     setOperationAction(ISD::FSIN , MVT::f64, Expand);
609     setOperationAction(ISD::FCOS , MVT::f64, Expand);
610     setOperationAction(ISD::FSIN , MVT::f32, Expand);
611     setOperationAction(ISD::FCOS , MVT::f32, Expand);
612
613     // Expand FP immediates into loads from the stack, except for the special
614     // cases we handle.
615     addLegalFPImmediate(APFloat(+0.0)); // xorpd
616     addLegalFPImmediate(APFloat(+0.0f)); // xorps
617   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618     // Use SSE for f32, x87 for f64.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
622
623     // Use ANDPS to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f32, Custom);
625
626     // Use XORP to simulate FNEG.
627     setOperationAction(ISD::FNEG , MVT::f32, Custom);
628
629     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
630
631     // Use ANDPS and ORPS to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // We don't support sin/cos/fmod
636     setOperationAction(ISD::FSIN , MVT::f32, Expand);
637     setOperationAction(ISD::FCOS , MVT::f32, Expand);
638
639     // Special cases we handle for FP constants.
640     addLegalFPImmediate(APFloat(+0.0f)); // xorps
641     addLegalFPImmediate(APFloat(+0.0)); // FLD0
642     addLegalFPImmediate(APFloat(+1.0)); // FLD1
643     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
645
646     if (!TM.Options.UnsafeFPMath) {
647       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
648       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
649     }
650   } else if (!TM.Options.UseSoftFloat) {
651     // f32 and f64 in x87.
652     // Set up the FP register classes.
653     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
655
656     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
657     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
660
661     if (!TM.Options.UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
663       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
666     }
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
675   }
676
677   // We don't support FMA.
678   setOperationAction(ISD::FMA, MVT::f64, Expand);
679   setOperationAction(ISD::FMA, MVT::f32, Expand);
680
681   // Long double always uses X87.
682   if (!TM.Options.UseSoftFloat) {
683     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
686     {
687       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688       addLegalFPImmediate(TmpFlt);  // FLD0
689       TmpFlt.changeSign();
690       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
691
692       bool ignored;
693       APFloat TmpFlt2(+1.0);
694       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
695                       &ignored);
696       addLegalFPImmediate(TmpFlt2);  // FLD1
697       TmpFlt2.changeSign();
698       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
699     }
700
701     if (!TM.Options.UnsafeFPMath) {
702       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
703       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
704     }
705
706     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
708     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
710     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711     setOperationAction(ISD::FMA, MVT::f80, Expand);
712   }
713
714   // Always use a library call for pow.
715   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
716   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
718
719   setOperationAction(ISD::FLOG, MVT::f80, Expand);
720   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722   setOperationAction(ISD::FEXP, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724
725   // First set operation action for all vector types to either promote
726   // (for widening) or expand (for scalarization). Then we will selectively
727   // turn on ones that can be effectively codegen'd.
728   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
729            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
730     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
745     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
747     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
784     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
785     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
789     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
790              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
791       setTruncStoreAction((MVT::SimpleValueType)VT,
792                           (MVT::SimpleValueType)InnerVT, Expand);
793     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
794     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
796   }
797
798   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
799   // with -msoft-float, disable use of MMX as well.
800   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
801     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
802     // No operations on x86mmx supported, everything uses intrinsics.
803   }
804
805   // MMX-sized vectors (other than x86mmx) are expected to be expanded
806   // into smaller operations.
807   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
808   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
809   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
811   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
812   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
813   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
814   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
815   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
816   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
817   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
818   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
819   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
820   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
821   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
822   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
823   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
827   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
828   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
829   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
830   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
832   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
836
837   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
838     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
839
840     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
846     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
847     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
848     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
849     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
850     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
852   }
853
854   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
855     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
856
857     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
858     // registers cannot be used even for integer operations.
859     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
860     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
861     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
862     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
863
864     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
865     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
866     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
867     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
868     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
869     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
870     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
871     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
872     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
873     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
874     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
875     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
879     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
880     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
881
882     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
883     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
886
887     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
892
893     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
894     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895       MVT VT = (MVT::SimpleValueType)i;
896       // Do not attempt to custom lower non-power-of-2 vectors
897       if (!isPowerOf2_32(VT.getVectorNumElements()))
898         continue;
899       // Do not attempt to custom lower non-128-bit vectors
900       if (!VT.is128BitVector())
901         continue;
902       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
903       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
904       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
905     }
906
907     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
909     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
912     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
913
914     if (Subtarget->is64Bit()) {
915       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
916       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
917     }
918
919     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
920     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
921       MVT VT = (MVT::SimpleValueType)i;
922
923       // Do not attempt to promote non-128-bit vectors
924       if (!VT.is128BitVector())
925         continue;
926
927       setOperationAction(ISD::AND,    VT, Promote);
928       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
929       setOperationAction(ISD::OR,     VT, Promote);
930       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
931       setOperationAction(ISD::XOR,    VT, Promote);
932       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
933       setOperationAction(ISD::LOAD,   VT, Promote);
934       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
935       setOperationAction(ISD::SELECT, VT, Promote);
936       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
937     }
938
939     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
940
941     // Custom lower v2i64 and v2f64 selects.
942     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
943     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
944     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
945     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
946
947     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
948     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
949
950     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
951     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
952
953     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
954   }
955
956   if (Subtarget->hasSSE41()) {
957     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
958     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
959     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
960     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
961     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
962     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
963     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
964     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
965     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
966     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
967
968     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
969     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
970
971     // FIXME: Do we need to handle scalar-to-vector here?
972     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
973
974     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
975     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
976     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
977     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
978     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
979
980     // i8 and i16 vectors are custom , because the source register and source
981     // source memory operand types are not the same width.  f32 vectors are
982     // custom since the immediate controlling the insert encodes additional
983     // information.
984     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
988
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
993
994     // FIXME: these should be Legal but thats only for the case where
995     // the index is constant.  For now custom expand to deal with that.
996     if (Subtarget->is64Bit()) {
997       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
998       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
999     }
1000   }
1001
1002   if (Subtarget->hasSSE2()) {
1003     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1004     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1005
1006     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1007     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1008
1009     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1010     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1011
1012     if (Subtarget->hasAVX2()) {
1013       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1014       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1015
1016       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1017       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1018
1019       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1020     } else {
1021       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1022       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1023
1024       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1025       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1026
1027       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1028     }
1029   }
1030
1031   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1032     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1033     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1038
1039     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1040     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1042
1043     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1048     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1049     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1050     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1051
1052     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1053     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1058     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1059     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1060
1061     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1062
1063     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1064
1065     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1066     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1067     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1068
1069     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1070
1071     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1072     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1073
1074     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1075     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1076
1077     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1078     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1079
1080     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1081     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1083     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1084
1085     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1086     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1087     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1088
1089     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1090     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1091     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1092     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1093
1094     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1095       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1096       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1097       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1098       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1099       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1100       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1101     }
1102
1103     if (Subtarget->hasAVX2()) {
1104       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1105       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1106       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1107       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1108
1109       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1110       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1111       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1112       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1113
1114       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1116       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1117       // Don't lower v32i8 because there is no 128-bit byte mul
1118
1119       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1120
1121       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1122       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1123
1124       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1125       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1126
1127       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1128     } else {
1129       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1130       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1131       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1132       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1133
1134       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1135       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1136       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1137       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1138
1139       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1140       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1141       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1142       // Don't lower v32i8 because there is no 128-bit byte mul
1143
1144       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1145       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1146
1147       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1148       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1149
1150       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1151     }
1152
1153     // Custom lower several nodes for 256-bit types.
1154     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1155              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1156       MVT VT = (MVT::SimpleValueType)i;
1157
1158       // Extract subvector is special because the value type
1159       // (result) is 128-bit but the source is 256-bit wide.
1160       if (VT.is128BitVector())
1161         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1162
1163       // Do not attempt to custom lower other non-256-bit vectors
1164       if (!VT.is256BitVector())
1165         continue;
1166
1167       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1168       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1169       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1170       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1171       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1172       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1173       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1174     }
1175
1176     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1177     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1178       MVT VT = (MVT::SimpleValueType)i;
1179
1180       // Do not attempt to promote non-256-bit vectors
1181       if (!VT.is256BitVector())
1182         continue;
1183
1184       setOperationAction(ISD::AND,    VT, Promote);
1185       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1186       setOperationAction(ISD::OR,     VT, Promote);
1187       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1188       setOperationAction(ISD::XOR,    VT, Promote);
1189       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1190       setOperationAction(ISD::LOAD,   VT, Promote);
1191       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1192       setOperationAction(ISD::SELECT, VT, Promote);
1193       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1194     }
1195   }
1196
1197   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1198   // of this type with custom code.
1199   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1200            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1201     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1202                        Custom);
1203   }
1204
1205   // We want to custom lower some of our intrinsics.
1206   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1207   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1208
1209
1210   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1211   // handle type legalization for these operations here.
1212   //
1213   // FIXME: We really should do custom legalization for addition and
1214   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1215   // than generic legalization for 64-bit multiplication-with-overflow, though.
1216   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1217     // Add/Sub/Mul with overflow operations are custom lowered.
1218     MVT VT = IntVTs[i];
1219     setOperationAction(ISD::SADDO, VT, Custom);
1220     setOperationAction(ISD::UADDO, VT, Custom);
1221     setOperationAction(ISD::SSUBO, VT, Custom);
1222     setOperationAction(ISD::USUBO, VT, Custom);
1223     setOperationAction(ISD::SMULO, VT, Custom);
1224     setOperationAction(ISD::UMULO, VT, Custom);
1225   }
1226
1227   // There are no 8-bit 3-address imul/mul instructions
1228   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1229   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1230
1231   if (!Subtarget->is64Bit()) {
1232     // These libcalls are not available in 32-bit.
1233     setLibcallName(RTLIB::SHL_I128, 0);
1234     setLibcallName(RTLIB::SRL_I128, 0);
1235     setLibcallName(RTLIB::SRA_I128, 0);
1236   }
1237
1238   // We have target-specific dag combine patterns for the following nodes:
1239   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1240   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1241   setTargetDAGCombine(ISD::VSELECT);
1242   setTargetDAGCombine(ISD::SELECT);
1243   setTargetDAGCombine(ISD::SHL);
1244   setTargetDAGCombine(ISD::SRA);
1245   setTargetDAGCombine(ISD::SRL);
1246   setTargetDAGCombine(ISD::OR);
1247   setTargetDAGCombine(ISD::AND);
1248   setTargetDAGCombine(ISD::ADD);
1249   setTargetDAGCombine(ISD::FADD);
1250   setTargetDAGCombine(ISD::FSUB);
1251   setTargetDAGCombine(ISD::FMA);
1252   setTargetDAGCombine(ISD::SUB);
1253   setTargetDAGCombine(ISD::LOAD);
1254   setTargetDAGCombine(ISD::STORE);
1255   setTargetDAGCombine(ISD::ZERO_EXTEND);
1256   setTargetDAGCombine(ISD::ANY_EXTEND);
1257   setTargetDAGCombine(ISD::SIGN_EXTEND);
1258   setTargetDAGCombine(ISD::TRUNCATE);
1259   setTargetDAGCombine(ISD::UINT_TO_FP);
1260   setTargetDAGCombine(ISD::SINT_TO_FP);
1261   setTargetDAGCombine(ISD::SETCC);
1262   if (Subtarget->is64Bit())
1263     setTargetDAGCombine(ISD::MUL);
1264   setTargetDAGCombine(ISD::XOR);
1265
1266   computeRegisterProperties();
1267
1268   // On Darwin, -Os means optimize for size without hurting performance,
1269   // do not reduce the limit.
1270   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1271   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1272   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1273   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1274   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1275   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1276   setPrefLoopAlignment(4); // 2^4 bytes.
1277   benefitFromCodePlacementOpt = true;
1278
1279   // Predictable cmov don't hurt on atom because it's in-order.
1280   predictableSelectIsExpensive = !Subtarget->isAtom();
1281
1282   setPrefFunctionAlignment(4); // 2^4 bytes.
1283 }
1284
1285
1286 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1287   if (!VT.isVector()) return MVT::i8;
1288   return VT.changeVectorElementTypeToInteger();
1289 }
1290
1291
1292 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1293 /// the desired ByVal argument alignment.
1294 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1295   if (MaxAlign == 16)
1296     return;
1297   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1298     if (VTy->getBitWidth() == 128)
1299       MaxAlign = 16;
1300   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1301     unsigned EltAlign = 0;
1302     getMaxByValAlign(ATy->getElementType(), EltAlign);
1303     if (EltAlign > MaxAlign)
1304       MaxAlign = EltAlign;
1305   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1306     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1307       unsigned EltAlign = 0;
1308       getMaxByValAlign(STy->getElementType(i), EltAlign);
1309       if (EltAlign > MaxAlign)
1310         MaxAlign = EltAlign;
1311       if (MaxAlign == 16)
1312         break;
1313     }
1314   }
1315 }
1316
1317 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1318 /// function arguments in the caller parameter area. For X86, aggregates
1319 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1320 /// are at 4-byte boundaries.
1321 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1322   if (Subtarget->is64Bit()) {
1323     // Max of 8 and alignment of type.
1324     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1325     if (TyAlign > 8)
1326       return TyAlign;
1327     return 8;
1328   }
1329
1330   unsigned Align = 4;
1331   if (Subtarget->hasSSE1())
1332     getMaxByValAlign(Ty, Align);
1333   return Align;
1334 }
1335
1336 /// getOptimalMemOpType - Returns the target specific optimal type for load
1337 /// and store operations as a result of memset, memcpy, and memmove
1338 /// lowering. If DstAlign is zero that means it's safe to destination
1339 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1340 /// means there isn't a need to check it against alignment requirement,
1341 /// probably because the source does not need to be loaded. If
1342 /// 'IsZeroVal' is true, that means it's safe to return a
1343 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1344 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1345 /// constant so it does not need to be loaded.
1346 /// It returns EVT::Other if the type should be determined using generic
1347 /// target-independent logic.
1348 EVT
1349 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1350                                        unsigned DstAlign, unsigned SrcAlign,
1351                                        bool IsZeroVal,
1352                                        bool MemcpyStrSrc,
1353                                        MachineFunction &MF) const {
1354   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1355   // linux.  This is because the stack realignment code can't handle certain
1356   // cases like PR2962.  This should be removed when PR2962 is fixed.
1357   const Function *F = MF.getFunction();
1358   if (IsZeroVal &&
1359       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1360     if (Size >= 16 &&
1361         (Subtarget->isUnalignedMemAccessFast() ||
1362          ((DstAlign == 0 || DstAlign >= 16) &&
1363           (SrcAlign == 0 || SrcAlign >= 16))) &&
1364         Subtarget->getStackAlignment() >= 16) {
1365       if (Subtarget->getStackAlignment() >= 32) {
1366         if (Subtarget->hasAVX2())
1367           return MVT::v8i32;
1368         if (Subtarget->hasAVX())
1369           return MVT::v8f32;
1370       }
1371       if (Subtarget->hasSSE2())
1372         return MVT::v4i32;
1373       if (Subtarget->hasSSE1())
1374         return MVT::v4f32;
1375     } else if (!MemcpyStrSrc && Size >= 8 &&
1376                !Subtarget->is64Bit() &&
1377                Subtarget->getStackAlignment() >= 8 &&
1378                Subtarget->hasSSE2()) {
1379       // Do not use f64 to lower memcpy if source is string constant. It's
1380       // better to use i32 to avoid the loads.
1381       return MVT::f64;
1382     }
1383   }
1384   if (Subtarget->is64Bit() && Size >= 8)
1385     return MVT::i64;
1386   return MVT::i32;
1387 }
1388
1389 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1390 /// current function.  The returned value is a member of the
1391 /// MachineJumpTableInfo::JTEntryKind enum.
1392 unsigned X86TargetLowering::getJumpTableEncoding() const {
1393   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1394   // symbol.
1395   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1396       Subtarget->isPICStyleGOT())
1397     return MachineJumpTableInfo::EK_Custom32;
1398
1399   // Otherwise, use the normal jump table encoding heuristics.
1400   return TargetLowering::getJumpTableEncoding();
1401 }
1402
1403 const MCExpr *
1404 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1405                                              const MachineBasicBlock *MBB,
1406                                              unsigned uid,MCContext &Ctx) const{
1407   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1408          Subtarget->isPICStyleGOT());
1409   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1410   // entries.
1411   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1412                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1413 }
1414
1415 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1416 /// jumptable.
1417 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1418                                                     SelectionDAG &DAG) const {
1419   if (!Subtarget->is64Bit())
1420     // This doesn't have DebugLoc associated with it, but is not really the
1421     // same as a Register.
1422     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1423   return Table;
1424 }
1425
1426 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1427 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1428 /// MCExpr.
1429 const MCExpr *X86TargetLowering::
1430 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1431                              MCContext &Ctx) const {
1432   // X86-64 uses RIP relative addressing based on the jump table label.
1433   if (Subtarget->isPICStyleRIPRel())
1434     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1435
1436   // Otherwise, the reference is relative to the PIC base.
1437   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1438 }
1439
1440 // FIXME: Why this routine is here? Move to RegInfo!
1441 std::pair<const TargetRegisterClass*, uint8_t>
1442 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1443   const TargetRegisterClass *RRC = 0;
1444   uint8_t Cost = 1;
1445   switch (VT.getSimpleVT().SimpleTy) {
1446   default:
1447     return TargetLowering::findRepresentativeClass(VT);
1448   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1449     RRC = Subtarget->is64Bit() ?
1450       (const TargetRegisterClass*)&X86::GR64RegClass :
1451       (const TargetRegisterClass*)&X86::GR32RegClass;
1452     break;
1453   case MVT::x86mmx:
1454     RRC = &X86::VR64RegClass;
1455     break;
1456   case MVT::f32: case MVT::f64:
1457   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1458   case MVT::v4f32: case MVT::v2f64:
1459   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1460   case MVT::v4f64:
1461     RRC = &X86::VR128RegClass;
1462     break;
1463   }
1464   return std::make_pair(RRC, Cost);
1465 }
1466
1467 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1468                                                unsigned &Offset) const {
1469   if (!Subtarget->isTargetLinux())
1470     return false;
1471
1472   if (Subtarget->is64Bit()) {
1473     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1474     Offset = 0x28;
1475     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1476       AddressSpace = 256;
1477     else
1478       AddressSpace = 257;
1479   } else {
1480     // %gs:0x14 on i386
1481     Offset = 0x14;
1482     AddressSpace = 256;
1483   }
1484   return true;
1485 }
1486
1487
1488 //===----------------------------------------------------------------------===//
1489 //               Return Value Calling Convention Implementation
1490 //===----------------------------------------------------------------------===//
1491
1492 #include "X86GenCallingConv.inc"
1493
1494 bool
1495 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1496                                   MachineFunction &MF, bool isVarArg,
1497                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1498                         LLVMContext &Context) const {
1499   SmallVector<CCValAssign, 16> RVLocs;
1500   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1501                  RVLocs, Context);
1502   return CCInfo.CheckReturn(Outs, RetCC_X86);
1503 }
1504
1505 SDValue
1506 X86TargetLowering::LowerReturn(SDValue Chain,
1507                                CallingConv::ID CallConv, bool isVarArg,
1508                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1509                                const SmallVectorImpl<SDValue> &OutVals,
1510                                DebugLoc dl, SelectionDAG &DAG) const {
1511   MachineFunction &MF = DAG.getMachineFunction();
1512   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1513
1514   SmallVector<CCValAssign, 16> RVLocs;
1515   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1516                  RVLocs, *DAG.getContext());
1517   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1518
1519   // Add the regs to the liveout set for the function.
1520   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1521   for (unsigned i = 0; i != RVLocs.size(); ++i)
1522     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1523       MRI.addLiveOut(RVLocs[i].getLocReg());
1524
1525   SDValue Flag;
1526
1527   SmallVector<SDValue, 6> RetOps;
1528   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1529   // Operand #1 = Bytes To Pop
1530   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1531                    MVT::i16));
1532
1533   // Copy the result values into the output registers.
1534   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1535     CCValAssign &VA = RVLocs[i];
1536     assert(VA.isRegLoc() && "Can only return in registers!");
1537     SDValue ValToCopy = OutVals[i];
1538     EVT ValVT = ValToCopy.getValueType();
1539
1540     // Promote values to the appropriate types
1541     if (VA.getLocInfo() == CCValAssign::SExt)
1542       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1543     else if (VA.getLocInfo() == CCValAssign::ZExt)
1544       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1545     else if (VA.getLocInfo() == CCValAssign::AExt)
1546       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1547     else if (VA.getLocInfo() == CCValAssign::BCvt)
1548       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1549
1550     // If this is x86-64, and we disabled SSE, we can't return FP values,
1551     // or SSE or MMX vectors.
1552     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1553          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1554           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1555       report_fatal_error("SSE register return with SSE disabled");
1556     }
1557     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1558     // llvm-gcc has never done it right and no one has noticed, so this
1559     // should be OK for now.
1560     if (ValVT == MVT::f64 &&
1561         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1562       report_fatal_error("SSE2 register return with SSE2 disabled");
1563
1564     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1565     // the RET instruction and handled by the FP Stackifier.
1566     if (VA.getLocReg() == X86::ST0 ||
1567         VA.getLocReg() == X86::ST1) {
1568       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1569       // change the value to the FP stack register class.
1570       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1571         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1572       RetOps.push_back(ValToCopy);
1573       // Don't emit a copytoreg.
1574       continue;
1575     }
1576
1577     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1578     // which is returned in RAX / RDX.
1579     if (Subtarget->is64Bit()) {
1580       if (ValVT == MVT::x86mmx) {
1581         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1582           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1583           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1584                                   ValToCopy);
1585           // If we don't have SSE2 available, convert to v4f32 so the generated
1586           // register is legal.
1587           if (!Subtarget->hasSSE2())
1588             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1589         }
1590       }
1591     }
1592
1593     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1594     Flag = Chain.getValue(1);
1595   }
1596
1597   // The x86-64 ABI for returning structs by value requires that we copy
1598   // the sret argument into %rax for the return. We saved the argument into
1599   // a virtual register in the entry block, so now we copy the value out
1600   // and into %rax.
1601   if (Subtarget->is64Bit() &&
1602       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1603     MachineFunction &MF = DAG.getMachineFunction();
1604     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1605     unsigned Reg = FuncInfo->getSRetReturnReg();
1606     assert(Reg &&
1607            "SRetReturnReg should have been set in LowerFormalArguments().");
1608     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1609
1610     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1611     Flag = Chain.getValue(1);
1612
1613     // RAX now acts like a return value.
1614     MRI.addLiveOut(X86::RAX);
1615   }
1616
1617   RetOps[0] = Chain;  // Update chain.
1618
1619   // Add the flag if we have it.
1620   if (Flag.getNode())
1621     RetOps.push_back(Flag);
1622
1623   return DAG.getNode(X86ISD::RET_FLAG, dl,
1624                      MVT::Other, &RetOps[0], RetOps.size());
1625 }
1626
1627 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1628   if (N->getNumValues() != 1)
1629     return false;
1630   if (!N->hasNUsesOfValue(1, 0))
1631     return false;
1632
1633   SDValue TCChain = Chain;
1634   SDNode *Copy = *N->use_begin();
1635   if (Copy->getOpcode() == ISD::CopyToReg) {
1636     // If the copy has a glue operand, we conservatively assume it isn't safe to
1637     // perform a tail call.
1638     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1639       return false;
1640     TCChain = Copy->getOperand(0);
1641   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1642     return false;
1643
1644   bool HasRet = false;
1645   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1646        UI != UE; ++UI) {
1647     if (UI->getOpcode() != X86ISD::RET_FLAG)
1648       return false;
1649     HasRet = true;
1650   }
1651
1652   if (!HasRet)
1653     return false;
1654
1655   Chain = TCChain;
1656   return true;
1657 }
1658
1659 EVT
1660 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1661                                             ISD::NodeType ExtendKind) const {
1662   MVT ReturnMVT;
1663   // TODO: Is this also valid on 32-bit?
1664   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1665     ReturnMVT = MVT::i8;
1666   else
1667     ReturnMVT = MVT::i32;
1668
1669   EVT MinVT = getRegisterType(Context, ReturnMVT);
1670   return VT.bitsLT(MinVT) ? MinVT : VT;
1671 }
1672
1673 /// LowerCallResult - Lower the result values of a call into the
1674 /// appropriate copies out of appropriate physical registers.
1675 ///
1676 SDValue
1677 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1678                                    CallingConv::ID CallConv, bool isVarArg,
1679                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1680                                    DebugLoc dl, SelectionDAG &DAG,
1681                                    SmallVectorImpl<SDValue> &InVals) const {
1682
1683   // Assign locations to each value returned by this call.
1684   SmallVector<CCValAssign, 16> RVLocs;
1685   bool Is64Bit = Subtarget->is64Bit();
1686   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1687                  getTargetMachine(), RVLocs, *DAG.getContext());
1688   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1689
1690   // Copy all of the result registers out of their specified physreg.
1691   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1692     CCValAssign &VA = RVLocs[i];
1693     EVT CopyVT = VA.getValVT();
1694
1695     // If this is x86-64, and we disabled SSE, we can't return FP values
1696     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1697         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1698       report_fatal_error("SSE register return with SSE disabled");
1699     }
1700
1701     SDValue Val;
1702
1703     // If this is a call to a function that returns an fp value on the floating
1704     // point stack, we must guarantee the value is popped from the stack, so
1705     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1706     // if the return value is not used. We use the FpPOP_RETVAL instruction
1707     // instead.
1708     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1709       // If we prefer to use the value in xmm registers, copy it out as f80 and
1710       // use a truncate to move it from fp stack reg to xmm reg.
1711       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1712       SDValue Ops[] = { Chain, InFlag };
1713       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1714                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1715       Val = Chain.getValue(0);
1716
1717       // Round the f80 to the right size, which also moves it to the appropriate
1718       // xmm register.
1719       if (CopyVT != VA.getValVT())
1720         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1721                           // This truncation won't change the value.
1722                           DAG.getIntPtrConstant(1));
1723     } else {
1724       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1725                                  CopyVT, InFlag).getValue(1);
1726       Val = Chain.getValue(0);
1727     }
1728     InFlag = Chain.getValue(2);
1729     InVals.push_back(Val);
1730   }
1731
1732   return Chain;
1733 }
1734
1735
1736 //===----------------------------------------------------------------------===//
1737 //                C & StdCall & Fast Calling Convention implementation
1738 //===----------------------------------------------------------------------===//
1739 //  StdCall calling convention seems to be standard for many Windows' API
1740 //  routines and around. It differs from C calling convention just a little:
1741 //  callee should clean up the stack, not caller. Symbols should be also
1742 //  decorated in some fancy way :) It doesn't support any vector arguments.
1743 //  For info on fast calling convention see Fast Calling Convention (tail call)
1744 //  implementation LowerX86_32FastCCCallTo.
1745
1746 /// CallIsStructReturn - Determines whether a call uses struct return
1747 /// semantics.
1748 enum StructReturnType {
1749   NotStructReturn,
1750   RegStructReturn,
1751   StackStructReturn
1752 };
1753 static StructReturnType
1754 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1755   if (Outs.empty())
1756     return NotStructReturn;
1757
1758   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1759   if (!Flags.isSRet())
1760     return NotStructReturn;
1761   if (Flags.isInReg())
1762     return RegStructReturn;
1763   return StackStructReturn;
1764 }
1765
1766 /// ArgsAreStructReturn - Determines whether a function uses struct
1767 /// return semantics.
1768 static StructReturnType
1769 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1770   if (Ins.empty())
1771     return NotStructReturn;
1772
1773   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1774   if (!Flags.isSRet())
1775     return NotStructReturn;
1776   if (Flags.isInReg())
1777     return RegStructReturn;
1778   return StackStructReturn;
1779 }
1780
1781 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1782 /// by "Src" to address "Dst" with size and alignment information specified by
1783 /// the specific parameter attribute. The copy will be passed as a byval
1784 /// function parameter.
1785 static SDValue
1786 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1787                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1788                           DebugLoc dl) {
1789   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1790
1791   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1792                        /*isVolatile*/false, /*AlwaysInline=*/true,
1793                        MachinePointerInfo(), MachinePointerInfo());
1794 }
1795
1796 /// IsTailCallConvention - Return true if the calling convention is one that
1797 /// supports tail call optimization.
1798 static bool IsTailCallConvention(CallingConv::ID CC) {
1799   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1800 }
1801
1802 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1803   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1804     return false;
1805
1806   CallSite CS(CI);
1807   CallingConv::ID CalleeCC = CS.getCallingConv();
1808   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1809     return false;
1810
1811   return true;
1812 }
1813
1814 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1815 /// a tailcall target by changing its ABI.
1816 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1817                                    bool GuaranteedTailCallOpt) {
1818   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1819 }
1820
1821 SDValue
1822 X86TargetLowering::LowerMemArgument(SDValue Chain,
1823                                     CallingConv::ID CallConv,
1824                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1825                                     DebugLoc dl, SelectionDAG &DAG,
1826                                     const CCValAssign &VA,
1827                                     MachineFrameInfo *MFI,
1828                                     unsigned i) const {
1829   // Create the nodes corresponding to a load from this parameter slot.
1830   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1831   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1832                               getTargetMachine().Options.GuaranteedTailCallOpt);
1833   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1834   EVT ValVT;
1835
1836   // If value is passed by pointer we have address passed instead of the value
1837   // itself.
1838   if (VA.getLocInfo() == CCValAssign::Indirect)
1839     ValVT = VA.getLocVT();
1840   else
1841     ValVT = VA.getValVT();
1842
1843   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1844   // changed with more analysis.
1845   // In case of tail call optimization mark all arguments mutable. Since they
1846   // could be overwritten by lowering of arguments in case of a tail call.
1847   if (Flags.isByVal()) {
1848     unsigned Bytes = Flags.getByValSize();
1849     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1850     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1851     return DAG.getFrameIndex(FI, getPointerTy());
1852   } else {
1853     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1854                                     VA.getLocMemOffset(), isImmutable);
1855     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1856     return DAG.getLoad(ValVT, dl, Chain, FIN,
1857                        MachinePointerInfo::getFixedStack(FI),
1858                        false, false, false, 0);
1859   }
1860 }
1861
1862 SDValue
1863 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1864                                         CallingConv::ID CallConv,
1865                                         bool isVarArg,
1866                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1867                                         DebugLoc dl,
1868                                         SelectionDAG &DAG,
1869                                         SmallVectorImpl<SDValue> &InVals)
1870                                           const {
1871   MachineFunction &MF = DAG.getMachineFunction();
1872   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1873
1874   const Function* Fn = MF.getFunction();
1875   if (Fn->hasExternalLinkage() &&
1876       Subtarget->isTargetCygMing() &&
1877       Fn->getName() == "main")
1878     FuncInfo->setForceFramePointer(true);
1879
1880   MachineFrameInfo *MFI = MF.getFrameInfo();
1881   bool Is64Bit = Subtarget->is64Bit();
1882   bool IsWindows = Subtarget->isTargetWindows();
1883   bool IsWin64 = Subtarget->isTargetWin64();
1884
1885   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1886          "Var args not supported with calling convention fastcc or ghc");
1887
1888   // Assign locations to all of the incoming arguments.
1889   SmallVector<CCValAssign, 16> ArgLocs;
1890   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1891                  ArgLocs, *DAG.getContext());
1892
1893   // Allocate shadow area for Win64
1894   if (IsWin64) {
1895     CCInfo.AllocateStack(32, 8);
1896   }
1897
1898   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1899
1900   unsigned LastVal = ~0U;
1901   SDValue ArgValue;
1902   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1903     CCValAssign &VA = ArgLocs[i];
1904     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1905     // places.
1906     assert(VA.getValNo() != LastVal &&
1907            "Don't support value assigned to multiple locs yet");
1908     (void)LastVal;
1909     LastVal = VA.getValNo();
1910
1911     if (VA.isRegLoc()) {
1912       EVT RegVT = VA.getLocVT();
1913       const TargetRegisterClass *RC;
1914       if (RegVT == MVT::i32)
1915         RC = &X86::GR32RegClass;
1916       else if (Is64Bit && RegVT == MVT::i64)
1917         RC = &X86::GR64RegClass;
1918       else if (RegVT == MVT::f32)
1919         RC = &X86::FR32RegClass;
1920       else if (RegVT == MVT::f64)
1921         RC = &X86::FR64RegClass;
1922       else if (RegVT.is256BitVector())
1923         RC = &X86::VR256RegClass;
1924       else if (RegVT.is128BitVector())
1925         RC = &X86::VR128RegClass;
1926       else if (RegVT == MVT::x86mmx)
1927         RC = &X86::VR64RegClass;
1928       else
1929         llvm_unreachable("Unknown argument type!");
1930
1931       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1932       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1933
1934       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1935       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1936       // right size.
1937       if (VA.getLocInfo() == CCValAssign::SExt)
1938         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1939                                DAG.getValueType(VA.getValVT()));
1940       else if (VA.getLocInfo() == CCValAssign::ZExt)
1941         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1942                                DAG.getValueType(VA.getValVT()));
1943       else if (VA.getLocInfo() == CCValAssign::BCvt)
1944         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1945
1946       if (VA.isExtInLoc()) {
1947         // Handle MMX values passed in XMM regs.
1948         if (RegVT.isVector()) {
1949           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1950                                  ArgValue);
1951         } else
1952           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1953       }
1954     } else {
1955       assert(VA.isMemLoc());
1956       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1957     }
1958
1959     // If value is passed via pointer - do a load.
1960     if (VA.getLocInfo() == CCValAssign::Indirect)
1961       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1962                              MachinePointerInfo(), false, false, false, 0);
1963
1964     InVals.push_back(ArgValue);
1965   }
1966
1967   // The x86-64 ABI for returning structs by value requires that we copy
1968   // the sret argument into %rax for the return. Save the argument into
1969   // a virtual register so that we can access it from the return points.
1970   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1971     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1972     unsigned Reg = FuncInfo->getSRetReturnReg();
1973     if (!Reg) {
1974       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1975       FuncInfo->setSRetReturnReg(Reg);
1976     }
1977     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1978     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1979   }
1980
1981   unsigned StackSize = CCInfo.getNextStackOffset();
1982   // Align stack specially for tail calls.
1983   if (FuncIsMadeTailCallSafe(CallConv,
1984                              MF.getTarget().Options.GuaranteedTailCallOpt))
1985     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1986
1987   // If the function takes variable number of arguments, make a frame index for
1988   // the start of the first vararg value... for expansion of llvm.va_start.
1989   if (isVarArg) {
1990     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1991                     CallConv != CallingConv::X86_ThisCall)) {
1992       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1993     }
1994     if (Is64Bit) {
1995       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1996
1997       // FIXME: We should really autogenerate these arrays
1998       static const uint16_t GPR64ArgRegsWin64[] = {
1999         X86::RCX, X86::RDX, X86::R8,  X86::R9
2000       };
2001       static const uint16_t GPR64ArgRegs64Bit[] = {
2002         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2003       };
2004       static const uint16_t XMMArgRegs64Bit[] = {
2005         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2006         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2007       };
2008       const uint16_t *GPR64ArgRegs;
2009       unsigned NumXMMRegs = 0;
2010
2011       if (IsWin64) {
2012         // The XMM registers which might contain var arg parameters are shadowed
2013         // in their paired GPR.  So we only need to save the GPR to their home
2014         // slots.
2015         TotalNumIntRegs = 4;
2016         GPR64ArgRegs = GPR64ArgRegsWin64;
2017       } else {
2018         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2019         GPR64ArgRegs = GPR64ArgRegs64Bit;
2020
2021         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2022                                                 TotalNumXMMRegs);
2023       }
2024       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2025                                                        TotalNumIntRegs);
2026
2027       bool NoImplicitFloatOps = Fn->getFnAttributes().
2028         hasAttribute(Attributes::NoImplicitFloat);
2029       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2030              "SSE register cannot be used when SSE is disabled!");
2031       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2032                NoImplicitFloatOps) &&
2033              "SSE register cannot be used when SSE is disabled!");
2034       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2035           !Subtarget->hasSSE1())
2036         // Kernel mode asks for SSE to be disabled, so don't push them
2037         // on the stack.
2038         TotalNumXMMRegs = 0;
2039
2040       if (IsWin64) {
2041         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2042         // Get to the caller-allocated home save location.  Add 8 to account
2043         // for the return address.
2044         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2045         FuncInfo->setRegSaveFrameIndex(
2046           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2047         // Fixup to set vararg frame on shadow area (4 x i64).
2048         if (NumIntRegs < 4)
2049           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2050       } else {
2051         // For X86-64, if there are vararg parameters that are passed via
2052         // registers, then we must store them to their spots on the stack so
2053         // they may be loaded by deferencing the result of va_next.
2054         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2055         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2056         FuncInfo->setRegSaveFrameIndex(
2057           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2058                                false));
2059       }
2060
2061       // Store the integer parameter registers.
2062       SmallVector<SDValue, 8> MemOps;
2063       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2064                                         getPointerTy());
2065       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2066       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2067         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2068                                   DAG.getIntPtrConstant(Offset));
2069         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2070                                      &X86::GR64RegClass);
2071         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2072         SDValue Store =
2073           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2074                        MachinePointerInfo::getFixedStack(
2075                          FuncInfo->getRegSaveFrameIndex(), Offset),
2076                        false, false, 0);
2077         MemOps.push_back(Store);
2078         Offset += 8;
2079       }
2080
2081       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2082         // Now store the XMM (fp + vector) parameter registers.
2083         SmallVector<SDValue, 11> SaveXMMOps;
2084         SaveXMMOps.push_back(Chain);
2085
2086         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2087         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2088         SaveXMMOps.push_back(ALVal);
2089
2090         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2091                                FuncInfo->getRegSaveFrameIndex()));
2092         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2093                                FuncInfo->getVarArgsFPOffset()));
2094
2095         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2096           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2097                                        &X86::VR128RegClass);
2098           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2099           SaveXMMOps.push_back(Val);
2100         }
2101         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2102                                      MVT::Other,
2103                                      &SaveXMMOps[0], SaveXMMOps.size()));
2104       }
2105
2106       if (!MemOps.empty())
2107         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2108                             &MemOps[0], MemOps.size());
2109     }
2110   }
2111
2112   // Some CCs need callee pop.
2113   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2114                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2115     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2116   } else {
2117     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2118     // If this is an sret function, the return should pop the hidden pointer.
2119     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2120         argsAreStructReturn(Ins) == StackStructReturn)
2121       FuncInfo->setBytesToPopOnReturn(4);
2122   }
2123
2124   if (!Is64Bit) {
2125     // RegSaveFrameIndex is X86-64 only.
2126     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2127     if (CallConv == CallingConv::X86_FastCall ||
2128         CallConv == CallingConv::X86_ThisCall)
2129       // fastcc functions can't have varargs.
2130       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2131   }
2132
2133   FuncInfo->setArgumentStackSize(StackSize);
2134
2135   return Chain;
2136 }
2137
2138 SDValue
2139 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2140                                     SDValue StackPtr, SDValue Arg,
2141                                     DebugLoc dl, SelectionDAG &DAG,
2142                                     const CCValAssign &VA,
2143                                     ISD::ArgFlagsTy Flags) const {
2144   unsigned LocMemOffset = VA.getLocMemOffset();
2145   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2146   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2147   if (Flags.isByVal())
2148     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2149
2150   return DAG.getStore(Chain, dl, Arg, PtrOff,
2151                       MachinePointerInfo::getStack(LocMemOffset),
2152                       false, false, 0);
2153 }
2154
2155 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2156 /// optimization is performed and it is required.
2157 SDValue
2158 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2159                                            SDValue &OutRetAddr, SDValue Chain,
2160                                            bool IsTailCall, bool Is64Bit,
2161                                            int FPDiff, DebugLoc dl) const {
2162   // Adjust the Return address stack slot.
2163   EVT VT = getPointerTy();
2164   OutRetAddr = getReturnAddressFrameIndex(DAG);
2165
2166   // Load the "old" Return address.
2167   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2168                            false, false, false, 0);
2169   return SDValue(OutRetAddr.getNode(), 1);
2170 }
2171
2172 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2173 /// optimization is performed and it is required (FPDiff!=0).
2174 static SDValue
2175 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2176                          SDValue Chain, SDValue RetAddrFrIdx,
2177                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2178   // Store the return address to the appropriate stack slot.
2179   if (!FPDiff) return Chain;
2180   // Calculate the new stack slot for the return address.
2181   int SlotSize = Is64Bit ? 8 : 4;
2182   int NewReturnAddrFI =
2183     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2184   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2185   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2186   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2187                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2188                        false, false, 0);
2189   return Chain;
2190 }
2191
2192 SDValue
2193 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2194                              SmallVectorImpl<SDValue> &InVals) const {
2195   SelectionDAG &DAG                     = CLI.DAG;
2196   DebugLoc &dl                          = CLI.DL;
2197   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2198   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2199   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2200   SDValue Chain                         = CLI.Chain;
2201   SDValue Callee                        = CLI.Callee;
2202   CallingConv::ID CallConv              = CLI.CallConv;
2203   bool &isTailCall                      = CLI.IsTailCall;
2204   bool isVarArg                         = CLI.IsVarArg;
2205
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   bool Is64Bit        = Subtarget->is64Bit();
2208   bool IsWin64        = Subtarget->isTargetWin64();
2209   bool IsWindows      = Subtarget->isTargetWindows();
2210   StructReturnType SR = callIsStructReturn(Outs);
2211   bool IsSibcall      = false;
2212
2213   if (MF.getTarget().Options.DisableTailCalls)
2214     isTailCall = false;
2215
2216   if (isTailCall) {
2217     // Check if it's really possible to do a tail call.
2218     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2219                     isVarArg, SR != NotStructReturn,
2220                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2221                     Outs, OutVals, Ins, DAG);
2222
2223     // Sibcalls are automatically detected tailcalls which do not require
2224     // ABI changes.
2225     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2226       IsSibcall = true;
2227
2228     if (isTailCall)
2229       ++NumTailCalls;
2230   }
2231
2232   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2233          "Var args not supported with calling convention fastcc or ghc");
2234
2235   // Analyze operands of the call, assigning locations to each operand.
2236   SmallVector<CCValAssign, 16> ArgLocs;
2237   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2238                  ArgLocs, *DAG.getContext());
2239
2240   // Allocate shadow area for Win64
2241   if (IsWin64) {
2242     CCInfo.AllocateStack(32, 8);
2243   }
2244
2245   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2246
2247   // Get a count of how many bytes are to be pushed on the stack.
2248   unsigned NumBytes = CCInfo.getNextStackOffset();
2249   if (IsSibcall)
2250     // This is a sibcall. The memory operands are available in caller's
2251     // own caller's stack.
2252     NumBytes = 0;
2253   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2254            IsTailCallConvention(CallConv))
2255     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2256
2257   int FPDiff = 0;
2258   if (isTailCall && !IsSibcall) {
2259     // Lower arguments at fp - stackoffset + fpdiff.
2260     unsigned NumBytesCallerPushed =
2261       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2262     FPDiff = NumBytesCallerPushed - NumBytes;
2263
2264     // Set the delta of movement of the returnaddr stackslot.
2265     // But only set if delta is greater than previous delta.
2266     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2267       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2268   }
2269
2270   if (!IsSibcall)
2271     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2272
2273   SDValue RetAddrFrIdx;
2274   // Load return address for tail calls.
2275   if (isTailCall && FPDiff)
2276     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2277                                     Is64Bit, FPDiff, dl);
2278
2279   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2280   SmallVector<SDValue, 8> MemOpChains;
2281   SDValue StackPtr;
2282
2283   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2284   // of tail call optimization arguments are handle later.
2285   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2286     CCValAssign &VA = ArgLocs[i];
2287     EVT RegVT = VA.getLocVT();
2288     SDValue Arg = OutVals[i];
2289     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2290     bool isByVal = Flags.isByVal();
2291
2292     // Promote the value if needed.
2293     switch (VA.getLocInfo()) {
2294     default: llvm_unreachable("Unknown loc info!");
2295     case CCValAssign::Full: break;
2296     case CCValAssign::SExt:
2297       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2298       break;
2299     case CCValAssign::ZExt:
2300       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2301       break;
2302     case CCValAssign::AExt:
2303       if (RegVT.is128BitVector()) {
2304         // Special case: passing MMX values in XMM registers.
2305         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2306         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2307         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2308       } else
2309         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2310       break;
2311     case CCValAssign::BCvt:
2312       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2313       break;
2314     case CCValAssign::Indirect: {
2315       // Store the argument.
2316       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2317       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2318       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2319                            MachinePointerInfo::getFixedStack(FI),
2320                            false, false, 0);
2321       Arg = SpillSlot;
2322       break;
2323     }
2324     }
2325
2326     if (VA.isRegLoc()) {
2327       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2328       if (isVarArg && IsWin64) {
2329         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2330         // shadow reg if callee is a varargs function.
2331         unsigned ShadowReg = 0;
2332         switch (VA.getLocReg()) {
2333         case X86::XMM0: ShadowReg = X86::RCX; break;
2334         case X86::XMM1: ShadowReg = X86::RDX; break;
2335         case X86::XMM2: ShadowReg = X86::R8; break;
2336         case X86::XMM3: ShadowReg = X86::R9; break;
2337         }
2338         if (ShadowReg)
2339           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2340       }
2341     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2342       assert(VA.isMemLoc());
2343       if (StackPtr.getNode() == 0)
2344         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2345       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2346                                              dl, DAG, VA, Flags));
2347     }
2348   }
2349
2350   if (!MemOpChains.empty())
2351     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2352                         &MemOpChains[0], MemOpChains.size());
2353
2354   if (Subtarget->isPICStyleGOT()) {
2355     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2356     // GOT pointer.
2357     if (!isTailCall) {
2358       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2359                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2360     } else {
2361       // If we are tail calling and generating PIC/GOT style code load the
2362       // address of the callee into ECX. The value in ecx is used as target of
2363       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2364       // for tail calls on PIC/GOT architectures. Normally we would just put the
2365       // address of GOT into ebx and then call target@PLT. But for tail calls
2366       // ebx would be restored (since ebx is callee saved) before jumping to the
2367       // target@PLT.
2368
2369       // Note: The actual moving to ECX is done further down.
2370       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2371       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2372           !G->getGlobal()->hasProtectedVisibility())
2373         Callee = LowerGlobalAddress(Callee, DAG);
2374       else if (isa<ExternalSymbolSDNode>(Callee))
2375         Callee = LowerExternalSymbol(Callee, DAG);
2376     }
2377   }
2378
2379   if (Is64Bit && isVarArg && !IsWin64) {
2380     // From AMD64 ABI document:
2381     // For calls that may call functions that use varargs or stdargs
2382     // (prototype-less calls or calls to functions containing ellipsis (...) in
2383     // the declaration) %al is used as hidden argument to specify the number
2384     // of SSE registers used. The contents of %al do not need to match exactly
2385     // the number of registers, but must be an ubound on the number of SSE
2386     // registers used and is in the range 0 - 8 inclusive.
2387
2388     // Count the number of XMM registers allocated.
2389     static const uint16_t XMMArgRegs[] = {
2390       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2391       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2392     };
2393     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2394     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2395            && "SSE registers cannot be used when SSE is disabled");
2396
2397     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2398                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2399   }
2400
2401   // For tail calls lower the arguments to the 'real' stack slot.
2402   if (isTailCall) {
2403     // Force all the incoming stack arguments to be loaded from the stack
2404     // before any new outgoing arguments are stored to the stack, because the
2405     // outgoing stack slots may alias the incoming argument stack slots, and
2406     // the alias isn't otherwise explicit. This is slightly more conservative
2407     // than necessary, because it means that each store effectively depends
2408     // on every argument instead of just those arguments it would clobber.
2409     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2410
2411     SmallVector<SDValue, 8> MemOpChains2;
2412     SDValue FIN;
2413     int FI = 0;
2414     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2415       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416         CCValAssign &VA = ArgLocs[i];
2417         if (VA.isRegLoc())
2418           continue;
2419         assert(VA.isMemLoc());
2420         SDValue Arg = OutVals[i];
2421         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2422         // Create frame index.
2423         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2424         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2425         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2426         FIN = DAG.getFrameIndex(FI, getPointerTy());
2427
2428         if (Flags.isByVal()) {
2429           // Copy relative to framepointer.
2430           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2431           if (StackPtr.getNode() == 0)
2432             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2433                                           getPointerTy());
2434           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2435
2436           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2437                                                            ArgChain,
2438                                                            Flags, DAG, dl));
2439         } else {
2440           // Store relative to framepointer.
2441           MemOpChains2.push_back(
2442             DAG.getStore(ArgChain, dl, Arg, FIN,
2443                          MachinePointerInfo::getFixedStack(FI),
2444                          false, false, 0));
2445         }
2446       }
2447     }
2448
2449     if (!MemOpChains2.empty())
2450       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2451                           &MemOpChains2[0], MemOpChains2.size());
2452
2453     // Store the return address to the appropriate stack slot.
2454     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2455                                      FPDiff, dl);
2456   }
2457
2458   // Build a sequence of copy-to-reg nodes chained together with token chain
2459   // and flag operands which copy the outgoing args into registers.
2460   SDValue InFlag;
2461   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2462     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2463                              RegsToPass[i].second, InFlag);
2464     InFlag = Chain.getValue(1);
2465   }
2466
2467   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2468     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2469     // In the 64-bit large code model, we have to make all calls
2470     // through a register, since the call instruction's 32-bit
2471     // pc-relative offset may not be large enough to hold the whole
2472     // address.
2473   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2474     // If the callee is a GlobalAddress node (quite common, every direct call
2475     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2476     // it.
2477
2478     // We should use extra load for direct calls to dllimported functions in
2479     // non-JIT mode.
2480     const GlobalValue *GV = G->getGlobal();
2481     if (!GV->hasDLLImportLinkage()) {
2482       unsigned char OpFlags = 0;
2483       bool ExtraLoad = false;
2484       unsigned WrapperKind = ISD::DELETED_NODE;
2485
2486       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2487       // external symbols most go through the PLT in PIC mode.  If the symbol
2488       // has hidden or protected visibility, or if it is static or local, then
2489       // we don't need to use the PLT - we can directly call it.
2490       if (Subtarget->isTargetELF() &&
2491           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2492           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2493         OpFlags = X86II::MO_PLT;
2494       } else if (Subtarget->isPICStyleStubAny() &&
2495                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2496                  (!Subtarget->getTargetTriple().isMacOSX() ||
2497                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2498         // PC-relative references to external symbols should go through $stub,
2499         // unless we're building with the leopard linker or later, which
2500         // automatically synthesizes these stubs.
2501         OpFlags = X86II::MO_DARWIN_STUB;
2502       } else if (Subtarget->isPICStyleRIPRel() &&
2503                  isa<Function>(GV) &&
2504                  cast<Function>(GV)->getFnAttributes().
2505                    hasAttribute(Attributes::NonLazyBind)) {
2506         // If the function is marked as non-lazy, generate an indirect call
2507         // which loads from the GOT directly. This avoids runtime overhead
2508         // at the cost of eager binding (and one extra byte of encoding).
2509         OpFlags = X86II::MO_GOTPCREL;
2510         WrapperKind = X86ISD::WrapperRIP;
2511         ExtraLoad = true;
2512       }
2513
2514       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2515                                           G->getOffset(), OpFlags);
2516
2517       // Add a wrapper if needed.
2518       if (WrapperKind != ISD::DELETED_NODE)
2519         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2520       // Add extra indirection if needed.
2521       if (ExtraLoad)
2522         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2523                              MachinePointerInfo::getGOT(),
2524                              false, false, false, 0);
2525     }
2526   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2527     unsigned char OpFlags = 0;
2528
2529     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2530     // external symbols should go through the PLT.
2531     if (Subtarget->isTargetELF() &&
2532         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2533       OpFlags = X86II::MO_PLT;
2534     } else if (Subtarget->isPICStyleStubAny() &&
2535                (!Subtarget->getTargetTriple().isMacOSX() ||
2536                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2537       // PC-relative references to external symbols should go through $stub,
2538       // unless we're building with the leopard linker or later, which
2539       // automatically synthesizes these stubs.
2540       OpFlags = X86II::MO_DARWIN_STUB;
2541     }
2542
2543     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2544                                          OpFlags);
2545   }
2546
2547   // Returns a chain & a flag for retval copy to use.
2548   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2549   SmallVector<SDValue, 8> Ops;
2550
2551   if (!IsSibcall && isTailCall) {
2552     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2553                            DAG.getIntPtrConstant(0, true), InFlag);
2554     InFlag = Chain.getValue(1);
2555   }
2556
2557   Ops.push_back(Chain);
2558   Ops.push_back(Callee);
2559
2560   if (isTailCall)
2561     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2562
2563   // Add argument registers to the end of the list so that they are known live
2564   // into the call.
2565   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2566     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2567                                   RegsToPass[i].second.getValueType()));
2568
2569   // Add a register mask operand representing the call-preserved registers.
2570   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2571   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2572   assert(Mask && "Missing call preserved mask for calling convention");
2573   Ops.push_back(DAG.getRegisterMask(Mask));
2574
2575   if (InFlag.getNode())
2576     Ops.push_back(InFlag);
2577
2578   if (isTailCall) {
2579     // We used to do:
2580     //// If this is the first return lowered for this function, add the regs
2581     //// to the liveout set for the function.
2582     // This isn't right, although it's probably harmless on x86; liveouts
2583     // should be computed from returns not tail calls.  Consider a void
2584     // function making a tail call to a function returning int.
2585     return DAG.getNode(X86ISD::TC_RETURN, dl,
2586                        NodeTys, &Ops[0], Ops.size());
2587   }
2588
2589   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2590   InFlag = Chain.getValue(1);
2591
2592   // Create the CALLSEQ_END node.
2593   unsigned NumBytesForCalleeToPush;
2594   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2595                        getTargetMachine().Options.GuaranteedTailCallOpt))
2596     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2597   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2598            SR == StackStructReturn)
2599     // If this is a call to a struct-return function, the callee
2600     // pops the hidden struct pointer, so we have to push it back.
2601     // This is common for Darwin/X86, Linux & Mingw32 targets.
2602     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2603     NumBytesForCalleeToPush = 4;
2604   else
2605     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2606
2607   // Returns a flag for retval copy to use.
2608   if (!IsSibcall) {
2609     Chain = DAG.getCALLSEQ_END(Chain,
2610                                DAG.getIntPtrConstant(NumBytes, true),
2611                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2612                                                      true),
2613                                InFlag);
2614     InFlag = Chain.getValue(1);
2615   }
2616
2617   // Handle result values, copying them out of physregs into vregs that we
2618   // return.
2619   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2620                          Ins, dl, DAG, InVals);
2621 }
2622
2623
2624 //===----------------------------------------------------------------------===//
2625 //                Fast Calling Convention (tail call) implementation
2626 //===----------------------------------------------------------------------===//
2627
2628 //  Like std call, callee cleans arguments, convention except that ECX is
2629 //  reserved for storing the tail called function address. Only 2 registers are
2630 //  free for argument passing (inreg). Tail call optimization is performed
2631 //  provided:
2632 //                * tailcallopt is enabled
2633 //                * caller/callee are fastcc
2634 //  On X86_64 architecture with GOT-style position independent code only local
2635 //  (within module) calls are supported at the moment.
2636 //  To keep the stack aligned according to platform abi the function
2637 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2638 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2639 //  If a tail called function callee has more arguments than the caller the
2640 //  caller needs to make sure that there is room to move the RETADDR to. This is
2641 //  achieved by reserving an area the size of the argument delta right after the
2642 //  original REtADDR, but before the saved framepointer or the spilled registers
2643 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2644 //  stack layout:
2645 //    arg1
2646 //    arg2
2647 //    RETADDR
2648 //    [ new RETADDR
2649 //      move area ]
2650 //    (possible EBP)
2651 //    ESI
2652 //    EDI
2653 //    local1 ..
2654
2655 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2656 /// for a 16 byte align requirement.
2657 unsigned
2658 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2659                                                SelectionDAG& DAG) const {
2660   MachineFunction &MF = DAG.getMachineFunction();
2661   const TargetMachine &TM = MF.getTarget();
2662   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2663   unsigned StackAlignment = TFI.getStackAlignment();
2664   uint64_t AlignMask = StackAlignment - 1;
2665   int64_t Offset = StackSize;
2666   uint64_t SlotSize = TD->getPointerSize(0);
2667   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2668     // Number smaller than 12 so just add the difference.
2669     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2670   } else {
2671     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2672     Offset = ((~AlignMask) & Offset) + StackAlignment +
2673       (StackAlignment-SlotSize);
2674   }
2675   return Offset;
2676 }
2677
2678 /// MatchingStackOffset - Return true if the given stack call argument is
2679 /// already available in the same position (relatively) of the caller's
2680 /// incoming argument stack.
2681 static
2682 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2683                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2684                          const X86InstrInfo *TII) {
2685   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2686   int FI = INT_MAX;
2687   if (Arg.getOpcode() == ISD::CopyFromReg) {
2688     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2689     if (!TargetRegisterInfo::isVirtualRegister(VR))
2690       return false;
2691     MachineInstr *Def = MRI->getVRegDef(VR);
2692     if (!Def)
2693       return false;
2694     if (!Flags.isByVal()) {
2695       if (!TII->isLoadFromStackSlot(Def, FI))
2696         return false;
2697     } else {
2698       unsigned Opcode = Def->getOpcode();
2699       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2700           Def->getOperand(1).isFI()) {
2701         FI = Def->getOperand(1).getIndex();
2702         Bytes = Flags.getByValSize();
2703       } else
2704         return false;
2705     }
2706   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2707     if (Flags.isByVal())
2708       // ByVal argument is passed in as a pointer but it's now being
2709       // dereferenced. e.g.
2710       // define @foo(%struct.X* %A) {
2711       //   tail call @bar(%struct.X* byval %A)
2712       // }
2713       return false;
2714     SDValue Ptr = Ld->getBasePtr();
2715     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2716     if (!FINode)
2717       return false;
2718     FI = FINode->getIndex();
2719   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2720     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2721     FI = FINode->getIndex();
2722     Bytes = Flags.getByValSize();
2723   } else
2724     return false;
2725
2726   assert(FI != INT_MAX);
2727   if (!MFI->isFixedObjectIndex(FI))
2728     return false;
2729   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2730 }
2731
2732 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2733 /// for tail call optimization. Targets which want to do tail call
2734 /// optimization should implement this function.
2735 bool
2736 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2737                                                      CallingConv::ID CalleeCC,
2738                                                      bool isVarArg,
2739                                                      bool isCalleeStructRet,
2740                                                      bool isCallerStructRet,
2741                                                      Type *RetTy,
2742                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2743                                     const SmallVectorImpl<SDValue> &OutVals,
2744                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2745                                                      SelectionDAG& DAG) const {
2746   if (!IsTailCallConvention(CalleeCC) &&
2747       CalleeCC != CallingConv::C)
2748     return false;
2749
2750   // If -tailcallopt is specified, make fastcc functions tail-callable.
2751   const MachineFunction &MF = DAG.getMachineFunction();
2752   const Function *CallerF = DAG.getMachineFunction().getFunction();
2753
2754   // If the function return type is x86_fp80 and the callee return type is not,
2755   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2756   // perform a tailcall optimization here.
2757   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2758     return false;
2759
2760   CallingConv::ID CallerCC = CallerF->getCallingConv();
2761   bool CCMatch = CallerCC == CalleeCC;
2762
2763   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2764     if (IsTailCallConvention(CalleeCC) && CCMatch)
2765       return true;
2766     return false;
2767   }
2768
2769   // Look for obvious safe cases to perform tail call optimization that do not
2770   // require ABI changes. This is what gcc calls sibcall.
2771
2772   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2773   // emit a special epilogue.
2774   if (RegInfo->needsStackRealignment(MF))
2775     return false;
2776
2777   // Also avoid sibcall optimization if either caller or callee uses struct
2778   // return semantics.
2779   if (isCalleeStructRet || isCallerStructRet)
2780     return false;
2781
2782   // An stdcall caller is expected to clean up its arguments; the callee
2783   // isn't going to do that.
2784   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2785     return false;
2786
2787   // Do not sibcall optimize vararg calls unless all arguments are passed via
2788   // registers.
2789   if (isVarArg && !Outs.empty()) {
2790
2791     // Optimizing for varargs on Win64 is unlikely to be safe without
2792     // additional testing.
2793     if (Subtarget->isTargetWin64())
2794       return false;
2795
2796     SmallVector<CCValAssign, 16> ArgLocs;
2797     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2798                    getTargetMachine(), ArgLocs, *DAG.getContext());
2799
2800     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2802       if (!ArgLocs[i].isRegLoc())
2803         return false;
2804   }
2805
2806   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2807   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2808   // this into a sibcall.
2809   bool Unused = false;
2810   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2811     if (!Ins[i].Used) {
2812       Unused = true;
2813       break;
2814     }
2815   }
2816   if (Unused) {
2817     SmallVector<CCValAssign, 16> RVLocs;
2818     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2819                    getTargetMachine(), RVLocs, *DAG.getContext());
2820     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2821     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2822       CCValAssign &VA = RVLocs[i];
2823       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2824         return false;
2825     }
2826   }
2827
2828   // If the calling conventions do not match, then we'd better make sure the
2829   // results are returned in the same way as what the caller expects.
2830   if (!CCMatch) {
2831     SmallVector<CCValAssign, 16> RVLocs1;
2832     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2833                     getTargetMachine(), RVLocs1, *DAG.getContext());
2834     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2835
2836     SmallVector<CCValAssign, 16> RVLocs2;
2837     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2838                     getTargetMachine(), RVLocs2, *DAG.getContext());
2839     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2840
2841     if (RVLocs1.size() != RVLocs2.size())
2842       return false;
2843     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2844       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2845         return false;
2846       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2847         return false;
2848       if (RVLocs1[i].isRegLoc()) {
2849         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2850           return false;
2851       } else {
2852         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2853           return false;
2854       }
2855     }
2856   }
2857
2858   // If the callee takes no arguments then go on to check the results of the
2859   // call.
2860   if (!Outs.empty()) {
2861     // Check if stack adjustment is needed. For now, do not do this if any
2862     // argument is passed on the stack.
2863     SmallVector<CCValAssign, 16> ArgLocs;
2864     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2865                    getTargetMachine(), ArgLocs, *DAG.getContext());
2866
2867     // Allocate shadow area for Win64
2868     if (Subtarget->isTargetWin64()) {
2869       CCInfo.AllocateStack(32, 8);
2870     }
2871
2872     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2873     if (CCInfo.getNextStackOffset()) {
2874       MachineFunction &MF = DAG.getMachineFunction();
2875       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2876         return false;
2877
2878       // Check if the arguments are already laid out in the right way as
2879       // the caller's fixed stack objects.
2880       MachineFrameInfo *MFI = MF.getFrameInfo();
2881       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2882       const X86InstrInfo *TII =
2883         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2884       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2885         CCValAssign &VA = ArgLocs[i];
2886         SDValue Arg = OutVals[i];
2887         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888         if (VA.getLocInfo() == CCValAssign::Indirect)
2889           return false;
2890         if (!VA.isRegLoc()) {
2891           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2892                                    MFI, MRI, TII))
2893             return false;
2894         }
2895       }
2896     }
2897
2898     // If the tailcall address may be in a register, then make sure it's
2899     // possible to register allocate for it. In 32-bit, the call address can
2900     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2901     // callee-saved registers are restored. These happen to be the same
2902     // registers used to pass 'inreg' arguments so watch out for those.
2903     if (!Subtarget->is64Bit() &&
2904         !isa<GlobalAddressSDNode>(Callee) &&
2905         !isa<ExternalSymbolSDNode>(Callee)) {
2906       unsigned NumInRegs = 0;
2907       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2908         CCValAssign &VA = ArgLocs[i];
2909         if (!VA.isRegLoc())
2910           continue;
2911         unsigned Reg = VA.getLocReg();
2912         switch (Reg) {
2913         default: break;
2914         case X86::EAX: case X86::EDX: case X86::ECX:
2915           if (++NumInRegs == 3)
2916             return false;
2917           break;
2918         }
2919       }
2920     }
2921   }
2922
2923   return true;
2924 }
2925
2926 FastISel *
2927 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2928                                   const TargetLibraryInfo *libInfo) const {
2929   return X86::createFastISel(funcInfo, libInfo);
2930 }
2931
2932
2933 //===----------------------------------------------------------------------===//
2934 //                           Other Lowering Hooks
2935 //===----------------------------------------------------------------------===//
2936
2937 static bool MayFoldLoad(SDValue Op) {
2938   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2939 }
2940
2941 static bool MayFoldIntoStore(SDValue Op) {
2942   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2943 }
2944
2945 static bool isTargetShuffle(unsigned Opcode) {
2946   switch(Opcode) {
2947   default: return false;
2948   case X86ISD::PSHUFD:
2949   case X86ISD::PSHUFHW:
2950   case X86ISD::PSHUFLW:
2951   case X86ISD::SHUFP:
2952   case X86ISD::PALIGN:
2953   case X86ISD::MOVLHPS:
2954   case X86ISD::MOVLHPD:
2955   case X86ISD::MOVHLPS:
2956   case X86ISD::MOVLPS:
2957   case X86ISD::MOVLPD:
2958   case X86ISD::MOVSHDUP:
2959   case X86ISD::MOVSLDUP:
2960   case X86ISD::MOVDDUP:
2961   case X86ISD::MOVSS:
2962   case X86ISD::MOVSD:
2963   case X86ISD::UNPCKL:
2964   case X86ISD::UNPCKH:
2965   case X86ISD::VPERMILP:
2966   case X86ISD::VPERM2X128:
2967   case X86ISD::VPERMI:
2968     return true;
2969   }
2970 }
2971
2972 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2973                                     SDValue V1, SelectionDAG &DAG) {
2974   switch(Opc) {
2975   default: llvm_unreachable("Unknown x86 shuffle node");
2976   case X86ISD::MOVSHDUP:
2977   case X86ISD::MOVSLDUP:
2978   case X86ISD::MOVDDUP:
2979     return DAG.getNode(Opc, dl, VT, V1);
2980   }
2981 }
2982
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984                                     SDValue V1, unsigned TargetMask,
2985                                     SelectionDAG &DAG) {
2986   switch(Opc) {
2987   default: llvm_unreachable("Unknown x86 shuffle node");
2988   case X86ISD::PSHUFD:
2989   case X86ISD::PSHUFHW:
2990   case X86ISD::PSHUFLW:
2991   case X86ISD::VPERMILP:
2992   case X86ISD::VPERMI:
2993     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2994   }
2995 }
2996
2997 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2998                                     SDValue V1, SDValue V2, unsigned TargetMask,
2999                                     SelectionDAG &DAG) {
3000   switch(Opc) {
3001   default: llvm_unreachable("Unknown x86 shuffle node");
3002   case X86ISD::PALIGN:
3003   case X86ISD::SHUFP:
3004   case X86ISD::VPERM2X128:
3005     return DAG.getNode(Opc, dl, VT, V1, V2,
3006                        DAG.getConstant(TargetMask, MVT::i8));
3007   }
3008 }
3009
3010 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3011                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3012   switch(Opc) {
3013   default: llvm_unreachable("Unknown x86 shuffle node");
3014   case X86ISD::MOVLHPS:
3015   case X86ISD::MOVLHPD:
3016   case X86ISD::MOVHLPS:
3017   case X86ISD::MOVLPS:
3018   case X86ISD::MOVLPD:
3019   case X86ISD::MOVSS:
3020   case X86ISD::MOVSD:
3021   case X86ISD::UNPCKL:
3022   case X86ISD::UNPCKH:
3023     return DAG.getNode(Opc, dl, VT, V1, V2);
3024   }
3025 }
3026
3027 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3028   MachineFunction &MF = DAG.getMachineFunction();
3029   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3030   int ReturnAddrIndex = FuncInfo->getRAIndex();
3031
3032   if (ReturnAddrIndex == 0) {
3033     // Set up a frame object for the return address.
3034     uint64_t SlotSize = TD->getPointerSize(0);
3035     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3036                                                            false);
3037     FuncInfo->setRAIndex(ReturnAddrIndex);
3038   }
3039
3040   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3041 }
3042
3043
3044 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3045                                        bool hasSymbolicDisplacement) {
3046   // Offset should fit into 32 bit immediate field.
3047   if (!isInt<32>(Offset))
3048     return false;
3049
3050   // If we don't have a symbolic displacement - we don't have any extra
3051   // restrictions.
3052   if (!hasSymbolicDisplacement)
3053     return true;
3054
3055   // FIXME: Some tweaks might be needed for medium code model.
3056   if (M != CodeModel::Small && M != CodeModel::Kernel)
3057     return false;
3058
3059   // For small code model we assume that latest object is 16MB before end of 31
3060   // bits boundary. We may also accept pretty large negative constants knowing
3061   // that all objects are in the positive half of address space.
3062   if (M == CodeModel::Small && Offset < 16*1024*1024)
3063     return true;
3064
3065   // For kernel code model we know that all object resist in the negative half
3066   // of 32bits address space. We may not accept negative offsets, since they may
3067   // be just off and we may accept pretty large positive ones.
3068   if (M == CodeModel::Kernel && Offset > 0)
3069     return true;
3070
3071   return false;
3072 }
3073
3074 /// isCalleePop - Determines whether the callee is required to pop its
3075 /// own arguments. Callee pop is necessary to support tail calls.
3076 bool X86::isCalleePop(CallingConv::ID CallingConv,
3077                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3078   if (IsVarArg)
3079     return false;
3080
3081   switch (CallingConv) {
3082   default:
3083     return false;
3084   case CallingConv::X86_StdCall:
3085     return !is64Bit;
3086   case CallingConv::X86_FastCall:
3087     return !is64Bit;
3088   case CallingConv::X86_ThisCall:
3089     return !is64Bit;
3090   case CallingConv::Fast:
3091     return TailCallOpt;
3092   case CallingConv::GHC:
3093     return TailCallOpt;
3094   }
3095 }
3096
3097 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3098 /// specific condition code, returning the condition code and the LHS/RHS of the
3099 /// comparison to make.
3100 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3101                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3102   if (!isFP) {
3103     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3104       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3105         // X > -1   -> X == 0, jump !sign.
3106         RHS = DAG.getConstant(0, RHS.getValueType());
3107         return X86::COND_NS;
3108       }
3109       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3110         // X < 0   -> X == 0, jump on sign.
3111         return X86::COND_S;
3112       }
3113       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3114         // X < 1   -> X <= 0
3115         RHS = DAG.getConstant(0, RHS.getValueType());
3116         return X86::COND_LE;
3117       }
3118     }
3119
3120     switch (SetCCOpcode) {
3121     default: llvm_unreachable("Invalid integer condition!");
3122     case ISD::SETEQ:  return X86::COND_E;
3123     case ISD::SETGT:  return X86::COND_G;
3124     case ISD::SETGE:  return X86::COND_GE;
3125     case ISD::SETLT:  return X86::COND_L;
3126     case ISD::SETLE:  return X86::COND_LE;
3127     case ISD::SETNE:  return X86::COND_NE;
3128     case ISD::SETULT: return X86::COND_B;
3129     case ISD::SETUGT: return X86::COND_A;
3130     case ISD::SETULE: return X86::COND_BE;
3131     case ISD::SETUGE: return X86::COND_AE;
3132     }
3133   }
3134
3135   // First determine if it is required or is profitable to flip the operands.
3136
3137   // If LHS is a foldable load, but RHS is not, flip the condition.
3138   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3139       !ISD::isNON_EXTLoad(RHS.getNode())) {
3140     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3141     std::swap(LHS, RHS);
3142   }
3143
3144   switch (SetCCOpcode) {
3145   default: break;
3146   case ISD::SETOLT:
3147   case ISD::SETOLE:
3148   case ISD::SETUGT:
3149   case ISD::SETUGE:
3150     std::swap(LHS, RHS);
3151     break;
3152   }
3153
3154   // On a floating point condition, the flags are set as follows:
3155   // ZF  PF  CF   op
3156   //  0 | 0 | 0 | X > Y
3157   //  0 | 0 | 1 | X < Y
3158   //  1 | 0 | 0 | X == Y
3159   //  1 | 1 | 1 | unordered
3160   switch (SetCCOpcode) {
3161   default: llvm_unreachable("Condcode should be pre-legalized away");
3162   case ISD::SETUEQ:
3163   case ISD::SETEQ:   return X86::COND_E;
3164   case ISD::SETOLT:              // flipped
3165   case ISD::SETOGT:
3166   case ISD::SETGT:   return X86::COND_A;
3167   case ISD::SETOLE:              // flipped
3168   case ISD::SETOGE:
3169   case ISD::SETGE:   return X86::COND_AE;
3170   case ISD::SETUGT:              // flipped
3171   case ISD::SETULT:
3172   case ISD::SETLT:   return X86::COND_B;
3173   case ISD::SETUGE:              // flipped
3174   case ISD::SETULE:
3175   case ISD::SETLE:   return X86::COND_BE;
3176   case ISD::SETONE:
3177   case ISD::SETNE:   return X86::COND_NE;
3178   case ISD::SETUO:   return X86::COND_P;
3179   case ISD::SETO:    return X86::COND_NP;
3180   case ISD::SETOEQ:
3181   case ISD::SETUNE:  return X86::COND_INVALID;
3182   }
3183 }
3184
3185 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3186 /// code. Current x86 isa includes the following FP cmov instructions:
3187 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3188 static bool hasFPCMov(unsigned X86CC) {
3189   switch (X86CC) {
3190   default:
3191     return false;
3192   case X86::COND_B:
3193   case X86::COND_BE:
3194   case X86::COND_E:
3195   case X86::COND_P:
3196   case X86::COND_A:
3197   case X86::COND_AE:
3198   case X86::COND_NE:
3199   case X86::COND_NP:
3200     return true;
3201   }
3202 }
3203
3204 /// isFPImmLegal - Returns true if the target can instruction select the
3205 /// specified FP immediate natively. If false, the legalizer will
3206 /// materialize the FP immediate as a load from a constant pool.
3207 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3208   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3209     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3210       return true;
3211   }
3212   return false;
3213 }
3214
3215 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3216 /// the specified range (L, H].
3217 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3218   return (Val < 0) || (Val >= Low && Val < Hi);
3219 }
3220
3221 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3222 /// specified value.
3223 static bool isUndefOrEqual(int Val, int CmpVal) {
3224   if (Val < 0 || Val == CmpVal)
3225     return true;
3226   return false;
3227 }
3228
3229 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3230 /// from position Pos and ending in Pos+Size, falls within the specified
3231 /// sequential range (L, L+Pos]. or is undef.
3232 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3233                                        unsigned Pos, unsigned Size, int Low) {
3234   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3235     if (!isUndefOrEqual(Mask[i], Low))
3236       return false;
3237   return true;
3238 }
3239
3240 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3241 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3242 /// the second operand.
3243 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3244   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3245     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3246   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3247     return (Mask[0] < 2 && Mask[1] < 2);
3248   return false;
3249 }
3250
3251 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3252 /// is suitable for input to PSHUFHW.
3253 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3254   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3255     return false;
3256
3257   // Lower quadword copied in order or undef.
3258   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3259     return false;
3260
3261   // Upper quadword shuffled.
3262   for (unsigned i = 4; i != 8; ++i)
3263     if (!isUndefOrInRange(Mask[i], 4, 8))
3264       return false;
3265
3266   if (VT == MVT::v16i16) {
3267     // Lower quadword copied in order or undef.
3268     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3269       return false;
3270
3271     // Upper quadword shuffled.
3272     for (unsigned i = 12; i != 16; ++i)
3273       if (!isUndefOrInRange(Mask[i], 12, 16))
3274         return false;
3275   }
3276
3277   return true;
3278 }
3279
3280 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3281 /// is suitable for input to PSHUFLW.
3282 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3283   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3284     return false;
3285
3286   // Upper quadword copied in order.
3287   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3288     return false;
3289
3290   // Lower quadword shuffled.
3291   for (unsigned i = 0; i != 4; ++i)
3292     if (!isUndefOrInRange(Mask[i], 0, 4))
3293       return false;
3294
3295   if (VT == MVT::v16i16) {
3296     // Upper quadword copied in order.
3297     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3298       return false;
3299
3300     // Lower quadword shuffled.
3301     for (unsigned i = 8; i != 12; ++i)
3302       if (!isUndefOrInRange(Mask[i], 8, 12))
3303         return false;
3304   }
3305
3306   return true;
3307 }
3308
3309 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3310 /// is suitable for input to PALIGNR.
3311 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3312                           const X86Subtarget *Subtarget) {
3313   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3314       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3315     return false;
3316
3317   unsigned NumElts = VT.getVectorNumElements();
3318   unsigned NumLanes = VT.getSizeInBits()/128;
3319   unsigned NumLaneElts = NumElts/NumLanes;
3320
3321   // Do not handle 64-bit element shuffles with palignr.
3322   if (NumLaneElts == 2)
3323     return false;
3324
3325   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3326     unsigned i;
3327     for (i = 0; i != NumLaneElts; ++i) {
3328       if (Mask[i+l] >= 0)
3329         break;
3330     }
3331
3332     // Lane is all undef, go to next lane
3333     if (i == NumLaneElts)
3334       continue;
3335
3336     int Start = Mask[i+l];
3337
3338     // Make sure its in this lane in one of the sources
3339     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3340         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3341       return false;
3342
3343     // If not lane 0, then we must match lane 0
3344     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3345       return false;
3346
3347     // Correct second source to be contiguous with first source
3348     if (Start >= (int)NumElts)
3349       Start -= NumElts - NumLaneElts;
3350
3351     // Make sure we're shifting in the right direction.
3352     if (Start <= (int)(i+l))
3353       return false;
3354
3355     Start -= i;
3356
3357     // Check the rest of the elements to see if they are consecutive.
3358     for (++i; i != NumLaneElts; ++i) {
3359       int Idx = Mask[i+l];
3360
3361       // Make sure its in this lane
3362       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3363           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3364         return false;
3365
3366       // If not lane 0, then we must match lane 0
3367       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3368         return false;
3369
3370       if (Idx >= (int)NumElts)
3371         Idx -= NumElts - NumLaneElts;
3372
3373       if (!isUndefOrEqual(Idx, Start+i))
3374         return false;
3375
3376     }
3377   }
3378
3379   return true;
3380 }
3381
3382 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3383 /// the two vector operands have swapped position.
3384 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3385                                      unsigned NumElems) {
3386   for (unsigned i = 0; i != NumElems; ++i) {
3387     int idx = Mask[i];
3388     if (idx < 0)
3389       continue;
3390     else if (idx < (int)NumElems)
3391       Mask[i] = idx + NumElems;
3392     else
3393       Mask[i] = idx - NumElems;
3394   }
3395 }
3396
3397 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3398 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3399 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3400 /// reverse of what x86 shuffles want.
3401 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3402                         bool Commuted = false) {
3403   if (!HasAVX && VT.getSizeInBits() == 256)
3404     return false;
3405
3406   unsigned NumElems = VT.getVectorNumElements();
3407   unsigned NumLanes = VT.getSizeInBits()/128;
3408   unsigned NumLaneElems = NumElems/NumLanes;
3409
3410   if (NumLaneElems != 2 && NumLaneElems != 4)
3411     return false;
3412
3413   // VSHUFPSY divides the resulting vector into 4 chunks.
3414   // The sources are also splitted into 4 chunks, and each destination
3415   // chunk must come from a different source chunk.
3416   //
3417   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3418   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3419   //
3420   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3421   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3422   //
3423   // VSHUFPDY divides the resulting vector into 4 chunks.
3424   // The sources are also splitted into 4 chunks, and each destination
3425   // chunk must come from a different source chunk.
3426   //
3427   //  SRC1 =>      X3       X2       X1       X0
3428   //  SRC2 =>      Y3       Y2       Y1       Y0
3429   //
3430   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3431   //
3432   unsigned HalfLaneElems = NumLaneElems/2;
3433   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3434     for (unsigned i = 0; i != NumLaneElems; ++i) {
3435       int Idx = Mask[i+l];
3436       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3437       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3438         return false;
3439       // For VSHUFPSY, the mask of the second half must be the same as the
3440       // first but with the appropriate offsets. This works in the same way as
3441       // VPERMILPS works with masks.
3442       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3443         continue;
3444       if (!isUndefOrEqual(Idx, Mask[i]+l))
3445         return false;
3446     }
3447   }
3448
3449   return true;
3450 }
3451
3452 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3453 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3454 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3455   if (!VT.is128BitVector())
3456     return false;
3457
3458   unsigned NumElems = VT.getVectorNumElements();
3459
3460   if (NumElems != 4)
3461     return false;
3462
3463   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3464   return isUndefOrEqual(Mask[0], 6) &&
3465          isUndefOrEqual(Mask[1], 7) &&
3466          isUndefOrEqual(Mask[2], 2) &&
3467          isUndefOrEqual(Mask[3], 3);
3468 }
3469
3470 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3471 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3472 /// <2, 3, 2, 3>
3473 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3474   if (!VT.is128BitVector())
3475     return false;
3476
3477   unsigned NumElems = VT.getVectorNumElements();
3478
3479   if (NumElems != 4)
3480     return false;
3481
3482   return isUndefOrEqual(Mask[0], 2) &&
3483          isUndefOrEqual(Mask[1], 3) &&
3484          isUndefOrEqual(Mask[2], 2) &&
3485          isUndefOrEqual(Mask[3], 3);
3486 }
3487
3488 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3490 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3491   if (!VT.is128BitVector())
3492     return false;
3493
3494   unsigned NumElems = VT.getVectorNumElements();
3495
3496   if (NumElems != 2 && NumElems != 4)
3497     return false;
3498
3499   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3500     if (!isUndefOrEqual(Mask[i], i + NumElems))
3501       return false;
3502
3503   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3504     if (!isUndefOrEqual(Mask[i], i))
3505       return false;
3506
3507   return true;
3508 }
3509
3510 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3511 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3512 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3513   if (!VT.is128BitVector())
3514     return false;
3515
3516   unsigned NumElems = VT.getVectorNumElements();
3517
3518   if (NumElems != 2 && NumElems != 4)
3519     return false;
3520
3521   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3522     if (!isUndefOrEqual(Mask[i], i))
3523       return false;
3524
3525   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3526     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3527       return false;
3528
3529   return true;
3530 }
3531
3532 //
3533 // Some special combinations that can be optimized.
3534 //
3535 static
3536 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3537                                SelectionDAG &DAG) {
3538   EVT VT = SVOp->getValueType(0);
3539   DebugLoc dl = SVOp->getDebugLoc();
3540
3541   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3542     return SDValue();
3543
3544   ArrayRef<int> Mask = SVOp->getMask();
3545
3546   // These are the special masks that may be optimized.
3547   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3548   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3549   bool MatchEvenMask = true;
3550   bool MatchOddMask  = true;
3551   for (int i=0; i<8; ++i) {
3552     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3553       MatchEvenMask = false;
3554     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3555       MatchOddMask = false;
3556   }
3557
3558   if (!MatchEvenMask && !MatchOddMask)
3559     return SDValue();
3560
3561   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3562
3563   SDValue Op0 = SVOp->getOperand(0);
3564   SDValue Op1 = SVOp->getOperand(1);
3565
3566   if (MatchEvenMask) {
3567     // Shift the second operand right to 32 bits.
3568     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3569     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3570   } else {
3571     // Shift the first operand left to 32 bits.
3572     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3573     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3574   }
3575   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3576   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3577 }
3578
3579 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3580 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3581 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3582                          bool HasAVX2, bool V2IsSplat = false) {
3583   unsigned NumElts = VT.getVectorNumElements();
3584
3585   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3586          "Unsupported vector type for unpckh");
3587
3588   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3589       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3590     return false;
3591
3592   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593   // independently on 128-bit lanes.
3594   unsigned NumLanes = VT.getSizeInBits()/128;
3595   unsigned NumLaneElts = NumElts/NumLanes;
3596
3597   for (unsigned l = 0; l != NumLanes; ++l) {
3598     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3599          i != (l+1)*NumLaneElts;
3600          i += 2, ++j) {
3601       int BitI  = Mask[i];
3602       int BitI1 = Mask[i+1];
3603       if (!isUndefOrEqual(BitI, j))
3604         return false;
3605       if (V2IsSplat) {
3606         if (!isUndefOrEqual(BitI1, NumElts))
3607           return false;
3608       } else {
3609         if (!isUndefOrEqual(BitI1, j + NumElts))
3610           return false;
3611       }
3612     }
3613   }
3614
3615   return true;
3616 }
3617
3618 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3619 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3620 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3621                          bool HasAVX2, bool V2IsSplat = false) {
3622   unsigned NumElts = VT.getVectorNumElements();
3623
3624   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3625          "Unsupported vector type for unpckh");
3626
3627   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3628       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3629     return false;
3630
3631   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3632   // independently on 128-bit lanes.
3633   unsigned NumLanes = VT.getSizeInBits()/128;
3634   unsigned NumLaneElts = NumElts/NumLanes;
3635
3636   for (unsigned l = 0; l != NumLanes; ++l) {
3637     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3638          i != (l+1)*NumLaneElts; i += 2, ++j) {
3639       int BitI  = Mask[i];
3640       int BitI1 = Mask[i+1];
3641       if (!isUndefOrEqual(BitI, j))
3642         return false;
3643       if (V2IsSplat) {
3644         if (isUndefOrEqual(BitI1, NumElts))
3645           return false;
3646       } else {
3647         if (!isUndefOrEqual(BitI1, j+NumElts))
3648           return false;
3649       }
3650     }
3651   }
3652   return true;
3653 }
3654
3655 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3656 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3657 /// <0, 0, 1, 1>
3658 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3659                                   bool HasAVX2) {
3660   unsigned NumElts = VT.getVectorNumElements();
3661
3662   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3663          "Unsupported vector type for unpckh");
3664
3665   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3666       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3667     return false;
3668
3669   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3670   // FIXME: Need a better way to get rid of this, there's no latency difference
3671   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3672   // the former later. We should also remove the "_undef" special mask.
3673   if (NumElts == 4 && VT.getSizeInBits() == 256)
3674     return false;
3675
3676   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3677   // independently on 128-bit lanes.
3678   unsigned NumLanes = VT.getSizeInBits()/128;
3679   unsigned NumLaneElts = NumElts/NumLanes;
3680
3681   for (unsigned l = 0; l != NumLanes; ++l) {
3682     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3683          i != (l+1)*NumLaneElts;
3684          i += 2, ++j) {
3685       int BitI  = Mask[i];
3686       int BitI1 = Mask[i+1];
3687
3688       if (!isUndefOrEqual(BitI, j))
3689         return false;
3690       if (!isUndefOrEqual(BitI1, j))
3691         return false;
3692     }
3693   }
3694
3695   return true;
3696 }
3697
3698 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3699 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3700 /// <2, 2, 3, 3>
3701 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3702   unsigned NumElts = VT.getVectorNumElements();
3703
3704   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3705          "Unsupported vector type for unpckh");
3706
3707   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3708       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3709     return false;
3710
3711   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3712   // independently on 128-bit lanes.
3713   unsigned NumLanes = VT.getSizeInBits()/128;
3714   unsigned NumLaneElts = NumElts/NumLanes;
3715
3716   for (unsigned l = 0; l != NumLanes; ++l) {
3717     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3718          i != (l+1)*NumLaneElts; i += 2, ++j) {
3719       int BitI  = Mask[i];
3720       int BitI1 = Mask[i+1];
3721       if (!isUndefOrEqual(BitI, j))
3722         return false;
3723       if (!isUndefOrEqual(BitI1, j))
3724         return false;
3725     }
3726   }
3727   return true;
3728 }
3729
3730 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3731 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3732 /// MOVSD, and MOVD, i.e. setting the lowest element.
3733 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3734   if (VT.getVectorElementType().getSizeInBits() < 32)
3735     return false;
3736   if (!VT.is128BitVector())
3737     return false;
3738
3739   unsigned NumElts = VT.getVectorNumElements();
3740
3741   if (!isUndefOrEqual(Mask[0], NumElts))
3742     return false;
3743
3744   for (unsigned i = 1; i != NumElts; ++i)
3745     if (!isUndefOrEqual(Mask[i], i))
3746       return false;
3747
3748   return true;
3749 }
3750
3751 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3752 /// as permutations between 128-bit chunks or halves. As an example: this
3753 /// shuffle bellow:
3754 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3755 /// The first half comes from the second half of V1 and the second half from the
3756 /// the second half of V2.
3757 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3758   if (!HasAVX || !VT.is256BitVector())
3759     return false;
3760
3761   // The shuffle result is divided into half A and half B. In total the two
3762   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3763   // B must come from C, D, E or F.
3764   unsigned HalfSize = VT.getVectorNumElements()/2;
3765   bool MatchA = false, MatchB = false;
3766
3767   // Check if A comes from one of C, D, E, F.
3768   for (unsigned Half = 0; Half != 4; ++Half) {
3769     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3770       MatchA = true;
3771       break;
3772     }
3773   }
3774
3775   // Check if B comes from one of C, D, E, F.
3776   for (unsigned Half = 0; Half != 4; ++Half) {
3777     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3778       MatchB = true;
3779       break;
3780     }
3781   }
3782
3783   return MatchA && MatchB;
3784 }
3785
3786 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3787 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3788 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3789   EVT VT = SVOp->getValueType(0);
3790
3791   unsigned HalfSize = VT.getVectorNumElements()/2;
3792
3793   unsigned FstHalf = 0, SndHalf = 0;
3794   for (unsigned i = 0; i < HalfSize; ++i) {
3795     if (SVOp->getMaskElt(i) > 0) {
3796       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3797       break;
3798     }
3799   }
3800   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3801     if (SVOp->getMaskElt(i) > 0) {
3802       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3803       break;
3804     }
3805   }
3806
3807   return (FstHalf | (SndHalf << 4));
3808 }
3809
3810 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3811 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3812 /// Note that VPERMIL mask matching is different depending whether theunderlying
3813 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3814 /// to the same elements of the low, but to the higher half of the source.
3815 /// In VPERMILPD the two lanes could be shuffled independently of each other
3816 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3817 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3818   if (!HasAVX)
3819     return false;
3820
3821   unsigned NumElts = VT.getVectorNumElements();
3822   // Only match 256-bit with 32/64-bit types
3823   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3824     return false;
3825
3826   unsigned NumLanes = VT.getSizeInBits()/128;
3827   unsigned LaneSize = NumElts/NumLanes;
3828   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3829     for (unsigned i = 0; i != LaneSize; ++i) {
3830       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3831         return false;
3832       if (NumElts != 8 || l == 0)
3833         continue;
3834       // VPERMILPS handling
3835       if (Mask[i] < 0)
3836         continue;
3837       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3838         return false;
3839     }
3840   }
3841
3842   return true;
3843 }
3844
3845 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3846 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3847 /// element of vector 2 and the other elements to come from vector 1 in order.
3848 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3849                                bool V2IsSplat = false, bool V2IsUndef = false) {
3850   if (!VT.is128BitVector())
3851     return false;
3852
3853   unsigned NumOps = VT.getVectorNumElements();
3854   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3855     return false;
3856
3857   if (!isUndefOrEqual(Mask[0], 0))
3858     return false;
3859
3860   for (unsigned i = 1; i != NumOps; ++i)
3861     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3862           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3863           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3864       return false;
3865
3866   return true;
3867 }
3868
3869 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3870 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3871 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3872 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3873                            const X86Subtarget *Subtarget) {
3874   if (!Subtarget->hasSSE3())
3875     return false;
3876
3877   unsigned NumElems = VT.getVectorNumElements();
3878
3879   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3880       (VT.getSizeInBits() == 256 && NumElems != 8))
3881     return false;
3882
3883   // "i+1" is the value the indexed mask element must have
3884   for (unsigned i = 0; i != NumElems; i += 2)
3885     if (!isUndefOrEqual(Mask[i], i+1) ||
3886         !isUndefOrEqual(Mask[i+1], i+1))
3887       return false;
3888
3889   return true;
3890 }
3891
3892 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3894 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3895 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3896                            const X86Subtarget *Subtarget) {
3897   if (!Subtarget->hasSSE3())
3898     return false;
3899
3900   unsigned NumElems = VT.getVectorNumElements();
3901
3902   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3903       (VT.getSizeInBits() == 256 && NumElems != 8))
3904     return false;
3905
3906   // "i" is the value the indexed mask element must have
3907   for (unsigned i = 0; i != NumElems; i += 2)
3908     if (!isUndefOrEqual(Mask[i], i) ||
3909         !isUndefOrEqual(Mask[i+1], i))
3910       return false;
3911
3912   return true;
3913 }
3914
3915 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to 256-bit
3917 /// version of MOVDDUP.
3918 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3919   if (!HasAVX || !VT.is256BitVector())
3920     return false;
3921
3922   unsigned NumElts = VT.getVectorNumElements();
3923   if (NumElts != 4)
3924     return false;
3925
3926   for (unsigned i = 0; i != NumElts/2; ++i)
3927     if (!isUndefOrEqual(Mask[i], 0))
3928       return false;
3929   for (unsigned i = NumElts/2; i != NumElts; ++i)
3930     if (!isUndefOrEqual(Mask[i], NumElts/2))
3931       return false;
3932   return true;
3933 }
3934
3935 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to 128-bit
3937 /// version of MOVDDUP.
3938 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3939   if (!VT.is128BitVector())
3940     return false;
3941
3942   unsigned e = VT.getVectorNumElements() / 2;
3943   for (unsigned i = 0; i != e; ++i)
3944     if (!isUndefOrEqual(Mask[i], i))
3945       return false;
3946   for (unsigned i = 0; i != e; ++i)
3947     if (!isUndefOrEqual(Mask[e+i], i))
3948       return false;
3949   return true;
3950 }
3951
3952 /// isVEXTRACTF128Index - Return true if the specified
3953 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3954 /// suitable for input to VEXTRACTF128.
3955 bool X86::isVEXTRACTF128Index(SDNode *N) {
3956   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3957     return false;
3958
3959   // The index should be aligned on a 128-bit boundary.
3960   uint64_t Index =
3961     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3962
3963   unsigned VL = N->getValueType(0).getVectorNumElements();
3964   unsigned VBits = N->getValueType(0).getSizeInBits();
3965   unsigned ElSize = VBits / VL;
3966   bool Result = (Index * ElSize) % 128 == 0;
3967
3968   return Result;
3969 }
3970
3971 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3972 /// operand specifies a subvector insert that is suitable for input to
3973 /// VINSERTF128.
3974 bool X86::isVINSERTF128Index(SDNode *N) {
3975   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3976     return false;
3977
3978   // The index should be aligned on a 128-bit boundary.
3979   uint64_t Index =
3980     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3981
3982   unsigned VL = N->getValueType(0).getVectorNumElements();
3983   unsigned VBits = N->getValueType(0).getSizeInBits();
3984   unsigned ElSize = VBits / VL;
3985   bool Result = (Index * ElSize) % 128 == 0;
3986
3987   return Result;
3988 }
3989
3990 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3991 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3992 /// Handles 128-bit and 256-bit.
3993 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3994   EVT VT = N->getValueType(0);
3995
3996   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3997          "Unsupported vector type for PSHUF/SHUFP");
3998
3999   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4000   // independently on 128-bit lanes.
4001   unsigned NumElts = VT.getVectorNumElements();
4002   unsigned NumLanes = VT.getSizeInBits()/128;
4003   unsigned NumLaneElts = NumElts/NumLanes;
4004
4005   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4006          "Only supports 2 or 4 elements per lane");
4007
4008   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4009   unsigned Mask = 0;
4010   for (unsigned i = 0; i != NumElts; ++i) {
4011     int Elt = N->getMaskElt(i);
4012     if (Elt < 0) continue;
4013     Elt &= NumLaneElts - 1;
4014     unsigned ShAmt = (i << Shift) % 8;
4015     Mask |= Elt << ShAmt;
4016   }
4017
4018   return Mask;
4019 }
4020
4021 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4022 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4023 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4024   EVT VT = N->getValueType(0);
4025
4026   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4027          "Unsupported vector type for PSHUFHW");
4028
4029   unsigned NumElts = VT.getVectorNumElements();
4030
4031   unsigned Mask = 0;
4032   for (unsigned l = 0; l != NumElts; l += 8) {
4033     // 8 nodes per lane, but we only care about the last 4.
4034     for (unsigned i = 0; i < 4; ++i) {
4035       int Elt = N->getMaskElt(l+i+4);
4036       if (Elt < 0) continue;
4037       Elt &= 0x3; // only 2-bits.
4038       Mask |= Elt << (i * 2);
4039     }
4040   }
4041
4042   return Mask;
4043 }
4044
4045 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4046 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4047 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4048   EVT VT = N->getValueType(0);
4049
4050   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4051          "Unsupported vector type for PSHUFHW");
4052
4053   unsigned NumElts = VT.getVectorNumElements();
4054
4055   unsigned Mask = 0;
4056   for (unsigned l = 0; l != NumElts; l += 8) {
4057     // 8 nodes per lane, but we only care about the first 4.
4058     for (unsigned i = 0; i < 4; ++i) {
4059       int Elt = N->getMaskElt(l+i);
4060       if (Elt < 0) continue;
4061       Elt &= 0x3; // only 2-bits
4062       Mask |= Elt << (i * 2);
4063     }
4064   }
4065
4066   return Mask;
4067 }
4068
4069 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4070 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4071 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4072   EVT VT = SVOp->getValueType(0);
4073   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4074
4075   unsigned NumElts = VT.getVectorNumElements();
4076   unsigned NumLanes = VT.getSizeInBits()/128;
4077   unsigned NumLaneElts = NumElts/NumLanes;
4078
4079   int Val = 0;
4080   unsigned i;
4081   for (i = 0; i != NumElts; ++i) {
4082     Val = SVOp->getMaskElt(i);
4083     if (Val >= 0)
4084       break;
4085   }
4086   if (Val >= (int)NumElts)
4087     Val -= NumElts - NumLaneElts;
4088
4089   assert(Val - i > 0 && "PALIGNR imm should be positive");
4090   return (Val - i) * EltSize;
4091 }
4092
4093 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4094 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4095 /// instructions.
4096 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4097   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4098     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4099
4100   uint64_t Index =
4101     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4102
4103   EVT VecVT = N->getOperand(0).getValueType();
4104   EVT ElVT = VecVT.getVectorElementType();
4105
4106   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4107   return Index / NumElemsPerChunk;
4108 }
4109
4110 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4111 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4112 /// instructions.
4113 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4114   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4115     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4116
4117   uint64_t Index =
4118     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4119
4120   EVT VecVT = N->getValueType(0);
4121   EVT ElVT = VecVT.getVectorElementType();
4122
4123   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4124   return Index / NumElemsPerChunk;
4125 }
4126
4127 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4128 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4129 /// Handles 256-bit.
4130 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4131   EVT VT = N->getValueType(0);
4132
4133   unsigned NumElts = VT.getVectorNumElements();
4134
4135   assert((VT.is256BitVector() && NumElts == 4) &&
4136          "Unsupported vector type for VPERMQ/VPERMPD");
4137
4138   unsigned Mask = 0;
4139   for (unsigned i = 0; i != NumElts; ++i) {
4140     int Elt = N->getMaskElt(i);
4141     if (Elt < 0)
4142       continue;
4143     Mask |= Elt << (i*2);
4144   }
4145
4146   return Mask;
4147 }
4148 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4149 /// constant +0.0.
4150 bool X86::isZeroNode(SDValue Elt) {
4151   return ((isa<ConstantSDNode>(Elt) &&
4152            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4153           (isa<ConstantFPSDNode>(Elt) &&
4154            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4155 }
4156
4157 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4158 /// their permute mask.
4159 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4160                                     SelectionDAG &DAG) {
4161   EVT VT = SVOp->getValueType(0);
4162   unsigned NumElems = VT.getVectorNumElements();
4163   SmallVector<int, 8> MaskVec;
4164
4165   for (unsigned i = 0; i != NumElems; ++i) {
4166     int Idx = SVOp->getMaskElt(i);
4167     if (Idx >= 0) {
4168       if (Idx < (int)NumElems)
4169         Idx += NumElems;
4170       else
4171         Idx -= NumElems;
4172     }
4173     MaskVec.push_back(Idx);
4174   }
4175   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4176                               SVOp->getOperand(0), &MaskVec[0]);
4177 }
4178
4179 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4180 /// match movhlps. The lower half elements should come from upper half of
4181 /// V1 (and in order), and the upper half elements should come from the upper
4182 /// half of V2 (and in order).
4183 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4184   if (!VT.is128BitVector())
4185     return false;
4186   if (VT.getVectorNumElements() != 4)
4187     return false;
4188   for (unsigned i = 0, e = 2; i != e; ++i)
4189     if (!isUndefOrEqual(Mask[i], i+2))
4190       return false;
4191   for (unsigned i = 2; i != 4; ++i)
4192     if (!isUndefOrEqual(Mask[i], i+4))
4193       return false;
4194   return true;
4195 }
4196
4197 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4198 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4199 /// required.
4200 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4201   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4202     return false;
4203   N = N->getOperand(0).getNode();
4204   if (!ISD::isNON_EXTLoad(N))
4205     return false;
4206   if (LD)
4207     *LD = cast<LoadSDNode>(N);
4208   return true;
4209 }
4210
4211 // Test whether the given value is a vector value which will be legalized
4212 // into a load.
4213 static bool WillBeConstantPoolLoad(SDNode *N) {
4214   if (N->getOpcode() != ISD::BUILD_VECTOR)
4215     return false;
4216
4217   // Check for any non-constant elements.
4218   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4219     switch (N->getOperand(i).getNode()->getOpcode()) {
4220     case ISD::UNDEF:
4221     case ISD::ConstantFP:
4222     case ISD::Constant:
4223       break;
4224     default:
4225       return false;
4226     }
4227
4228   // Vectors of all-zeros and all-ones are materialized with special
4229   // instructions rather than being loaded.
4230   return !ISD::isBuildVectorAllZeros(N) &&
4231          !ISD::isBuildVectorAllOnes(N);
4232 }
4233
4234 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4235 /// match movlp{s|d}. The lower half elements should come from lower half of
4236 /// V1 (and in order), and the upper half elements should come from the upper
4237 /// half of V2 (and in order). And since V1 will become the source of the
4238 /// MOVLP, it must be either a vector load or a scalar load to vector.
4239 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4240                                ArrayRef<int> Mask, EVT VT) {
4241   if (!VT.is128BitVector())
4242     return false;
4243
4244   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4245     return false;
4246   // Is V2 is a vector load, don't do this transformation. We will try to use
4247   // load folding shufps op.
4248   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4249     return false;
4250
4251   unsigned NumElems = VT.getVectorNumElements();
4252
4253   if (NumElems != 2 && NumElems != 4)
4254     return false;
4255   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4256     if (!isUndefOrEqual(Mask[i], i))
4257       return false;
4258   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4259     if (!isUndefOrEqual(Mask[i], i+NumElems))
4260       return false;
4261   return true;
4262 }
4263
4264 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4265 /// all the same.
4266 static bool isSplatVector(SDNode *N) {
4267   if (N->getOpcode() != ISD::BUILD_VECTOR)
4268     return false;
4269
4270   SDValue SplatValue = N->getOperand(0);
4271   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4272     if (N->getOperand(i) != SplatValue)
4273       return false;
4274   return true;
4275 }
4276
4277 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4278 /// to an zero vector.
4279 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4280 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4281   SDValue V1 = N->getOperand(0);
4282   SDValue V2 = N->getOperand(1);
4283   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4284   for (unsigned i = 0; i != NumElems; ++i) {
4285     int Idx = N->getMaskElt(i);
4286     if (Idx >= (int)NumElems) {
4287       unsigned Opc = V2.getOpcode();
4288       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4289         continue;
4290       if (Opc != ISD::BUILD_VECTOR ||
4291           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4292         return false;
4293     } else if (Idx >= 0) {
4294       unsigned Opc = V1.getOpcode();
4295       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4296         continue;
4297       if (Opc != ISD::BUILD_VECTOR ||
4298           !X86::isZeroNode(V1.getOperand(Idx)))
4299         return false;
4300     }
4301   }
4302   return true;
4303 }
4304
4305 /// getZeroVector - Returns a vector of specified type with all zero elements.
4306 ///
4307 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4308                              SelectionDAG &DAG, DebugLoc dl) {
4309   assert(VT.isVector() && "Expected a vector type");
4310   unsigned Size = VT.getSizeInBits();
4311
4312   // Always build SSE zero vectors as <4 x i32> bitcasted
4313   // to their dest type. This ensures they get CSE'd.
4314   SDValue Vec;
4315   if (Size == 128) {  // SSE
4316     if (Subtarget->hasSSE2()) {  // SSE2
4317       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4318       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4319     } else { // SSE1
4320       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4321       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4322     }
4323   } else if (Size == 256) { // AVX
4324     if (Subtarget->hasAVX2()) { // AVX2
4325       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4326       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4328     } else {
4329       // 256-bit logic and arithmetic instructions in AVX are all
4330       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4331       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4332       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4333       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4334     }
4335   } else
4336     llvm_unreachable("Unexpected vector type");
4337
4338   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4339 }
4340
4341 /// getOnesVector - Returns a vector of specified type with all bits set.
4342 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4343 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4344 /// Then bitcast to their original type, ensuring they get CSE'd.
4345 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4346                              DebugLoc dl) {
4347   assert(VT.isVector() && "Expected a vector type");
4348   unsigned Size = VT.getSizeInBits();
4349
4350   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4351   SDValue Vec;
4352   if (Size == 256) {
4353     if (HasAVX2) { // AVX2
4354       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4355       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4356     } else { // AVX
4357       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4358       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4359     }
4360   } else if (Size == 128) {
4361     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4362   } else
4363     llvm_unreachable("Unexpected vector type");
4364
4365   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4366 }
4367
4368 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4369 /// that point to V2 points to its first element.
4370 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4371   for (unsigned i = 0; i != NumElems; ++i) {
4372     if (Mask[i] > (int)NumElems) {
4373       Mask[i] = NumElems;
4374     }
4375   }
4376 }
4377
4378 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4379 /// operation of specified width.
4380 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4381                        SDValue V2) {
4382   unsigned NumElems = VT.getVectorNumElements();
4383   SmallVector<int, 8> Mask;
4384   Mask.push_back(NumElems);
4385   for (unsigned i = 1; i != NumElems; ++i)
4386     Mask.push_back(i);
4387   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4388 }
4389
4390 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4391 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4392                           SDValue V2) {
4393   unsigned NumElems = VT.getVectorNumElements();
4394   SmallVector<int, 8> Mask;
4395   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4396     Mask.push_back(i);
4397     Mask.push_back(i + NumElems);
4398   }
4399   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4400 }
4401
4402 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4403 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4404                           SDValue V2) {
4405   unsigned NumElems = VT.getVectorNumElements();
4406   SmallVector<int, 8> Mask;
4407   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4408     Mask.push_back(i + Half);
4409     Mask.push_back(i + NumElems + Half);
4410   }
4411   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4412 }
4413
4414 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4415 // a generic shuffle instruction because the target has no such instructions.
4416 // Generate shuffles which repeat i16 and i8 several times until they can be
4417 // represented by v4f32 and then be manipulated by target suported shuffles.
4418 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4419   EVT VT = V.getValueType();
4420   int NumElems = VT.getVectorNumElements();
4421   DebugLoc dl = V.getDebugLoc();
4422
4423   while (NumElems > 4) {
4424     if (EltNo < NumElems/2) {
4425       V = getUnpackl(DAG, dl, VT, V, V);
4426     } else {
4427       V = getUnpackh(DAG, dl, VT, V, V);
4428       EltNo -= NumElems/2;
4429     }
4430     NumElems >>= 1;
4431   }
4432   return V;
4433 }
4434
4435 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4436 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4437   EVT VT = V.getValueType();
4438   DebugLoc dl = V.getDebugLoc();
4439   unsigned Size = VT.getSizeInBits();
4440
4441   if (Size == 128) {
4442     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4443     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4444     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4445                              &SplatMask[0]);
4446   } else if (Size == 256) {
4447     // To use VPERMILPS to splat scalars, the second half of indicies must
4448     // refer to the higher part, which is a duplication of the lower one,
4449     // because VPERMILPS can only handle in-lane permutations.
4450     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4451                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4452
4453     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4454     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4455                              &SplatMask[0]);
4456   } else
4457     llvm_unreachable("Vector size not supported");
4458
4459   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4460 }
4461
4462 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4463 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4464   EVT SrcVT = SV->getValueType(0);
4465   SDValue V1 = SV->getOperand(0);
4466   DebugLoc dl = SV->getDebugLoc();
4467
4468   int EltNo = SV->getSplatIndex();
4469   int NumElems = SrcVT.getVectorNumElements();
4470   unsigned Size = SrcVT.getSizeInBits();
4471
4472   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4473           "Unknown how to promote splat for type");
4474
4475   // Extract the 128-bit part containing the splat element and update
4476   // the splat element index when it refers to the higher register.
4477   if (Size == 256) {
4478     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4479     if (EltNo >= NumElems/2)
4480       EltNo -= NumElems/2;
4481   }
4482
4483   // All i16 and i8 vector types can't be used directly by a generic shuffle
4484   // instruction because the target has no such instruction. Generate shuffles
4485   // which repeat i16 and i8 several times until they fit in i32, and then can
4486   // be manipulated by target suported shuffles.
4487   EVT EltVT = SrcVT.getVectorElementType();
4488   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4489     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4490
4491   // Recreate the 256-bit vector and place the same 128-bit vector
4492   // into the low and high part. This is necessary because we want
4493   // to use VPERM* to shuffle the vectors
4494   if (Size == 256) {
4495     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4496   }
4497
4498   return getLegalSplat(DAG, V1, EltNo);
4499 }
4500
4501 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4502 /// vector of zero or undef vector.  This produces a shuffle where the low
4503 /// element of V2 is swizzled into the zero/undef vector, landing at element
4504 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4505 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4506                                            bool IsZero,
4507                                            const X86Subtarget *Subtarget,
4508                                            SelectionDAG &DAG) {
4509   EVT VT = V2.getValueType();
4510   SDValue V1 = IsZero
4511     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4512   unsigned NumElems = VT.getVectorNumElements();
4513   SmallVector<int, 16> MaskVec;
4514   for (unsigned i = 0; i != NumElems; ++i)
4515     // If this is the insertion idx, put the low elt of V2 here.
4516     MaskVec.push_back(i == Idx ? NumElems : i);
4517   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4518 }
4519
4520 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4521 /// target specific opcode. Returns true if the Mask could be calculated.
4522 /// Sets IsUnary to true if only uses one source.
4523 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4524                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4525   unsigned NumElems = VT.getVectorNumElements();
4526   SDValue ImmN;
4527
4528   IsUnary = false;
4529   switch(N->getOpcode()) {
4530   case X86ISD::SHUFP:
4531     ImmN = N->getOperand(N->getNumOperands()-1);
4532     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4533     break;
4534   case X86ISD::UNPCKH:
4535     DecodeUNPCKHMask(VT, Mask);
4536     break;
4537   case X86ISD::UNPCKL:
4538     DecodeUNPCKLMask(VT, Mask);
4539     break;
4540   case X86ISD::MOVHLPS:
4541     DecodeMOVHLPSMask(NumElems, Mask);
4542     break;
4543   case X86ISD::MOVLHPS:
4544     DecodeMOVLHPSMask(NumElems, Mask);
4545     break;
4546   case X86ISD::PSHUFD:
4547   case X86ISD::VPERMILP:
4548     ImmN = N->getOperand(N->getNumOperands()-1);
4549     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4550     IsUnary = true;
4551     break;
4552   case X86ISD::PSHUFHW:
4553     ImmN = N->getOperand(N->getNumOperands()-1);
4554     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4555     IsUnary = true;
4556     break;
4557   case X86ISD::PSHUFLW:
4558     ImmN = N->getOperand(N->getNumOperands()-1);
4559     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4560     IsUnary = true;
4561     break;
4562   case X86ISD::VPERMI:
4563     ImmN = N->getOperand(N->getNumOperands()-1);
4564     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4565     IsUnary = true;
4566     break;
4567   case X86ISD::MOVSS:
4568   case X86ISD::MOVSD: {
4569     // The index 0 always comes from the first element of the second source,
4570     // this is why MOVSS and MOVSD are used in the first place. The other
4571     // elements come from the other positions of the first source vector
4572     Mask.push_back(NumElems);
4573     for (unsigned i = 1; i != NumElems; ++i) {
4574       Mask.push_back(i);
4575     }
4576     break;
4577   }
4578   case X86ISD::VPERM2X128:
4579     ImmN = N->getOperand(N->getNumOperands()-1);
4580     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4581     if (Mask.empty()) return false;
4582     break;
4583   case X86ISD::MOVDDUP:
4584   case X86ISD::MOVLHPD:
4585   case X86ISD::MOVLPD:
4586   case X86ISD::MOVLPS:
4587   case X86ISD::MOVSHDUP:
4588   case X86ISD::MOVSLDUP:
4589   case X86ISD::PALIGN:
4590     // Not yet implemented
4591     return false;
4592   default: llvm_unreachable("unknown target shuffle node");
4593   }
4594
4595   return true;
4596 }
4597
4598 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4599 /// element of the result of the vector shuffle.
4600 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4601                                    unsigned Depth) {
4602   if (Depth == 6)
4603     return SDValue();  // Limit search depth.
4604
4605   SDValue V = SDValue(N, 0);
4606   EVT VT = V.getValueType();
4607   unsigned Opcode = V.getOpcode();
4608
4609   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4610   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4611     int Elt = SV->getMaskElt(Index);
4612
4613     if (Elt < 0)
4614       return DAG.getUNDEF(VT.getVectorElementType());
4615
4616     unsigned NumElems = VT.getVectorNumElements();
4617     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4618                                          : SV->getOperand(1);
4619     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4620   }
4621
4622   // Recurse into target specific vector shuffles to find scalars.
4623   if (isTargetShuffle(Opcode)) {
4624     MVT ShufVT = V.getValueType().getSimpleVT();
4625     unsigned NumElems = ShufVT.getVectorNumElements();
4626     SmallVector<int, 16> ShuffleMask;
4627     SDValue ImmN;
4628     bool IsUnary;
4629
4630     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4631       return SDValue();
4632
4633     int Elt = ShuffleMask[Index];
4634     if (Elt < 0)
4635       return DAG.getUNDEF(ShufVT.getVectorElementType());
4636
4637     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4638                                          : N->getOperand(1);
4639     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4640                                Depth+1);
4641   }
4642
4643   // Actual nodes that may contain scalar elements
4644   if (Opcode == ISD::BITCAST) {
4645     V = V.getOperand(0);
4646     EVT SrcVT = V.getValueType();
4647     unsigned NumElems = VT.getVectorNumElements();
4648
4649     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4650       return SDValue();
4651   }
4652
4653   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4654     return (Index == 0) ? V.getOperand(0)
4655                         : DAG.getUNDEF(VT.getVectorElementType());
4656
4657   if (V.getOpcode() == ISD::BUILD_VECTOR)
4658     return V.getOperand(Index);
4659
4660   return SDValue();
4661 }
4662
4663 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4664 /// shuffle operation which come from a consecutively from a zero. The
4665 /// search can start in two different directions, from left or right.
4666 static
4667 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4668                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4669   unsigned i;
4670   for (i = 0; i != NumElems; ++i) {
4671     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4672     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4673     if (!(Elt.getNode() &&
4674          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4675       break;
4676   }
4677
4678   return i;
4679 }
4680
4681 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4682 /// correspond consecutively to elements from one of the vector operands,
4683 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4684 static
4685 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4686                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4687                               unsigned NumElems, unsigned &OpNum) {
4688   bool SeenV1 = false;
4689   bool SeenV2 = false;
4690
4691   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4692     int Idx = SVOp->getMaskElt(i);
4693     // Ignore undef indicies
4694     if (Idx < 0)
4695       continue;
4696
4697     if (Idx < (int)NumElems)
4698       SeenV1 = true;
4699     else
4700       SeenV2 = true;
4701
4702     // Only accept consecutive elements from the same vector
4703     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4704       return false;
4705   }
4706
4707   OpNum = SeenV1 ? 0 : 1;
4708   return true;
4709 }
4710
4711 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4712 /// logical left shift of a vector.
4713 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4714                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4715   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4716   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4717               false /* check zeros from right */, DAG);
4718   unsigned OpSrc;
4719
4720   if (!NumZeros)
4721     return false;
4722
4723   // Considering the elements in the mask that are not consecutive zeros,
4724   // check if they consecutively come from only one of the source vectors.
4725   //
4726   //               V1 = {X, A, B, C}     0
4727   //                         \  \  \    /
4728   //   vector_shuffle V1, V2 <1, 2, 3, X>
4729   //
4730   if (!isShuffleMaskConsecutive(SVOp,
4731             0,                   // Mask Start Index
4732             NumElems-NumZeros,   // Mask End Index(exclusive)
4733             NumZeros,            // Where to start looking in the src vector
4734             NumElems,            // Number of elements in vector
4735             OpSrc))              // Which source operand ?
4736     return false;
4737
4738   isLeft = false;
4739   ShAmt = NumZeros;
4740   ShVal = SVOp->getOperand(OpSrc);
4741   return true;
4742 }
4743
4744 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4745 /// logical left shift of a vector.
4746 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4747                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4748   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4749   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4750               true /* check zeros from left */, DAG);
4751   unsigned OpSrc;
4752
4753   if (!NumZeros)
4754     return false;
4755
4756   // Considering the elements in the mask that are not consecutive zeros,
4757   // check if they consecutively come from only one of the source vectors.
4758   //
4759   //                           0    { A, B, X, X } = V2
4760   //                          / \    /  /
4761   //   vector_shuffle V1, V2 <X, X, 4, 5>
4762   //
4763   if (!isShuffleMaskConsecutive(SVOp,
4764             NumZeros,     // Mask Start Index
4765             NumElems,     // Mask End Index(exclusive)
4766             0,            // Where to start looking in the src vector
4767             NumElems,     // Number of elements in vector
4768             OpSrc))       // Which source operand ?
4769     return false;
4770
4771   isLeft = true;
4772   ShAmt = NumZeros;
4773   ShVal = SVOp->getOperand(OpSrc);
4774   return true;
4775 }
4776
4777 /// isVectorShift - Returns true if the shuffle can be implemented as a
4778 /// logical left or right shift of a vector.
4779 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4780                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4781   // Although the logic below support any bitwidth size, there are no
4782   // shift instructions which handle more than 128-bit vectors.
4783   if (!SVOp->getValueType(0).is128BitVector())
4784     return false;
4785
4786   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4787       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4788     return true;
4789
4790   return false;
4791 }
4792
4793 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4794 ///
4795 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4796                                        unsigned NumNonZero, unsigned NumZero,
4797                                        SelectionDAG &DAG,
4798                                        const X86Subtarget* Subtarget,
4799                                        const TargetLowering &TLI) {
4800   if (NumNonZero > 8)
4801     return SDValue();
4802
4803   DebugLoc dl = Op.getDebugLoc();
4804   SDValue V(0, 0);
4805   bool First = true;
4806   for (unsigned i = 0; i < 16; ++i) {
4807     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4808     if (ThisIsNonZero && First) {
4809       if (NumZero)
4810         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4811       else
4812         V = DAG.getUNDEF(MVT::v8i16);
4813       First = false;
4814     }
4815
4816     if ((i & 1) != 0) {
4817       SDValue ThisElt(0, 0), LastElt(0, 0);
4818       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4819       if (LastIsNonZero) {
4820         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4821                               MVT::i16, Op.getOperand(i-1));
4822       }
4823       if (ThisIsNonZero) {
4824         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4825         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4826                               ThisElt, DAG.getConstant(8, MVT::i8));
4827         if (LastIsNonZero)
4828           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4829       } else
4830         ThisElt = LastElt;
4831
4832       if (ThisElt.getNode())
4833         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4834                         DAG.getIntPtrConstant(i/2));
4835     }
4836   }
4837
4838   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4839 }
4840
4841 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4842 ///
4843 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4844                                      unsigned NumNonZero, unsigned NumZero,
4845                                      SelectionDAG &DAG,
4846                                      const X86Subtarget* Subtarget,
4847                                      const TargetLowering &TLI) {
4848   if (NumNonZero > 4)
4849     return SDValue();
4850
4851   DebugLoc dl = Op.getDebugLoc();
4852   SDValue V(0, 0);
4853   bool First = true;
4854   for (unsigned i = 0; i < 8; ++i) {
4855     bool isNonZero = (NonZeros & (1 << i)) != 0;
4856     if (isNonZero) {
4857       if (First) {
4858         if (NumZero)
4859           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4860         else
4861           V = DAG.getUNDEF(MVT::v8i16);
4862         First = false;
4863       }
4864       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4865                       MVT::v8i16, V, Op.getOperand(i),
4866                       DAG.getIntPtrConstant(i));
4867     }
4868   }
4869
4870   return V;
4871 }
4872
4873 /// getVShift - Return a vector logical shift node.
4874 ///
4875 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4876                          unsigned NumBits, SelectionDAG &DAG,
4877                          const TargetLowering &TLI, DebugLoc dl) {
4878   assert(VT.is128BitVector() && "Unknown type for VShift");
4879   EVT ShVT = MVT::v2i64;
4880   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4881   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4882   return DAG.getNode(ISD::BITCAST, dl, VT,
4883                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4884                              DAG.getConstant(NumBits,
4885                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4886 }
4887
4888 SDValue
4889 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4890                                           SelectionDAG &DAG) const {
4891
4892   // Check if the scalar load can be widened into a vector load. And if
4893   // the address is "base + cst" see if the cst can be "absorbed" into
4894   // the shuffle mask.
4895   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4896     SDValue Ptr = LD->getBasePtr();
4897     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4898       return SDValue();
4899     EVT PVT = LD->getValueType(0);
4900     if (PVT != MVT::i32 && PVT != MVT::f32)
4901       return SDValue();
4902
4903     int FI = -1;
4904     int64_t Offset = 0;
4905     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4906       FI = FINode->getIndex();
4907       Offset = 0;
4908     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4909                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4910       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4911       Offset = Ptr.getConstantOperandVal(1);
4912       Ptr = Ptr.getOperand(0);
4913     } else {
4914       return SDValue();
4915     }
4916
4917     // FIXME: 256-bit vector instructions don't require a strict alignment,
4918     // improve this code to support it better.
4919     unsigned RequiredAlign = VT.getSizeInBits()/8;
4920     SDValue Chain = LD->getChain();
4921     // Make sure the stack object alignment is at least 16 or 32.
4922     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4923     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4924       if (MFI->isFixedObjectIndex(FI)) {
4925         // Can't change the alignment. FIXME: It's possible to compute
4926         // the exact stack offset and reference FI + adjust offset instead.
4927         // If someone *really* cares about this. That's the way to implement it.
4928         return SDValue();
4929       } else {
4930         MFI->setObjectAlignment(FI, RequiredAlign);
4931       }
4932     }
4933
4934     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4935     // Ptr + (Offset & ~15).
4936     if (Offset < 0)
4937       return SDValue();
4938     if ((Offset % RequiredAlign) & 3)
4939       return SDValue();
4940     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4941     if (StartOffset)
4942       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4943                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4944
4945     int EltNo = (Offset - StartOffset) >> 2;
4946     unsigned NumElems = VT.getVectorNumElements();
4947
4948     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4949     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4950                              LD->getPointerInfo().getWithOffset(StartOffset),
4951                              false, false, false, 0);
4952
4953     SmallVector<int, 8> Mask;
4954     for (unsigned i = 0; i != NumElems; ++i)
4955       Mask.push_back(EltNo);
4956
4957     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4958   }
4959
4960   return SDValue();
4961 }
4962
4963 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4964 /// vector of type 'VT', see if the elements can be replaced by a single large
4965 /// load which has the same value as a build_vector whose operands are 'elts'.
4966 ///
4967 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4968 ///
4969 /// FIXME: we'd also like to handle the case where the last elements are zero
4970 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4971 /// There's even a handy isZeroNode for that purpose.
4972 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4973                                         DebugLoc &DL, SelectionDAG &DAG) {
4974   EVT EltVT = VT.getVectorElementType();
4975   unsigned NumElems = Elts.size();
4976
4977   LoadSDNode *LDBase = NULL;
4978   unsigned LastLoadedElt = -1U;
4979
4980   // For each element in the initializer, see if we've found a load or an undef.
4981   // If we don't find an initial load element, or later load elements are
4982   // non-consecutive, bail out.
4983   for (unsigned i = 0; i < NumElems; ++i) {
4984     SDValue Elt = Elts[i];
4985
4986     if (!Elt.getNode() ||
4987         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4988       return SDValue();
4989     if (!LDBase) {
4990       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4991         return SDValue();
4992       LDBase = cast<LoadSDNode>(Elt.getNode());
4993       LastLoadedElt = i;
4994       continue;
4995     }
4996     if (Elt.getOpcode() == ISD::UNDEF)
4997       continue;
4998
4999     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5000     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5001       return SDValue();
5002     LastLoadedElt = i;
5003   }
5004
5005   // If we have found an entire vector of loads and undefs, then return a large
5006   // load of the entire vector width starting at the base pointer.  If we found
5007   // consecutive loads for the low half, generate a vzext_load node.
5008   if (LastLoadedElt == NumElems - 1) {
5009     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5010       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5011                          LDBase->getPointerInfo(),
5012                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5013                          LDBase->isInvariant(), 0);
5014     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5015                        LDBase->getPointerInfo(),
5016                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5017                        LDBase->isInvariant(), LDBase->getAlignment());
5018   }
5019   if (NumElems == 4 && LastLoadedElt == 1 &&
5020       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5021     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5022     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5023     SDValue ResNode =
5024         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5025                                 LDBase->getPointerInfo(),
5026                                 LDBase->getAlignment(),
5027                                 false/*isVolatile*/, true/*ReadMem*/,
5028                                 false/*WriteMem*/);
5029
5030     // Make sure the newly-created LOAD is in the same position as LDBase in
5031     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5032     // update uses of LDBase's output chain to use the TokenFactor.
5033     if (LDBase->hasAnyUseOfValue(1)) {
5034       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5035                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5036       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5037       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5038                              SDValue(ResNode.getNode(), 1));
5039     }
5040
5041     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5042   }
5043   return SDValue();
5044 }
5045
5046 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5047 /// to generate a splat value for the following cases:
5048 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5049 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5050 /// a scalar load, or a constant.
5051 /// The VBROADCAST node is returned when a pattern is found,
5052 /// or SDValue() otherwise.
5053 SDValue
5054 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5055   if (!Subtarget->hasAVX())
5056     return SDValue();
5057
5058   EVT VT = Op.getValueType();
5059   DebugLoc dl = Op.getDebugLoc();
5060
5061   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5062          "Unsupported vector type for broadcast.");
5063
5064   SDValue Ld;
5065   bool ConstSplatVal;
5066
5067   switch (Op.getOpcode()) {
5068     default:
5069       // Unknown pattern found.
5070       return SDValue();
5071
5072     case ISD::BUILD_VECTOR: {
5073       // The BUILD_VECTOR node must be a splat.
5074       if (!isSplatVector(Op.getNode()))
5075         return SDValue();
5076
5077       Ld = Op.getOperand(0);
5078       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5079                      Ld.getOpcode() == ISD::ConstantFP);
5080
5081       // The suspected load node has several users. Make sure that all
5082       // of its users are from the BUILD_VECTOR node.
5083       // Constants may have multiple users.
5084       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5085         return SDValue();
5086       break;
5087     }
5088
5089     case ISD::VECTOR_SHUFFLE: {
5090       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5091
5092       // Shuffles must have a splat mask where the first element is
5093       // broadcasted.
5094       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5095         return SDValue();
5096
5097       SDValue Sc = Op.getOperand(0);
5098       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5099           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5100
5101         if (!Subtarget->hasAVX2())
5102           return SDValue();
5103
5104         // Use the register form of the broadcast instruction available on AVX2.
5105         if (VT.is256BitVector())
5106           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5107         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5108       }
5109
5110       Ld = Sc.getOperand(0);
5111       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5112                        Ld.getOpcode() == ISD::ConstantFP);
5113
5114       // The scalar_to_vector node and the suspected
5115       // load node must have exactly one user.
5116       // Constants may have multiple users.
5117       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5118         return SDValue();
5119       break;
5120     }
5121   }
5122
5123   bool Is256 = VT.is256BitVector();
5124
5125   // Handle the broadcasting a single constant scalar from the constant pool
5126   // into a vector. On Sandybridge it is still better to load a constant vector
5127   // from the constant pool and not to broadcast it from a scalar.
5128   if (ConstSplatVal && Subtarget->hasAVX2()) {
5129     EVT CVT = Ld.getValueType();
5130     assert(!CVT.isVector() && "Must not broadcast a vector type");
5131     unsigned ScalarSize = CVT.getSizeInBits();
5132
5133     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5134       const Constant *C = 0;
5135       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5136         C = CI->getConstantIntValue();
5137       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5138         C = CF->getConstantFPValue();
5139
5140       assert(C && "Invalid constant type");
5141
5142       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5143       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5144       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5145                        MachinePointerInfo::getConstantPool(),
5146                        false, false, false, Alignment);
5147
5148       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5149     }
5150   }
5151
5152   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5153   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5154
5155   // Handle AVX2 in-register broadcasts.
5156   if (!IsLoad && Subtarget->hasAVX2() &&
5157       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5158     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5159
5160   // The scalar source must be a normal load.
5161   if (!IsLoad)
5162     return SDValue();
5163
5164   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5165     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5166
5167   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5168   // double since there is no vbroadcastsd xmm
5169   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5170     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5171       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5172   }
5173
5174   // Unsupported broadcast.
5175   return SDValue();
5176 }
5177
5178 SDValue
5179 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5180   EVT VT = Op.getValueType();
5181
5182   // Skip if insert_vec_elt is not supported.
5183   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5184     return SDValue();
5185
5186   DebugLoc DL = Op.getDebugLoc();
5187   unsigned NumElems = Op.getNumOperands();
5188
5189   SDValue VecIn1;
5190   SDValue VecIn2;
5191   SmallVector<unsigned, 4> InsertIndices;
5192   SmallVector<int, 8> Mask(NumElems, -1);
5193
5194   for (unsigned i = 0; i != NumElems; ++i) {
5195     unsigned Opc = Op.getOperand(i).getOpcode();
5196
5197     if (Opc == ISD::UNDEF)
5198       continue;
5199
5200     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5201       // Quit if more than 1 elements need inserting.
5202       if (InsertIndices.size() > 1)
5203         return SDValue();
5204
5205       InsertIndices.push_back(i);
5206       continue;
5207     }
5208
5209     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5210     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5211
5212     // Quit if extracted from vector of different type.
5213     if (ExtractedFromVec.getValueType() != VT)
5214       return SDValue();
5215
5216     // Quit if non-constant index.
5217     if (!isa<ConstantSDNode>(ExtIdx))
5218       return SDValue();
5219
5220     if (VecIn1.getNode() == 0)
5221       VecIn1 = ExtractedFromVec;
5222     else if (VecIn1 != ExtractedFromVec) {
5223       if (VecIn2.getNode() == 0)
5224         VecIn2 = ExtractedFromVec;
5225       else if (VecIn2 != ExtractedFromVec)
5226         // Quit if more than 2 vectors to shuffle
5227         return SDValue();
5228     }
5229
5230     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5231
5232     if (ExtractedFromVec == VecIn1)
5233       Mask[i] = Idx;
5234     else if (ExtractedFromVec == VecIn2)
5235       Mask[i] = Idx + NumElems;
5236   }
5237
5238   if (VecIn1.getNode() == 0)
5239     return SDValue();
5240
5241   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5242   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5243   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5244     unsigned Idx = InsertIndices[i];
5245     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5246                      DAG.getIntPtrConstant(Idx));
5247   }
5248
5249   return NV;
5250 }
5251
5252 SDValue
5253 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5254   DebugLoc dl = Op.getDebugLoc();
5255
5256   EVT VT = Op.getValueType();
5257   EVT ExtVT = VT.getVectorElementType();
5258   unsigned NumElems = Op.getNumOperands();
5259
5260   // Vectors containing all zeros can be matched by pxor and xorps later
5261   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5262     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5263     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5264     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5265       return Op;
5266
5267     return getZeroVector(VT, Subtarget, DAG, dl);
5268   }
5269
5270   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5271   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5272   // vpcmpeqd on 256-bit vectors.
5273   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5274     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5275       return Op;
5276
5277     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5278   }
5279
5280   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5281   if (Broadcast.getNode())
5282     return Broadcast;
5283
5284   unsigned EVTBits = ExtVT.getSizeInBits();
5285
5286   unsigned NumZero  = 0;
5287   unsigned NumNonZero = 0;
5288   unsigned NonZeros = 0;
5289   bool IsAllConstants = true;
5290   SmallSet<SDValue, 8> Values;
5291   for (unsigned i = 0; i < NumElems; ++i) {
5292     SDValue Elt = Op.getOperand(i);
5293     if (Elt.getOpcode() == ISD::UNDEF)
5294       continue;
5295     Values.insert(Elt);
5296     if (Elt.getOpcode() != ISD::Constant &&
5297         Elt.getOpcode() != ISD::ConstantFP)
5298       IsAllConstants = false;
5299     if (X86::isZeroNode(Elt))
5300       NumZero++;
5301     else {
5302       NonZeros |= (1 << i);
5303       NumNonZero++;
5304     }
5305   }
5306
5307   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5308   if (NumNonZero == 0)
5309     return DAG.getUNDEF(VT);
5310
5311   // Special case for single non-zero, non-undef, element.
5312   if (NumNonZero == 1) {
5313     unsigned Idx = CountTrailingZeros_32(NonZeros);
5314     SDValue Item = Op.getOperand(Idx);
5315
5316     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5317     // the value are obviously zero, truncate the value to i32 and do the
5318     // insertion that way.  Only do this if the value is non-constant or if the
5319     // value is a constant being inserted into element 0.  It is cheaper to do
5320     // a constant pool load than it is to do a movd + shuffle.
5321     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5322         (!IsAllConstants || Idx == 0)) {
5323       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5324         // Handle SSE only.
5325         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5326         EVT VecVT = MVT::v4i32;
5327         unsigned VecElts = 4;
5328
5329         // Truncate the value (which may itself be a constant) to i32, and
5330         // convert it to a vector with movd (S2V+shuffle to zero extend).
5331         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5332         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5333         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5334
5335         // Now we have our 32-bit value zero extended in the low element of
5336         // a vector.  If Idx != 0, swizzle it into place.
5337         if (Idx != 0) {
5338           SmallVector<int, 4> Mask;
5339           Mask.push_back(Idx);
5340           for (unsigned i = 1; i != VecElts; ++i)
5341             Mask.push_back(i);
5342           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5343                                       &Mask[0]);
5344         }
5345         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5346       }
5347     }
5348
5349     // If we have a constant or non-constant insertion into the low element of
5350     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5351     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5352     // depending on what the source datatype is.
5353     if (Idx == 0) {
5354       if (NumZero == 0)
5355         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5356
5357       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5358           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5359         if (VT.is256BitVector()) {
5360           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5361           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5362                              Item, DAG.getIntPtrConstant(0));
5363         }
5364         assert(VT.is128BitVector() && "Expected an SSE value type!");
5365         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5366         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5367         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5368       }
5369
5370       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5371         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5372         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5373         if (VT.is256BitVector()) {
5374           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5375           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5376         } else {
5377           assert(VT.is128BitVector() && "Expected an SSE value type!");
5378           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5379         }
5380         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5381       }
5382     }
5383
5384     // Is it a vector logical left shift?
5385     if (NumElems == 2 && Idx == 1 &&
5386         X86::isZeroNode(Op.getOperand(0)) &&
5387         !X86::isZeroNode(Op.getOperand(1))) {
5388       unsigned NumBits = VT.getSizeInBits();
5389       return getVShift(true, VT,
5390                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5391                                    VT, Op.getOperand(1)),
5392                        NumBits/2, DAG, *this, dl);
5393     }
5394
5395     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5396       return SDValue();
5397
5398     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5399     // is a non-constant being inserted into an element other than the low one,
5400     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5401     // movd/movss) to move this into the low element, then shuffle it into
5402     // place.
5403     if (EVTBits == 32) {
5404       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5405
5406       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5407       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5408       SmallVector<int, 8> MaskVec;
5409       for (unsigned i = 0; i != NumElems; ++i)
5410         MaskVec.push_back(i == Idx ? 0 : 1);
5411       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5412     }
5413   }
5414
5415   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5416   if (Values.size() == 1) {
5417     if (EVTBits == 32) {
5418       // Instead of a shuffle like this:
5419       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5420       // Check if it's possible to issue this instead.
5421       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5422       unsigned Idx = CountTrailingZeros_32(NonZeros);
5423       SDValue Item = Op.getOperand(Idx);
5424       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5425         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5426     }
5427     return SDValue();
5428   }
5429
5430   // A vector full of immediates; various special cases are already
5431   // handled, so this is best done with a single constant-pool load.
5432   if (IsAllConstants)
5433     return SDValue();
5434
5435   // For AVX-length vectors, build the individual 128-bit pieces and use
5436   // shuffles to put them in place.
5437   if (VT.is256BitVector()) {
5438     SmallVector<SDValue, 32> V;
5439     for (unsigned i = 0; i != NumElems; ++i)
5440       V.push_back(Op.getOperand(i));
5441
5442     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5443
5444     // Build both the lower and upper subvector.
5445     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5446     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5447                                 NumElems/2);
5448
5449     // Recreate the wider vector with the lower and upper part.
5450     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5451   }
5452
5453   // Let legalizer expand 2-wide build_vectors.
5454   if (EVTBits == 64) {
5455     if (NumNonZero == 1) {
5456       // One half is zero or undef.
5457       unsigned Idx = CountTrailingZeros_32(NonZeros);
5458       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5459                                  Op.getOperand(Idx));
5460       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5461     }
5462     return SDValue();
5463   }
5464
5465   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5466   if (EVTBits == 8 && NumElems == 16) {
5467     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5468                                         Subtarget, *this);
5469     if (V.getNode()) return V;
5470   }
5471
5472   if (EVTBits == 16 && NumElems == 8) {
5473     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5474                                       Subtarget, *this);
5475     if (V.getNode()) return V;
5476   }
5477
5478   // If element VT is == 32 bits, turn it into a number of shuffles.
5479   SmallVector<SDValue, 8> V(NumElems);
5480   if (NumElems == 4 && NumZero > 0) {
5481     for (unsigned i = 0; i < 4; ++i) {
5482       bool isZero = !(NonZeros & (1 << i));
5483       if (isZero)
5484         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5485       else
5486         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5487     }
5488
5489     for (unsigned i = 0; i < 2; ++i) {
5490       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5491         default: break;
5492         case 0:
5493           V[i] = V[i*2];  // Must be a zero vector.
5494           break;
5495         case 1:
5496           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5497           break;
5498         case 2:
5499           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5500           break;
5501         case 3:
5502           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5503           break;
5504       }
5505     }
5506
5507     bool Reverse1 = (NonZeros & 0x3) == 2;
5508     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5509     int MaskVec[] = {
5510       Reverse1 ? 1 : 0,
5511       Reverse1 ? 0 : 1,
5512       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5513       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5514     };
5515     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5516   }
5517
5518   if (Values.size() > 1 && VT.is128BitVector()) {
5519     // Check for a build vector of consecutive loads.
5520     for (unsigned i = 0; i < NumElems; ++i)
5521       V[i] = Op.getOperand(i);
5522
5523     // Check for elements which are consecutive loads.
5524     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5525     if (LD.getNode())
5526       return LD;
5527
5528     // Check for a build vector from mostly shuffle plus few inserting.
5529     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5530     if (Sh.getNode())
5531       return Sh;
5532
5533     // For SSE 4.1, use insertps to put the high elements into the low element.
5534     if (getSubtarget()->hasSSE41()) {
5535       SDValue Result;
5536       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5537         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5538       else
5539         Result = DAG.getUNDEF(VT);
5540
5541       for (unsigned i = 1; i < NumElems; ++i) {
5542         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5543         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5544                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5545       }
5546       return Result;
5547     }
5548
5549     // Otherwise, expand into a number of unpckl*, start by extending each of
5550     // our (non-undef) elements to the full vector width with the element in the
5551     // bottom slot of the vector (which generates no code for SSE).
5552     for (unsigned i = 0; i < NumElems; ++i) {
5553       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5554         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5555       else
5556         V[i] = DAG.getUNDEF(VT);
5557     }
5558
5559     // Next, we iteratively mix elements, e.g. for v4f32:
5560     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5561     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5562     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5563     unsigned EltStride = NumElems >> 1;
5564     while (EltStride != 0) {
5565       for (unsigned i = 0; i < EltStride; ++i) {
5566         // If V[i+EltStride] is undef and this is the first round of mixing,
5567         // then it is safe to just drop this shuffle: V[i] is already in the
5568         // right place, the one element (since it's the first round) being
5569         // inserted as undef can be dropped.  This isn't safe for successive
5570         // rounds because they will permute elements within both vectors.
5571         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5572             EltStride == NumElems/2)
5573           continue;
5574
5575         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5576       }
5577       EltStride >>= 1;
5578     }
5579     return V[0];
5580   }
5581   return SDValue();
5582 }
5583
5584 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5585 // to create 256-bit vectors from two other 128-bit ones.
5586 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5587   DebugLoc dl = Op.getDebugLoc();
5588   EVT ResVT = Op.getValueType();
5589
5590   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5591
5592   SDValue V1 = Op.getOperand(0);
5593   SDValue V2 = Op.getOperand(1);
5594   unsigned NumElems = ResVT.getVectorNumElements();
5595
5596   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5597 }
5598
5599 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5600   assert(Op.getNumOperands() == 2);
5601
5602   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5603   // from two other 128-bit ones.
5604   return LowerAVXCONCAT_VECTORS(Op, DAG);
5605 }
5606
5607 // Try to lower a shuffle node into a simple blend instruction.
5608 static SDValue
5609 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5610                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5611   SDValue V1 = SVOp->getOperand(0);
5612   SDValue V2 = SVOp->getOperand(1);
5613   DebugLoc dl = SVOp->getDebugLoc();
5614   MVT VT = SVOp->getValueType(0).getSimpleVT();
5615   unsigned NumElems = VT.getVectorNumElements();
5616
5617   if (!Subtarget->hasSSE41())
5618     return SDValue();
5619
5620   unsigned ISDNo = 0;
5621   MVT OpTy;
5622
5623   switch (VT.SimpleTy) {
5624   default: return SDValue();
5625   case MVT::v8i16:
5626     ISDNo = X86ISD::BLENDPW;
5627     OpTy = MVT::v8i16;
5628     break;
5629   case MVT::v4i32:
5630   case MVT::v4f32:
5631     ISDNo = X86ISD::BLENDPS;
5632     OpTy = MVT::v4f32;
5633     break;
5634   case MVT::v2i64:
5635   case MVT::v2f64:
5636     ISDNo = X86ISD::BLENDPD;
5637     OpTy = MVT::v2f64;
5638     break;
5639   case MVT::v8i32:
5640   case MVT::v8f32:
5641     if (!Subtarget->hasAVX())
5642       return SDValue();
5643     ISDNo = X86ISD::BLENDPS;
5644     OpTy = MVT::v8f32;
5645     break;
5646   case MVT::v4i64:
5647   case MVT::v4f64:
5648     if (!Subtarget->hasAVX())
5649       return SDValue();
5650     ISDNo = X86ISD::BLENDPD;
5651     OpTy = MVT::v4f64;
5652     break;
5653   }
5654   assert(ISDNo && "Invalid Op Number");
5655
5656   unsigned MaskVals = 0;
5657
5658   for (unsigned i = 0; i != NumElems; ++i) {
5659     int EltIdx = SVOp->getMaskElt(i);
5660     if (EltIdx == (int)i || EltIdx < 0)
5661       MaskVals |= (1<<i);
5662     else if (EltIdx == (int)(i + NumElems))
5663       continue; // Bit is set to zero;
5664     else
5665       return SDValue();
5666   }
5667
5668   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5669   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5670   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5671                              DAG.getConstant(MaskVals, MVT::i32));
5672   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5673 }
5674
5675 // v8i16 shuffles - Prefer shuffles in the following order:
5676 // 1. [all]   pshuflw, pshufhw, optional move
5677 // 2. [ssse3] 1 x pshufb
5678 // 3. [ssse3] 2 x pshufb + 1 x por
5679 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5680 static SDValue
5681 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5682                          SelectionDAG &DAG) {
5683   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5684   SDValue V1 = SVOp->getOperand(0);
5685   SDValue V2 = SVOp->getOperand(1);
5686   DebugLoc dl = SVOp->getDebugLoc();
5687   SmallVector<int, 8> MaskVals;
5688
5689   // Determine if more than 1 of the words in each of the low and high quadwords
5690   // of the result come from the same quadword of one of the two inputs.  Undef
5691   // mask values count as coming from any quadword, for better codegen.
5692   unsigned LoQuad[] = { 0, 0, 0, 0 };
5693   unsigned HiQuad[] = { 0, 0, 0, 0 };
5694   std::bitset<4> InputQuads;
5695   for (unsigned i = 0; i < 8; ++i) {
5696     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5697     int EltIdx = SVOp->getMaskElt(i);
5698     MaskVals.push_back(EltIdx);
5699     if (EltIdx < 0) {
5700       ++Quad[0];
5701       ++Quad[1];
5702       ++Quad[2];
5703       ++Quad[3];
5704       continue;
5705     }
5706     ++Quad[EltIdx / 4];
5707     InputQuads.set(EltIdx / 4);
5708   }
5709
5710   int BestLoQuad = -1;
5711   unsigned MaxQuad = 1;
5712   for (unsigned i = 0; i < 4; ++i) {
5713     if (LoQuad[i] > MaxQuad) {
5714       BestLoQuad = i;
5715       MaxQuad = LoQuad[i];
5716     }
5717   }
5718
5719   int BestHiQuad = -1;
5720   MaxQuad = 1;
5721   for (unsigned i = 0; i < 4; ++i) {
5722     if (HiQuad[i] > MaxQuad) {
5723       BestHiQuad = i;
5724       MaxQuad = HiQuad[i];
5725     }
5726   }
5727
5728   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5729   // of the two input vectors, shuffle them into one input vector so only a
5730   // single pshufb instruction is necessary. If There are more than 2 input
5731   // quads, disable the next transformation since it does not help SSSE3.
5732   bool V1Used = InputQuads[0] || InputQuads[1];
5733   bool V2Used = InputQuads[2] || InputQuads[3];
5734   if (Subtarget->hasSSSE3()) {
5735     if (InputQuads.count() == 2 && V1Used && V2Used) {
5736       BestLoQuad = InputQuads[0] ? 0 : 1;
5737       BestHiQuad = InputQuads[2] ? 2 : 3;
5738     }
5739     if (InputQuads.count() > 2) {
5740       BestLoQuad = -1;
5741       BestHiQuad = -1;
5742     }
5743   }
5744
5745   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5746   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5747   // words from all 4 input quadwords.
5748   SDValue NewV;
5749   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5750     int MaskV[] = {
5751       BestLoQuad < 0 ? 0 : BestLoQuad,
5752       BestHiQuad < 0 ? 1 : BestHiQuad
5753     };
5754     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5755                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5756                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5757     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5758
5759     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5760     // source words for the shuffle, to aid later transformations.
5761     bool AllWordsInNewV = true;
5762     bool InOrder[2] = { true, true };
5763     for (unsigned i = 0; i != 8; ++i) {
5764       int idx = MaskVals[i];
5765       if (idx != (int)i)
5766         InOrder[i/4] = false;
5767       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5768         continue;
5769       AllWordsInNewV = false;
5770       break;
5771     }
5772
5773     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5774     if (AllWordsInNewV) {
5775       for (int i = 0; i != 8; ++i) {
5776         int idx = MaskVals[i];
5777         if (idx < 0)
5778           continue;
5779         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5780         if ((idx != i) && idx < 4)
5781           pshufhw = false;
5782         if ((idx != i) && idx > 3)
5783           pshuflw = false;
5784       }
5785       V1 = NewV;
5786       V2Used = false;
5787       BestLoQuad = 0;
5788       BestHiQuad = 1;
5789     }
5790
5791     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5792     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5793     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5794       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5795       unsigned TargetMask = 0;
5796       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5797                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5798       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5799       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5800                              getShufflePSHUFLWImmediate(SVOp);
5801       V1 = NewV.getOperand(0);
5802       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5803     }
5804   }
5805
5806   // If we have SSSE3, and all words of the result are from 1 input vector,
5807   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5808   // is present, fall back to case 4.
5809   if (Subtarget->hasSSSE3()) {
5810     SmallVector<SDValue,16> pshufbMask;
5811
5812     // If we have elements from both input vectors, set the high bit of the
5813     // shuffle mask element to zero out elements that come from V2 in the V1
5814     // mask, and elements that come from V1 in the V2 mask, so that the two
5815     // results can be OR'd together.
5816     bool TwoInputs = V1Used && V2Used;
5817     for (unsigned i = 0; i != 8; ++i) {
5818       int EltIdx = MaskVals[i] * 2;
5819       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5820       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5821       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5822       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5823     }
5824     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5825     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5826                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5827                                  MVT::v16i8, &pshufbMask[0], 16));
5828     if (!TwoInputs)
5829       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5830
5831     // Calculate the shuffle mask for the second input, shuffle it, and
5832     // OR it with the first shuffled input.
5833     pshufbMask.clear();
5834     for (unsigned i = 0; i != 8; ++i) {
5835       int EltIdx = MaskVals[i] * 2;
5836       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5837       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5838       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5839       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5840     }
5841     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5842     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5843                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5844                                  MVT::v16i8, &pshufbMask[0], 16));
5845     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5846     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5847   }
5848
5849   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5850   // and update MaskVals with new element order.
5851   std::bitset<8> InOrder;
5852   if (BestLoQuad >= 0) {
5853     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5854     for (int i = 0; i != 4; ++i) {
5855       int idx = MaskVals[i];
5856       if (idx < 0) {
5857         InOrder.set(i);
5858       } else if ((idx / 4) == BestLoQuad) {
5859         MaskV[i] = idx & 3;
5860         InOrder.set(i);
5861       }
5862     }
5863     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5864                                 &MaskV[0]);
5865
5866     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5867       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5868       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5869                                   NewV.getOperand(0),
5870                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5871     }
5872   }
5873
5874   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5875   // and update MaskVals with the new element order.
5876   if (BestHiQuad >= 0) {
5877     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5878     for (unsigned i = 4; i != 8; ++i) {
5879       int idx = MaskVals[i];
5880       if (idx < 0) {
5881         InOrder.set(i);
5882       } else if ((idx / 4) == BestHiQuad) {
5883         MaskV[i] = (idx & 3) + 4;
5884         InOrder.set(i);
5885       }
5886     }
5887     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5888                                 &MaskV[0]);
5889
5890     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5891       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5892       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5893                                   NewV.getOperand(0),
5894                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5895     }
5896   }
5897
5898   // In case BestHi & BestLo were both -1, which means each quadword has a word
5899   // from each of the four input quadwords, calculate the InOrder bitvector now
5900   // before falling through to the insert/extract cleanup.
5901   if (BestLoQuad == -1 && BestHiQuad == -1) {
5902     NewV = V1;
5903     for (int i = 0; i != 8; ++i)
5904       if (MaskVals[i] < 0 || MaskVals[i] == i)
5905         InOrder.set(i);
5906   }
5907
5908   // The other elements are put in the right place using pextrw and pinsrw.
5909   for (unsigned i = 0; i != 8; ++i) {
5910     if (InOrder[i])
5911       continue;
5912     int EltIdx = MaskVals[i];
5913     if (EltIdx < 0)
5914       continue;
5915     SDValue ExtOp = (EltIdx < 8) ?
5916       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5917                   DAG.getIntPtrConstant(EltIdx)) :
5918       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5919                   DAG.getIntPtrConstant(EltIdx - 8));
5920     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5921                        DAG.getIntPtrConstant(i));
5922   }
5923   return NewV;
5924 }
5925
5926 // v16i8 shuffles - Prefer shuffles in the following order:
5927 // 1. [ssse3] 1 x pshufb
5928 // 2. [ssse3] 2 x pshufb + 1 x por
5929 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5930 static
5931 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5932                                  SelectionDAG &DAG,
5933                                  const X86TargetLowering &TLI) {
5934   SDValue V1 = SVOp->getOperand(0);
5935   SDValue V2 = SVOp->getOperand(1);
5936   DebugLoc dl = SVOp->getDebugLoc();
5937   ArrayRef<int> MaskVals = SVOp->getMask();
5938
5939   // If we have SSSE3, case 1 is generated when all result bytes come from
5940   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5941   // present, fall back to case 3.
5942
5943   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5944   if (TLI.getSubtarget()->hasSSSE3()) {
5945     SmallVector<SDValue,16> pshufbMask;
5946
5947     // If all result elements are from one input vector, then only translate
5948     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5949     //
5950     // Otherwise, we have elements from both input vectors, and must zero out
5951     // elements that come from V2 in the first mask, and V1 in the second mask
5952     // so that we can OR them together.
5953     for (unsigned i = 0; i != 16; ++i) {
5954       int EltIdx = MaskVals[i];
5955       if (EltIdx < 0 || EltIdx >= 16)
5956         EltIdx = 0x80;
5957       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5958     }
5959     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5960                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5961                                  MVT::v16i8, &pshufbMask[0], 16));
5962
5963     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5964     // the 2nd operand if it's undefined or zero.
5965     if (V2.getOpcode() == ISD::UNDEF ||
5966         ISD::isBuildVectorAllZeros(V2.getNode()))
5967       return V1;
5968
5969     // Calculate the shuffle mask for the second input, shuffle it, and
5970     // OR it with the first shuffled input.
5971     pshufbMask.clear();
5972     for (unsigned i = 0; i != 16; ++i) {
5973       int EltIdx = MaskVals[i];
5974       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5975       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5976     }
5977     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5978                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5979                                  MVT::v16i8, &pshufbMask[0], 16));
5980     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5981   }
5982
5983   // No SSSE3 - Calculate in place words and then fix all out of place words
5984   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5985   // the 16 different words that comprise the two doublequadword input vectors.
5986   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5987   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5988   SDValue NewV = V1;
5989   for (int i = 0; i != 8; ++i) {
5990     int Elt0 = MaskVals[i*2];
5991     int Elt1 = MaskVals[i*2+1];
5992
5993     // This word of the result is all undef, skip it.
5994     if (Elt0 < 0 && Elt1 < 0)
5995       continue;
5996
5997     // This word of the result is already in the correct place, skip it.
5998     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5999       continue;
6000
6001     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6002     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6003     SDValue InsElt;
6004
6005     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6006     // using a single extract together, load it and store it.
6007     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6008       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6009                            DAG.getIntPtrConstant(Elt1 / 2));
6010       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6011                         DAG.getIntPtrConstant(i));
6012       continue;
6013     }
6014
6015     // If Elt1 is defined, extract it from the appropriate source.  If the
6016     // source byte is not also odd, shift the extracted word left 8 bits
6017     // otherwise clear the bottom 8 bits if we need to do an or.
6018     if (Elt1 >= 0) {
6019       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6020                            DAG.getIntPtrConstant(Elt1 / 2));
6021       if ((Elt1 & 1) == 0)
6022         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6023                              DAG.getConstant(8,
6024                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6025       else if (Elt0 >= 0)
6026         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6027                              DAG.getConstant(0xFF00, MVT::i16));
6028     }
6029     // If Elt0 is defined, extract it from the appropriate source.  If the
6030     // source byte is not also even, shift the extracted word right 8 bits. If
6031     // Elt1 was also defined, OR the extracted values together before
6032     // inserting them in the result.
6033     if (Elt0 >= 0) {
6034       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6035                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6036       if ((Elt0 & 1) != 0)
6037         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6038                               DAG.getConstant(8,
6039                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6040       else if (Elt1 >= 0)
6041         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6042                              DAG.getConstant(0x00FF, MVT::i16));
6043       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6044                          : InsElt0;
6045     }
6046     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6047                        DAG.getIntPtrConstant(i));
6048   }
6049   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6050 }
6051
6052 // v32i8 shuffles - Translate to VPSHUFB if possible.
6053 static
6054 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6055                                  const X86Subtarget *Subtarget,
6056                                  SelectionDAG &DAG) {
6057   EVT VT = SVOp->getValueType(0);
6058   SDValue V1 = SVOp->getOperand(0);
6059   SDValue V2 = SVOp->getOperand(1);
6060   DebugLoc dl = SVOp->getDebugLoc();
6061   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6062
6063   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6064   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6065   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6066
6067   // VPSHUFB may be generated if
6068   // (1) one of input vector is undefined or zeroinitializer.
6069   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6070   // And (2) the mask indexes don't cross the 128-bit lane.
6071   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6072       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6073     return SDValue();
6074
6075   if (V1IsAllZero && !V2IsAllZero) {
6076     CommuteVectorShuffleMask(MaskVals, 32);
6077     V1 = V2;
6078   }
6079   SmallVector<SDValue, 32> pshufbMask;
6080   for (unsigned i = 0; i != 32; i++) {
6081     int EltIdx = MaskVals[i];
6082     if (EltIdx < 0 || EltIdx >= 32)
6083       EltIdx = 0x80;
6084     else {
6085       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6086         // Cross lane is not allowed.
6087         return SDValue();
6088       EltIdx &= 0xf;
6089     }
6090     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6091   }
6092   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6093                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6094                                   MVT::v32i8, &pshufbMask[0], 32));
6095 }
6096
6097 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6098 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6099 /// done when every pair / quad of shuffle mask elements point to elements in
6100 /// the right sequence. e.g.
6101 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6102 static
6103 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6104                                  SelectionDAG &DAG, DebugLoc dl) {
6105   MVT VT = SVOp->getValueType(0).getSimpleVT();
6106   unsigned NumElems = VT.getVectorNumElements();
6107   MVT NewVT;
6108   unsigned Scale;
6109   switch (VT.SimpleTy) {
6110   default: llvm_unreachable("Unexpected!");
6111   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6112   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6113   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6114   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6115   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6116   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6117   }
6118
6119   SmallVector<int, 8> MaskVec;
6120   for (unsigned i = 0; i != NumElems; i += Scale) {
6121     int StartIdx = -1;
6122     for (unsigned j = 0; j != Scale; ++j) {
6123       int EltIdx = SVOp->getMaskElt(i+j);
6124       if (EltIdx < 0)
6125         continue;
6126       if (StartIdx < 0)
6127         StartIdx = (EltIdx / Scale);
6128       if (EltIdx != (int)(StartIdx*Scale + j))
6129         return SDValue();
6130     }
6131     MaskVec.push_back(StartIdx);
6132   }
6133
6134   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6135   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6136   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6137 }
6138
6139 /// getVZextMovL - Return a zero-extending vector move low node.
6140 ///
6141 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6142                             SDValue SrcOp, SelectionDAG &DAG,
6143                             const X86Subtarget *Subtarget, DebugLoc dl) {
6144   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6145     LoadSDNode *LD = NULL;
6146     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6147       LD = dyn_cast<LoadSDNode>(SrcOp);
6148     if (!LD) {
6149       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6150       // instead.
6151       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6152       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6153           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6154           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6155           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6156         // PR2108
6157         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6158         return DAG.getNode(ISD::BITCAST, dl, VT,
6159                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6160                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6161                                                    OpVT,
6162                                                    SrcOp.getOperand(0)
6163                                                           .getOperand(0))));
6164       }
6165     }
6166   }
6167
6168   return DAG.getNode(ISD::BITCAST, dl, VT,
6169                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6170                                  DAG.getNode(ISD::BITCAST, dl,
6171                                              OpVT, SrcOp)));
6172 }
6173
6174 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6175 /// which could not be matched by any known target speficic shuffle
6176 static SDValue
6177 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6178
6179   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6180   if (NewOp.getNode())
6181     return NewOp;
6182
6183   EVT VT = SVOp->getValueType(0);
6184
6185   unsigned NumElems = VT.getVectorNumElements();
6186   unsigned NumLaneElems = NumElems / 2;
6187
6188   DebugLoc dl = SVOp->getDebugLoc();
6189   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6190   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6191   SDValue Output[2];
6192
6193   SmallVector<int, 16> Mask;
6194   for (unsigned l = 0; l < 2; ++l) {
6195     // Build a shuffle mask for the output, discovering on the fly which
6196     // input vectors to use as shuffle operands (recorded in InputUsed).
6197     // If building a suitable shuffle vector proves too hard, then bail
6198     // out with UseBuildVector set.
6199     bool UseBuildVector = false;
6200     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6201     unsigned LaneStart = l * NumLaneElems;
6202     for (unsigned i = 0; i != NumLaneElems; ++i) {
6203       // The mask element.  This indexes into the input.
6204       int Idx = SVOp->getMaskElt(i+LaneStart);
6205       if (Idx < 0) {
6206         // the mask element does not index into any input vector.
6207         Mask.push_back(-1);
6208         continue;
6209       }
6210
6211       // The input vector this mask element indexes into.
6212       int Input = Idx / NumLaneElems;
6213
6214       // Turn the index into an offset from the start of the input vector.
6215       Idx -= Input * NumLaneElems;
6216
6217       // Find or create a shuffle vector operand to hold this input.
6218       unsigned OpNo;
6219       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6220         if (InputUsed[OpNo] == Input)
6221           // This input vector is already an operand.
6222           break;
6223         if (InputUsed[OpNo] < 0) {
6224           // Create a new operand for this input vector.
6225           InputUsed[OpNo] = Input;
6226           break;
6227         }
6228       }
6229
6230       if (OpNo >= array_lengthof(InputUsed)) {
6231         // More than two input vectors used!  Give up on trying to create a
6232         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6233         UseBuildVector = true;
6234         break;
6235       }
6236
6237       // Add the mask index for the new shuffle vector.
6238       Mask.push_back(Idx + OpNo * NumLaneElems);
6239     }
6240
6241     if (UseBuildVector) {
6242       SmallVector<SDValue, 16> SVOps;
6243       for (unsigned i = 0; i != NumLaneElems; ++i) {
6244         // The mask element.  This indexes into the input.
6245         int Idx = SVOp->getMaskElt(i+LaneStart);
6246         if (Idx < 0) {
6247           SVOps.push_back(DAG.getUNDEF(EltVT));
6248           continue;
6249         }
6250
6251         // The input vector this mask element indexes into.
6252         int Input = Idx / NumElems;
6253
6254         // Turn the index into an offset from the start of the input vector.
6255         Idx -= Input * NumElems;
6256
6257         // Extract the vector element by hand.
6258         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6259                                     SVOp->getOperand(Input),
6260                                     DAG.getIntPtrConstant(Idx)));
6261       }
6262
6263       // Construct the output using a BUILD_VECTOR.
6264       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6265                               SVOps.size());
6266     } else if (InputUsed[0] < 0) {
6267       // No input vectors were used! The result is undefined.
6268       Output[l] = DAG.getUNDEF(NVT);
6269     } else {
6270       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6271                                         (InputUsed[0] % 2) * NumLaneElems,
6272                                         DAG, dl);
6273       // If only one input was used, use an undefined vector for the other.
6274       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6275         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6276                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6277       // At least one input vector was used. Create a new shuffle vector.
6278       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6279     }
6280
6281     Mask.clear();
6282   }
6283
6284   // Concatenate the result back
6285   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6286 }
6287
6288 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6289 /// 4 elements, and match them with several different shuffle types.
6290 static SDValue
6291 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6292   SDValue V1 = SVOp->getOperand(0);
6293   SDValue V2 = SVOp->getOperand(1);
6294   DebugLoc dl = SVOp->getDebugLoc();
6295   EVT VT = SVOp->getValueType(0);
6296
6297   assert(VT.is128BitVector() && "Unsupported vector size");
6298
6299   std::pair<int, int> Locs[4];
6300   int Mask1[] = { -1, -1, -1, -1 };
6301   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6302
6303   unsigned NumHi = 0;
6304   unsigned NumLo = 0;
6305   for (unsigned i = 0; i != 4; ++i) {
6306     int Idx = PermMask[i];
6307     if (Idx < 0) {
6308       Locs[i] = std::make_pair(-1, -1);
6309     } else {
6310       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6311       if (Idx < 4) {
6312         Locs[i] = std::make_pair(0, NumLo);
6313         Mask1[NumLo] = Idx;
6314         NumLo++;
6315       } else {
6316         Locs[i] = std::make_pair(1, NumHi);
6317         if (2+NumHi < 4)
6318           Mask1[2+NumHi] = Idx;
6319         NumHi++;
6320       }
6321     }
6322   }
6323
6324   if (NumLo <= 2 && NumHi <= 2) {
6325     // If no more than two elements come from either vector. This can be
6326     // implemented with two shuffles. First shuffle gather the elements.
6327     // The second shuffle, which takes the first shuffle as both of its
6328     // vector operands, put the elements into the right order.
6329     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6330
6331     int Mask2[] = { -1, -1, -1, -1 };
6332
6333     for (unsigned i = 0; i != 4; ++i)
6334       if (Locs[i].first != -1) {
6335         unsigned Idx = (i < 2) ? 0 : 4;
6336         Idx += Locs[i].first * 2 + Locs[i].second;
6337         Mask2[i] = Idx;
6338       }
6339
6340     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6341   }
6342
6343   if (NumLo == 3 || NumHi == 3) {
6344     // Otherwise, we must have three elements from one vector, call it X, and
6345     // one element from the other, call it Y.  First, use a shufps to build an
6346     // intermediate vector with the one element from Y and the element from X
6347     // that will be in the same half in the final destination (the indexes don't
6348     // matter). Then, use a shufps to build the final vector, taking the half
6349     // containing the element from Y from the intermediate, and the other half
6350     // from X.
6351     if (NumHi == 3) {
6352       // Normalize it so the 3 elements come from V1.
6353       CommuteVectorShuffleMask(PermMask, 4);
6354       std::swap(V1, V2);
6355     }
6356
6357     // Find the element from V2.
6358     unsigned HiIndex;
6359     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6360       int Val = PermMask[HiIndex];
6361       if (Val < 0)
6362         continue;
6363       if (Val >= 4)
6364         break;
6365     }
6366
6367     Mask1[0] = PermMask[HiIndex];
6368     Mask1[1] = -1;
6369     Mask1[2] = PermMask[HiIndex^1];
6370     Mask1[3] = -1;
6371     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6372
6373     if (HiIndex >= 2) {
6374       Mask1[0] = PermMask[0];
6375       Mask1[1] = PermMask[1];
6376       Mask1[2] = HiIndex & 1 ? 6 : 4;
6377       Mask1[3] = HiIndex & 1 ? 4 : 6;
6378       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6379     }
6380
6381     Mask1[0] = HiIndex & 1 ? 2 : 0;
6382     Mask1[1] = HiIndex & 1 ? 0 : 2;
6383     Mask1[2] = PermMask[2];
6384     Mask1[3] = PermMask[3];
6385     if (Mask1[2] >= 0)
6386       Mask1[2] += 4;
6387     if (Mask1[3] >= 0)
6388       Mask1[3] += 4;
6389     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6390   }
6391
6392   // Break it into (shuffle shuffle_hi, shuffle_lo).
6393   int LoMask[] = { -1, -1, -1, -1 };
6394   int HiMask[] = { -1, -1, -1, -1 };
6395
6396   int *MaskPtr = LoMask;
6397   unsigned MaskIdx = 0;
6398   unsigned LoIdx = 0;
6399   unsigned HiIdx = 2;
6400   for (unsigned i = 0; i != 4; ++i) {
6401     if (i == 2) {
6402       MaskPtr = HiMask;
6403       MaskIdx = 1;
6404       LoIdx = 0;
6405       HiIdx = 2;
6406     }
6407     int Idx = PermMask[i];
6408     if (Idx < 0) {
6409       Locs[i] = std::make_pair(-1, -1);
6410     } else if (Idx < 4) {
6411       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6412       MaskPtr[LoIdx] = Idx;
6413       LoIdx++;
6414     } else {
6415       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6416       MaskPtr[HiIdx] = Idx;
6417       HiIdx++;
6418     }
6419   }
6420
6421   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6422   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6423   int MaskOps[] = { -1, -1, -1, -1 };
6424   for (unsigned i = 0; i != 4; ++i)
6425     if (Locs[i].first != -1)
6426       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6427   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6428 }
6429
6430 static bool MayFoldVectorLoad(SDValue V) {
6431   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6432     V = V.getOperand(0);
6433   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6434     V = V.getOperand(0);
6435   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6436       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6437     // BUILD_VECTOR (load), undef
6438     V = V.getOperand(0);
6439   if (MayFoldLoad(V))
6440     return true;
6441   return false;
6442 }
6443
6444 // FIXME: the version above should always be used. Since there's
6445 // a bug where several vector shuffles can't be folded because the
6446 // DAG is not updated during lowering and a node claims to have two
6447 // uses while it only has one, use this version, and let isel match
6448 // another instruction if the load really happens to have more than
6449 // one use. Remove this version after this bug get fixed.
6450 // rdar://8434668, PR8156
6451 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6452   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6453     V = V.getOperand(0);
6454   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6455     V = V.getOperand(0);
6456   if (ISD::isNormalLoad(V.getNode()))
6457     return true;
6458   return false;
6459 }
6460
6461 static
6462 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6463   EVT VT = Op.getValueType();
6464
6465   // Canonizalize to v2f64.
6466   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6467   return DAG.getNode(ISD::BITCAST, dl, VT,
6468                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6469                                           V1, DAG));
6470 }
6471
6472 static
6473 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6474                         bool HasSSE2) {
6475   SDValue V1 = Op.getOperand(0);
6476   SDValue V2 = Op.getOperand(1);
6477   EVT VT = Op.getValueType();
6478
6479   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6480
6481   if (HasSSE2 && VT == MVT::v2f64)
6482     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6483
6484   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6485   return DAG.getNode(ISD::BITCAST, dl, VT,
6486                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6487                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6488                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6489 }
6490
6491 static
6492 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6493   SDValue V1 = Op.getOperand(0);
6494   SDValue V2 = Op.getOperand(1);
6495   EVT VT = Op.getValueType();
6496
6497   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6498          "unsupported shuffle type");
6499
6500   if (V2.getOpcode() == ISD::UNDEF)
6501     V2 = V1;
6502
6503   // v4i32 or v4f32
6504   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6505 }
6506
6507 static
6508 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6509   SDValue V1 = Op.getOperand(0);
6510   SDValue V2 = Op.getOperand(1);
6511   EVT VT = Op.getValueType();
6512   unsigned NumElems = VT.getVectorNumElements();
6513
6514   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6515   // operand of these instructions is only memory, so check if there's a
6516   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6517   // same masks.
6518   bool CanFoldLoad = false;
6519
6520   // Trivial case, when V2 comes from a load.
6521   if (MayFoldVectorLoad(V2))
6522     CanFoldLoad = true;
6523
6524   // When V1 is a load, it can be folded later into a store in isel, example:
6525   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6526   //    turns into:
6527   //  (MOVLPSmr addr:$src1, VR128:$src2)
6528   // So, recognize this potential and also use MOVLPS or MOVLPD
6529   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6530     CanFoldLoad = true;
6531
6532   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6533   if (CanFoldLoad) {
6534     if (HasSSE2 && NumElems == 2)
6535       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6536
6537     if (NumElems == 4)
6538       // If we don't care about the second element, proceed to use movss.
6539       if (SVOp->getMaskElt(1) != -1)
6540         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6541   }
6542
6543   // movl and movlp will both match v2i64, but v2i64 is never matched by
6544   // movl earlier because we make it strict to avoid messing with the movlp load
6545   // folding logic (see the code above getMOVLP call). Match it here then,
6546   // this is horrible, but will stay like this until we move all shuffle
6547   // matching to x86 specific nodes. Note that for the 1st condition all
6548   // types are matched with movsd.
6549   if (HasSSE2) {
6550     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6551     // as to remove this logic from here, as much as possible
6552     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6553       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6554     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6555   }
6556
6557   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6558
6559   // Invert the operand order and use SHUFPS to match it.
6560   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6561                               getShuffleSHUFImmediate(SVOp), DAG);
6562 }
6563
6564 SDValue
6565 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6566   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6567   EVT VT = Op.getValueType();
6568   DebugLoc dl = Op.getDebugLoc();
6569   SDValue V1 = Op.getOperand(0);
6570   SDValue V2 = Op.getOperand(1);
6571
6572   if (isZeroShuffle(SVOp))
6573     return getZeroVector(VT, Subtarget, DAG, dl);
6574
6575   // Handle splat operations
6576   if (SVOp->isSplat()) {
6577     unsigned NumElem = VT.getVectorNumElements();
6578     int Size = VT.getSizeInBits();
6579
6580     // Use vbroadcast whenever the splat comes from a foldable load
6581     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6582     if (Broadcast.getNode())
6583       return Broadcast;
6584
6585     // Handle splats by matching through known shuffle masks
6586     if ((Size == 128 && NumElem <= 4) ||
6587         (Size == 256 && NumElem < 8))
6588       return SDValue();
6589
6590     // All remaning splats are promoted to target supported vector shuffles.
6591     return PromoteSplat(SVOp, DAG);
6592   }
6593
6594   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6595   // do it!
6596   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6597       VT == MVT::v16i16 || VT == MVT::v32i8) {
6598     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6599     if (NewOp.getNode())
6600       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6601   } else if ((VT == MVT::v4i32 ||
6602              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6603     // FIXME: Figure out a cleaner way to do this.
6604     // Try to make use of movq to zero out the top part.
6605     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6606       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6607       if (NewOp.getNode()) {
6608         EVT NewVT = NewOp.getValueType();
6609         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6610                                NewVT, true, false))
6611           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6612                               DAG, Subtarget, dl);
6613       }
6614     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6615       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6616       if (NewOp.getNode()) {
6617         EVT NewVT = NewOp.getValueType();
6618         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6619           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6620                               DAG, Subtarget, dl);
6621       }
6622     }
6623   }
6624   return SDValue();
6625 }
6626
6627 SDValue
6628 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6629   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6630   SDValue V1 = Op.getOperand(0);
6631   SDValue V2 = Op.getOperand(1);
6632   EVT VT = Op.getValueType();
6633   DebugLoc dl = Op.getDebugLoc();
6634   unsigned NumElems = VT.getVectorNumElements();
6635   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6636   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6637   bool V1IsSplat = false;
6638   bool V2IsSplat = false;
6639   bool HasSSE2 = Subtarget->hasSSE2();
6640   bool HasAVX    = Subtarget->hasAVX();
6641   bool HasAVX2   = Subtarget->hasAVX2();
6642   MachineFunction &MF = DAG.getMachineFunction();
6643   bool OptForSize = MF.getFunction()->getFnAttributes().
6644     hasAttribute(Attributes::OptimizeForSize);
6645
6646   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6647
6648   if (V1IsUndef && V2IsUndef)
6649     return DAG.getUNDEF(VT);
6650
6651   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6652
6653   // Vector shuffle lowering takes 3 steps:
6654   //
6655   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6656   //    narrowing and commutation of operands should be handled.
6657   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6658   //    shuffle nodes.
6659   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6660   //    so the shuffle can be broken into other shuffles and the legalizer can
6661   //    try the lowering again.
6662   //
6663   // The general idea is that no vector_shuffle operation should be left to
6664   // be matched during isel, all of them must be converted to a target specific
6665   // node here.
6666
6667   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6668   // narrowing and commutation of operands should be handled. The actual code
6669   // doesn't include all of those, work in progress...
6670   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6671   if (NewOp.getNode())
6672     return NewOp;
6673
6674   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6675
6676   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6677   // unpckh_undef). Only use pshufd if speed is more important than size.
6678   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6679     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6680   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6681     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6682
6683   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6684       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6685     return getMOVDDup(Op, dl, V1, DAG);
6686
6687   if (isMOVHLPS_v_undef_Mask(M, VT))
6688     return getMOVHighToLow(Op, dl, DAG);
6689
6690   // Use to match splats
6691   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6692       (VT == MVT::v2f64 || VT == MVT::v2i64))
6693     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6694
6695   if (isPSHUFDMask(M, VT)) {
6696     // The actual implementation will match the mask in the if above and then
6697     // during isel it can match several different instructions, not only pshufd
6698     // as its name says, sad but true, emulate the behavior for now...
6699     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6700       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6701
6702     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6703
6704     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6705       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6706
6707     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6708       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6709
6710     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6711                                 TargetMask, DAG);
6712   }
6713
6714   // Check if this can be converted into a logical shift.
6715   bool isLeft = false;
6716   unsigned ShAmt = 0;
6717   SDValue ShVal;
6718   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6719   if (isShift && ShVal.hasOneUse()) {
6720     // If the shifted value has multiple uses, it may be cheaper to use
6721     // v_set0 + movlhps or movhlps, etc.
6722     EVT EltVT = VT.getVectorElementType();
6723     ShAmt *= EltVT.getSizeInBits();
6724     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6725   }
6726
6727   if (isMOVLMask(M, VT)) {
6728     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6729       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6730     if (!isMOVLPMask(M, VT)) {
6731       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6732         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6733
6734       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6735         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6736     }
6737   }
6738
6739   // FIXME: fold these into legal mask.
6740   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6741     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6742
6743   if (isMOVHLPSMask(M, VT))
6744     return getMOVHighToLow(Op, dl, DAG);
6745
6746   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6747     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6748
6749   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6750     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6751
6752   if (isMOVLPMask(M, VT))
6753     return getMOVLP(Op, dl, DAG, HasSSE2);
6754
6755   if (ShouldXformToMOVHLPS(M, VT) ||
6756       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6757     return CommuteVectorShuffle(SVOp, DAG);
6758
6759   if (isShift) {
6760     // No better options. Use a vshldq / vsrldq.
6761     EVT EltVT = VT.getVectorElementType();
6762     ShAmt *= EltVT.getSizeInBits();
6763     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6764   }
6765
6766   bool Commuted = false;
6767   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6768   // 1,1,1,1 -> v8i16 though.
6769   V1IsSplat = isSplatVector(V1.getNode());
6770   V2IsSplat = isSplatVector(V2.getNode());
6771
6772   // Canonicalize the splat or undef, if present, to be on the RHS.
6773   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6774     CommuteVectorShuffleMask(M, NumElems);
6775     std::swap(V1, V2);
6776     std::swap(V1IsSplat, V2IsSplat);
6777     Commuted = true;
6778   }
6779
6780   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6781     // Shuffling low element of v1 into undef, just return v1.
6782     if (V2IsUndef)
6783       return V1;
6784     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6785     // the instruction selector will not match, so get a canonical MOVL with
6786     // swapped operands to undo the commute.
6787     return getMOVL(DAG, dl, VT, V2, V1);
6788   }
6789
6790   if (isUNPCKLMask(M, VT, HasAVX2))
6791     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6792
6793   if (isUNPCKHMask(M, VT, HasAVX2))
6794     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6795
6796   if (V2IsSplat) {
6797     // Normalize mask so all entries that point to V2 points to its first
6798     // element then try to match unpck{h|l} again. If match, return a
6799     // new vector_shuffle with the corrected mask.p
6800     SmallVector<int, 8> NewMask(M.begin(), M.end());
6801     NormalizeMask(NewMask, NumElems);
6802     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6803       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6804     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6805       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6806   }
6807
6808   if (Commuted) {
6809     // Commute is back and try unpck* again.
6810     // FIXME: this seems wrong.
6811     CommuteVectorShuffleMask(M, NumElems);
6812     std::swap(V1, V2);
6813     std::swap(V1IsSplat, V2IsSplat);
6814     Commuted = false;
6815
6816     if (isUNPCKLMask(M, VT, HasAVX2))
6817       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6818
6819     if (isUNPCKHMask(M, VT, HasAVX2))
6820       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6821   }
6822
6823   // Normalize the node to match x86 shuffle ops if needed
6824   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6825     return CommuteVectorShuffle(SVOp, DAG);
6826
6827   // The checks below are all present in isShuffleMaskLegal, but they are
6828   // inlined here right now to enable us to directly emit target specific
6829   // nodes, and remove one by one until they don't return Op anymore.
6830
6831   if (isPALIGNRMask(M, VT, Subtarget))
6832     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6833                                 getShufflePALIGNRImmediate(SVOp),
6834                                 DAG);
6835
6836   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6837       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6838     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6839       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6840   }
6841
6842   if (isPSHUFHWMask(M, VT, HasAVX2))
6843     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6844                                 getShufflePSHUFHWImmediate(SVOp),
6845                                 DAG);
6846
6847   if (isPSHUFLWMask(M, VT, HasAVX2))
6848     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6849                                 getShufflePSHUFLWImmediate(SVOp),
6850                                 DAG);
6851
6852   if (isSHUFPMask(M, VT, HasAVX))
6853     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6854                                 getShuffleSHUFImmediate(SVOp), DAG);
6855
6856   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6857     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6858   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6859     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6860
6861   //===--------------------------------------------------------------------===//
6862   // Generate target specific nodes for 128 or 256-bit shuffles only
6863   // supported in the AVX instruction set.
6864   //
6865
6866   // Handle VMOVDDUPY permutations
6867   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6868     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6869
6870   // Handle VPERMILPS/D* permutations
6871   if (isVPERMILPMask(M, VT, HasAVX)) {
6872     if (HasAVX2 && VT == MVT::v8i32)
6873       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6874                                   getShuffleSHUFImmediate(SVOp), DAG);
6875     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6876                                 getShuffleSHUFImmediate(SVOp), DAG);
6877   }
6878
6879   // Handle VPERM2F128/VPERM2I128 permutations
6880   if (isVPERM2X128Mask(M, VT, HasAVX))
6881     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6882                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6883
6884   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6885   if (BlendOp.getNode())
6886     return BlendOp;
6887
6888   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6889     SmallVector<SDValue, 8> permclMask;
6890     for (unsigned i = 0; i != 8; ++i) {
6891       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6892     }
6893     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6894                                &permclMask[0], 8);
6895     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6896     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6897                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6898   }
6899
6900   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6901     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6902                                 getShuffleCLImmediate(SVOp), DAG);
6903
6904
6905   //===--------------------------------------------------------------------===//
6906   // Since no target specific shuffle was selected for this generic one,
6907   // lower it into other known shuffles. FIXME: this isn't true yet, but
6908   // this is the plan.
6909   //
6910
6911   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6912   if (VT == MVT::v8i16) {
6913     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6914     if (NewOp.getNode())
6915       return NewOp;
6916   }
6917
6918   if (VT == MVT::v16i8) {
6919     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6920     if (NewOp.getNode())
6921       return NewOp;
6922   }
6923
6924   if (VT == MVT::v32i8) {
6925     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6926     if (NewOp.getNode())
6927       return NewOp;
6928   }
6929
6930   // Handle all 128-bit wide vectors with 4 elements, and match them with
6931   // several different shuffle types.
6932   if (NumElems == 4 && VT.is128BitVector())
6933     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6934
6935   // Handle general 256-bit shuffles
6936   if (VT.is256BitVector())
6937     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6938
6939   return SDValue();
6940 }
6941
6942 SDValue
6943 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6944                                                 SelectionDAG &DAG) const {
6945   EVT VT = Op.getValueType();
6946   DebugLoc dl = Op.getDebugLoc();
6947
6948   if (!Op.getOperand(0).getValueType().is128BitVector())
6949     return SDValue();
6950
6951   if (VT.getSizeInBits() == 8) {
6952     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6953                                   Op.getOperand(0), Op.getOperand(1));
6954     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6955                                   DAG.getValueType(VT));
6956     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6957   }
6958
6959   if (VT.getSizeInBits() == 16) {
6960     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6961     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6962     if (Idx == 0)
6963       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6964                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6965                                      DAG.getNode(ISD::BITCAST, dl,
6966                                                  MVT::v4i32,
6967                                                  Op.getOperand(0)),
6968                                      Op.getOperand(1)));
6969     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6970                                   Op.getOperand(0), Op.getOperand(1));
6971     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6972                                   DAG.getValueType(VT));
6973     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6974   }
6975
6976   if (VT == MVT::f32) {
6977     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6978     // the result back to FR32 register. It's only worth matching if the
6979     // result has a single use which is a store or a bitcast to i32.  And in
6980     // the case of a store, it's not worth it if the index is a constant 0,
6981     // because a MOVSSmr can be used instead, which is smaller and faster.
6982     if (!Op.hasOneUse())
6983       return SDValue();
6984     SDNode *User = *Op.getNode()->use_begin();
6985     if ((User->getOpcode() != ISD::STORE ||
6986          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6987           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6988         (User->getOpcode() != ISD::BITCAST ||
6989          User->getValueType(0) != MVT::i32))
6990       return SDValue();
6991     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6992                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6993                                               Op.getOperand(0)),
6994                                               Op.getOperand(1));
6995     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6996   }
6997
6998   if (VT == MVT::i32 || VT == MVT::i64) {
6999     // ExtractPS/pextrq works with constant index.
7000     if (isa<ConstantSDNode>(Op.getOperand(1)))
7001       return Op;
7002   }
7003   return SDValue();
7004 }
7005
7006
7007 SDValue
7008 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7009                                            SelectionDAG &DAG) const {
7010   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7011     return SDValue();
7012
7013   SDValue Vec = Op.getOperand(0);
7014   EVT VecVT = Vec.getValueType();
7015
7016   // If this is a 256-bit vector result, first extract the 128-bit vector and
7017   // then extract the element from the 128-bit vector.
7018   if (VecVT.is256BitVector()) {
7019     DebugLoc dl = Op.getNode()->getDebugLoc();
7020     unsigned NumElems = VecVT.getVectorNumElements();
7021     SDValue Idx = Op.getOperand(1);
7022     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7023
7024     // Get the 128-bit vector.
7025     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7026
7027     if (IdxVal >= NumElems/2)
7028       IdxVal -= NumElems/2;
7029     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7030                        DAG.getConstant(IdxVal, MVT::i32));
7031   }
7032
7033   assert(VecVT.is128BitVector() && "Unexpected vector length");
7034
7035   if (Subtarget->hasSSE41()) {
7036     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7037     if (Res.getNode())
7038       return Res;
7039   }
7040
7041   EVT VT = Op.getValueType();
7042   DebugLoc dl = Op.getDebugLoc();
7043   // TODO: handle v16i8.
7044   if (VT.getSizeInBits() == 16) {
7045     SDValue Vec = Op.getOperand(0);
7046     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7047     if (Idx == 0)
7048       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7049                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7050                                      DAG.getNode(ISD::BITCAST, dl,
7051                                                  MVT::v4i32, Vec),
7052                                      Op.getOperand(1)));
7053     // Transform it so it match pextrw which produces a 32-bit result.
7054     EVT EltVT = MVT::i32;
7055     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7056                                   Op.getOperand(0), Op.getOperand(1));
7057     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7058                                   DAG.getValueType(VT));
7059     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7060   }
7061
7062   if (VT.getSizeInBits() == 32) {
7063     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7064     if (Idx == 0)
7065       return Op;
7066
7067     // SHUFPS the element to the lowest double word, then movss.
7068     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7069     EVT VVT = Op.getOperand(0).getValueType();
7070     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7071                                        DAG.getUNDEF(VVT), Mask);
7072     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7073                        DAG.getIntPtrConstant(0));
7074   }
7075
7076   if (VT.getSizeInBits() == 64) {
7077     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7078     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7079     //        to match extract_elt for f64.
7080     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7081     if (Idx == 0)
7082       return Op;
7083
7084     // UNPCKHPD the element to the lowest double word, then movsd.
7085     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7086     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7087     int Mask[2] = { 1, -1 };
7088     EVT VVT = Op.getOperand(0).getValueType();
7089     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7090                                        DAG.getUNDEF(VVT), Mask);
7091     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7092                        DAG.getIntPtrConstant(0));
7093   }
7094
7095   return SDValue();
7096 }
7097
7098 SDValue
7099 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7100                                                SelectionDAG &DAG) const {
7101   EVT VT = Op.getValueType();
7102   EVT EltVT = VT.getVectorElementType();
7103   DebugLoc dl = Op.getDebugLoc();
7104
7105   SDValue N0 = Op.getOperand(0);
7106   SDValue N1 = Op.getOperand(1);
7107   SDValue N2 = Op.getOperand(2);
7108
7109   if (!VT.is128BitVector())
7110     return SDValue();
7111
7112   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7113       isa<ConstantSDNode>(N2)) {
7114     unsigned Opc;
7115     if (VT == MVT::v8i16)
7116       Opc = X86ISD::PINSRW;
7117     else if (VT == MVT::v16i8)
7118       Opc = X86ISD::PINSRB;
7119     else
7120       Opc = X86ISD::PINSRB;
7121
7122     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7123     // argument.
7124     if (N1.getValueType() != MVT::i32)
7125       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7126     if (N2.getValueType() != MVT::i32)
7127       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7128     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7129   }
7130
7131   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7132     // Bits [7:6] of the constant are the source select.  This will always be
7133     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7134     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7135     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7136     // Bits [5:4] of the constant are the destination select.  This is the
7137     //  value of the incoming immediate.
7138     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7139     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7140     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7141     // Create this as a scalar to vector..
7142     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7143     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7144   }
7145
7146   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7147     // PINSR* works with constant index.
7148     return Op;
7149   }
7150   return SDValue();
7151 }
7152
7153 SDValue
7154 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7155   EVT VT = Op.getValueType();
7156   EVT EltVT = VT.getVectorElementType();
7157
7158   DebugLoc dl = Op.getDebugLoc();
7159   SDValue N0 = Op.getOperand(0);
7160   SDValue N1 = Op.getOperand(1);
7161   SDValue N2 = Op.getOperand(2);
7162
7163   // If this is a 256-bit vector result, first extract the 128-bit vector,
7164   // insert the element into the extracted half and then place it back.
7165   if (VT.is256BitVector()) {
7166     if (!isa<ConstantSDNode>(N2))
7167       return SDValue();
7168
7169     // Get the desired 128-bit vector half.
7170     unsigned NumElems = VT.getVectorNumElements();
7171     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7172     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7173
7174     // Insert the element into the desired half.
7175     bool Upper = IdxVal >= NumElems/2;
7176     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7177                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7178
7179     // Insert the changed part back to the 256-bit vector
7180     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7181   }
7182
7183   if (Subtarget->hasSSE41())
7184     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7185
7186   if (EltVT == MVT::i8)
7187     return SDValue();
7188
7189   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7190     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7191     // as its second argument.
7192     if (N1.getValueType() != MVT::i32)
7193       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7194     if (N2.getValueType() != MVT::i32)
7195       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7196     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7197   }
7198   return SDValue();
7199 }
7200
7201 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7202   LLVMContext *Context = DAG.getContext();
7203   DebugLoc dl = Op.getDebugLoc();
7204   EVT OpVT = Op.getValueType();
7205
7206   // If this is a 256-bit vector result, first insert into a 128-bit
7207   // vector and then insert into the 256-bit vector.
7208   if (!OpVT.is128BitVector()) {
7209     // Insert into a 128-bit vector.
7210     EVT VT128 = EVT::getVectorVT(*Context,
7211                                  OpVT.getVectorElementType(),
7212                                  OpVT.getVectorNumElements() / 2);
7213
7214     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7215
7216     // Insert the 128-bit vector.
7217     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7218   }
7219
7220   if (OpVT == MVT::v1i64 &&
7221       Op.getOperand(0).getValueType() == MVT::i64)
7222     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7223
7224   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7225   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7226   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7227                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7228 }
7229
7230 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7231 // a simple subregister reference or explicit instructions to grab
7232 // upper bits of a vector.
7233 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7234                                       SelectionDAG &DAG) {
7235   if (Subtarget->hasAVX()) {
7236     DebugLoc dl = Op.getNode()->getDebugLoc();
7237     SDValue Vec = Op.getNode()->getOperand(0);
7238     SDValue Idx = Op.getNode()->getOperand(1);
7239
7240     if (Op.getNode()->getValueType(0).is128BitVector() &&
7241         Vec.getNode()->getValueType(0).is256BitVector() &&
7242         isa<ConstantSDNode>(Idx)) {
7243       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7244       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7245     }
7246   }
7247   return SDValue();
7248 }
7249
7250 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7251 // simple superregister reference or explicit instructions to insert
7252 // the upper bits of a vector.
7253 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7254                                      SelectionDAG &DAG) {
7255   if (Subtarget->hasAVX()) {
7256     DebugLoc dl = Op.getNode()->getDebugLoc();
7257     SDValue Vec = Op.getNode()->getOperand(0);
7258     SDValue SubVec = Op.getNode()->getOperand(1);
7259     SDValue Idx = Op.getNode()->getOperand(2);
7260
7261     if (Op.getNode()->getValueType(0).is256BitVector() &&
7262         SubVec.getNode()->getValueType(0).is128BitVector() &&
7263         isa<ConstantSDNode>(Idx)) {
7264       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7265       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7266     }
7267   }
7268   return SDValue();
7269 }
7270
7271 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7272 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7273 // one of the above mentioned nodes. It has to be wrapped because otherwise
7274 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7275 // be used to form addressing mode. These wrapped nodes will be selected
7276 // into MOV32ri.
7277 SDValue
7278 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7279   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7280
7281   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7282   // global base reg.
7283   unsigned char OpFlag = 0;
7284   unsigned WrapperKind = X86ISD::Wrapper;
7285   CodeModel::Model M = getTargetMachine().getCodeModel();
7286
7287   if (Subtarget->isPICStyleRIPRel() &&
7288       (M == CodeModel::Small || M == CodeModel::Kernel))
7289     WrapperKind = X86ISD::WrapperRIP;
7290   else if (Subtarget->isPICStyleGOT())
7291     OpFlag = X86II::MO_GOTOFF;
7292   else if (Subtarget->isPICStyleStubPIC())
7293     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7294
7295   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7296                                              CP->getAlignment(),
7297                                              CP->getOffset(), OpFlag);
7298   DebugLoc DL = CP->getDebugLoc();
7299   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7300   // With PIC, the address is actually $g + Offset.
7301   if (OpFlag) {
7302     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7303                          DAG.getNode(X86ISD::GlobalBaseReg,
7304                                      DebugLoc(), getPointerTy()),
7305                          Result);
7306   }
7307
7308   return Result;
7309 }
7310
7311 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7312   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7313
7314   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7315   // global base reg.
7316   unsigned char OpFlag = 0;
7317   unsigned WrapperKind = X86ISD::Wrapper;
7318   CodeModel::Model M = getTargetMachine().getCodeModel();
7319
7320   if (Subtarget->isPICStyleRIPRel() &&
7321       (M == CodeModel::Small || M == CodeModel::Kernel))
7322     WrapperKind = X86ISD::WrapperRIP;
7323   else if (Subtarget->isPICStyleGOT())
7324     OpFlag = X86II::MO_GOTOFF;
7325   else if (Subtarget->isPICStyleStubPIC())
7326     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7327
7328   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7329                                           OpFlag);
7330   DebugLoc DL = JT->getDebugLoc();
7331   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7332
7333   // With PIC, the address is actually $g + Offset.
7334   if (OpFlag)
7335     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7336                          DAG.getNode(X86ISD::GlobalBaseReg,
7337                                      DebugLoc(), getPointerTy()),
7338                          Result);
7339
7340   return Result;
7341 }
7342
7343 SDValue
7344 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7345   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7346
7347   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7348   // global base reg.
7349   unsigned char OpFlag = 0;
7350   unsigned WrapperKind = X86ISD::Wrapper;
7351   CodeModel::Model M = getTargetMachine().getCodeModel();
7352
7353   if (Subtarget->isPICStyleRIPRel() &&
7354       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7355     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7356       OpFlag = X86II::MO_GOTPCREL;
7357     WrapperKind = X86ISD::WrapperRIP;
7358   } else if (Subtarget->isPICStyleGOT()) {
7359     OpFlag = X86II::MO_GOT;
7360   } else if (Subtarget->isPICStyleStubPIC()) {
7361     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7362   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7363     OpFlag = X86II::MO_DARWIN_NONLAZY;
7364   }
7365
7366   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7367
7368   DebugLoc DL = Op.getDebugLoc();
7369   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7370
7371
7372   // With PIC, the address is actually $g + Offset.
7373   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7374       !Subtarget->is64Bit()) {
7375     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7376                          DAG.getNode(X86ISD::GlobalBaseReg,
7377                                      DebugLoc(), getPointerTy()),
7378                          Result);
7379   }
7380
7381   // For symbols that require a load from a stub to get the address, emit the
7382   // load.
7383   if (isGlobalStubReference(OpFlag))
7384     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7385                          MachinePointerInfo::getGOT(), false, false, false, 0);
7386
7387   return Result;
7388 }
7389
7390 SDValue
7391 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7392   // Create the TargetBlockAddressAddress node.
7393   unsigned char OpFlags =
7394     Subtarget->ClassifyBlockAddressReference();
7395   CodeModel::Model M = getTargetMachine().getCodeModel();
7396   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7397   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7398   DebugLoc dl = Op.getDebugLoc();
7399   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7400                                              OpFlags);
7401
7402   if (Subtarget->isPICStyleRIPRel() &&
7403       (M == CodeModel::Small || M == CodeModel::Kernel))
7404     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7405   else
7406     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7407
7408   // With PIC, the address is actually $g + Offset.
7409   if (isGlobalRelativeToPICBase(OpFlags)) {
7410     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7411                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7412                          Result);
7413   }
7414
7415   return Result;
7416 }
7417
7418 SDValue
7419 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7420                                       int64_t Offset,
7421                                       SelectionDAG &DAG) const {
7422   // Create the TargetGlobalAddress node, folding in the constant
7423   // offset if it is legal.
7424   unsigned char OpFlags =
7425     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7426   CodeModel::Model M = getTargetMachine().getCodeModel();
7427   SDValue Result;
7428   if (OpFlags == X86II::MO_NO_FLAG &&
7429       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7430     // A direct static reference to a global.
7431     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7432     Offset = 0;
7433   } else {
7434     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7435   }
7436
7437   if (Subtarget->isPICStyleRIPRel() &&
7438       (M == CodeModel::Small || M == CodeModel::Kernel))
7439     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7440   else
7441     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7442
7443   // With PIC, the address is actually $g + Offset.
7444   if (isGlobalRelativeToPICBase(OpFlags)) {
7445     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7446                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7447                          Result);
7448   }
7449
7450   // For globals that require a load from a stub to get the address, emit the
7451   // load.
7452   if (isGlobalStubReference(OpFlags))
7453     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7454                          MachinePointerInfo::getGOT(), false, false, false, 0);
7455
7456   // If there was a non-zero offset that we didn't fold, create an explicit
7457   // addition for it.
7458   if (Offset != 0)
7459     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7460                          DAG.getConstant(Offset, getPointerTy()));
7461
7462   return Result;
7463 }
7464
7465 SDValue
7466 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7467   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7468   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7469   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7470 }
7471
7472 static SDValue
7473 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7474            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7475            unsigned char OperandFlags, bool LocalDynamic = false) {
7476   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7477   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7478   DebugLoc dl = GA->getDebugLoc();
7479   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7480                                            GA->getValueType(0),
7481                                            GA->getOffset(),
7482                                            OperandFlags);
7483
7484   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7485                                            : X86ISD::TLSADDR;
7486
7487   if (InFlag) {
7488     SDValue Ops[] = { Chain,  TGA, *InFlag };
7489     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7490   } else {
7491     SDValue Ops[]  = { Chain, TGA };
7492     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7493   }
7494
7495   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7496   MFI->setAdjustsStack(true);
7497
7498   SDValue Flag = Chain.getValue(1);
7499   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7500 }
7501
7502 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7503 static SDValue
7504 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7505                                 const EVT PtrVT) {
7506   SDValue InFlag;
7507   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7508   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7509                                    DAG.getNode(X86ISD::GlobalBaseReg,
7510                                                DebugLoc(), PtrVT), InFlag);
7511   InFlag = Chain.getValue(1);
7512
7513   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7514 }
7515
7516 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7517 static SDValue
7518 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7519                                 const EVT PtrVT) {
7520   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7521                     X86::RAX, X86II::MO_TLSGD);
7522 }
7523
7524 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7525                                            SelectionDAG &DAG,
7526                                            const EVT PtrVT,
7527                                            bool is64Bit) {
7528   DebugLoc dl = GA->getDebugLoc();
7529
7530   // Get the start address of the TLS block for this module.
7531   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7532       .getInfo<X86MachineFunctionInfo>();
7533   MFI->incNumLocalDynamicTLSAccesses();
7534
7535   SDValue Base;
7536   if (is64Bit) {
7537     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7538                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7539   } else {
7540     SDValue InFlag;
7541     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7542         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7543     InFlag = Chain.getValue(1);
7544     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7545                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7546   }
7547
7548   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7549   // of Base.
7550
7551   // Build x@dtpoff.
7552   unsigned char OperandFlags = X86II::MO_DTPOFF;
7553   unsigned WrapperKind = X86ISD::Wrapper;
7554   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7555                                            GA->getValueType(0),
7556                                            GA->getOffset(), OperandFlags);
7557   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7558
7559   // Add x@dtpoff with the base.
7560   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7561 }
7562
7563 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7564 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7565                                    const EVT PtrVT, TLSModel::Model model,
7566                                    bool is64Bit, bool isPIC) {
7567   DebugLoc dl = GA->getDebugLoc();
7568
7569   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7570   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7571                                                          is64Bit ? 257 : 256));
7572
7573   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7574                                       DAG.getIntPtrConstant(0),
7575                                       MachinePointerInfo(Ptr),
7576                                       false, false, false, 0);
7577
7578   unsigned char OperandFlags = 0;
7579   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7580   // initialexec.
7581   unsigned WrapperKind = X86ISD::Wrapper;
7582   if (model == TLSModel::LocalExec) {
7583     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7584   } else if (model == TLSModel::InitialExec) {
7585     if (is64Bit) {
7586       OperandFlags = X86II::MO_GOTTPOFF;
7587       WrapperKind = X86ISD::WrapperRIP;
7588     } else {
7589       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7590     }
7591   } else {
7592     llvm_unreachable("Unexpected model");
7593   }
7594
7595   // emit "addl x@ntpoff,%eax" (local exec)
7596   // or "addl x@indntpoff,%eax" (initial exec)
7597   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7598   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7599                                            GA->getValueType(0),
7600                                            GA->getOffset(), OperandFlags);
7601   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7602
7603   if (model == TLSModel::InitialExec) {
7604     if (isPIC && !is64Bit) {
7605       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7606                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7607                            Offset);
7608     }
7609
7610     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7611                          MachinePointerInfo::getGOT(), false, false, false,
7612                          0);
7613   }
7614
7615   // The address of the thread local variable is the add of the thread
7616   // pointer with the offset of the variable.
7617   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7618 }
7619
7620 SDValue
7621 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7622
7623   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7624   const GlobalValue *GV = GA->getGlobal();
7625
7626   if (Subtarget->isTargetELF()) {
7627     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7628
7629     switch (model) {
7630       case TLSModel::GeneralDynamic:
7631         if (Subtarget->is64Bit())
7632           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7633         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7634       case TLSModel::LocalDynamic:
7635         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7636                                            Subtarget->is64Bit());
7637       case TLSModel::InitialExec:
7638       case TLSModel::LocalExec:
7639         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7640                                    Subtarget->is64Bit(),
7641                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7642     }
7643     llvm_unreachable("Unknown TLS model.");
7644   }
7645
7646   if (Subtarget->isTargetDarwin()) {
7647     // Darwin only has one model of TLS.  Lower to that.
7648     unsigned char OpFlag = 0;
7649     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7650                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7651
7652     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7653     // global base reg.
7654     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7655                   !Subtarget->is64Bit();
7656     if (PIC32)
7657       OpFlag = X86II::MO_TLVP_PIC_BASE;
7658     else
7659       OpFlag = X86II::MO_TLVP;
7660     DebugLoc DL = Op.getDebugLoc();
7661     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7662                                                 GA->getValueType(0),
7663                                                 GA->getOffset(), OpFlag);
7664     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7665
7666     // With PIC32, the address is actually $g + Offset.
7667     if (PIC32)
7668       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7669                            DAG.getNode(X86ISD::GlobalBaseReg,
7670                                        DebugLoc(), getPointerTy()),
7671                            Offset);
7672
7673     // Lowering the machine isd will make sure everything is in the right
7674     // location.
7675     SDValue Chain = DAG.getEntryNode();
7676     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7677     SDValue Args[] = { Chain, Offset };
7678     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7679
7680     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7681     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7682     MFI->setAdjustsStack(true);
7683
7684     // And our return value (tls address) is in the standard call return value
7685     // location.
7686     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7687     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7688                               Chain.getValue(1));
7689   }
7690
7691   if (Subtarget->isTargetWindows()) {
7692     // Just use the implicit TLS architecture
7693     // Need to generate someting similar to:
7694     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7695     //                                  ; from TEB
7696     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7697     //   mov     rcx, qword [rdx+rcx*8]
7698     //   mov     eax, .tls$:tlsvar
7699     //   [rax+rcx] contains the address
7700     // Windows 64bit: gs:0x58
7701     // Windows 32bit: fs:__tls_array
7702
7703     // If GV is an alias then use the aliasee for determining
7704     // thread-localness.
7705     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7706       GV = GA->resolveAliasedGlobal(false);
7707     DebugLoc dl = GA->getDebugLoc();
7708     SDValue Chain = DAG.getEntryNode();
7709
7710     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7711     // %gs:0x58 (64-bit).
7712     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7713                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7714                                                              256)
7715                                         : Type::getInt32PtrTy(*DAG.getContext(),
7716                                                               257));
7717
7718     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7719                                         Subtarget->is64Bit()
7720                                         ? DAG.getIntPtrConstant(0x58)
7721                                         : DAG.getExternalSymbol("_tls_array",
7722                                                                 getPointerTy()),
7723                                         MachinePointerInfo(Ptr),
7724                                         false, false, false, 0);
7725
7726     // Load the _tls_index variable
7727     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7728     if (Subtarget->is64Bit())
7729       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7730                            IDX, MachinePointerInfo(), MVT::i32,
7731                            false, false, 0);
7732     else
7733       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7734                         false, false, false, 0);
7735
7736     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7737                                     getPointerTy());
7738     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7739
7740     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7741     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7742                       false, false, false, 0);
7743
7744     // Get the offset of start of .tls section
7745     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7746                                              GA->getValueType(0),
7747                                              GA->getOffset(), X86II::MO_SECREL);
7748     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7749
7750     // The address of the thread local variable is the add of the thread
7751     // pointer with the offset of the variable.
7752     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7753   }
7754
7755   llvm_unreachable("TLS not implemented for this target.");
7756 }
7757
7758
7759 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7760 /// and take a 2 x i32 value to shift plus a shift amount.
7761 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7762   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7763   EVT VT = Op.getValueType();
7764   unsigned VTBits = VT.getSizeInBits();
7765   DebugLoc dl = Op.getDebugLoc();
7766   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7767   SDValue ShOpLo = Op.getOperand(0);
7768   SDValue ShOpHi = Op.getOperand(1);
7769   SDValue ShAmt  = Op.getOperand(2);
7770   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7771                                      DAG.getConstant(VTBits - 1, MVT::i8))
7772                        : DAG.getConstant(0, VT);
7773
7774   SDValue Tmp2, Tmp3;
7775   if (Op.getOpcode() == ISD::SHL_PARTS) {
7776     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7777     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7778   } else {
7779     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7780     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7781   }
7782
7783   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7784                                 DAG.getConstant(VTBits, MVT::i8));
7785   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7786                              AndNode, DAG.getConstant(0, MVT::i8));
7787
7788   SDValue Hi, Lo;
7789   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7790   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7791   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7792
7793   if (Op.getOpcode() == ISD::SHL_PARTS) {
7794     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7795     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7796   } else {
7797     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7798     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7799   }
7800
7801   SDValue Ops[2] = { Lo, Hi };
7802   return DAG.getMergeValues(Ops, 2, dl);
7803 }
7804
7805 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7806                                            SelectionDAG &DAG) const {
7807   EVT SrcVT = Op.getOperand(0).getValueType();
7808
7809   if (SrcVT.isVector())
7810     return SDValue();
7811
7812   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7813          "Unknown SINT_TO_FP to lower!");
7814
7815   // These are really Legal; return the operand so the caller accepts it as
7816   // Legal.
7817   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7818     return Op;
7819   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7820       Subtarget->is64Bit()) {
7821     return Op;
7822   }
7823
7824   DebugLoc dl = Op.getDebugLoc();
7825   unsigned Size = SrcVT.getSizeInBits()/8;
7826   MachineFunction &MF = DAG.getMachineFunction();
7827   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7828   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7829   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7830                                StackSlot,
7831                                MachinePointerInfo::getFixedStack(SSFI),
7832                                false, false, 0);
7833   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7834 }
7835
7836 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7837                                      SDValue StackSlot,
7838                                      SelectionDAG &DAG) const {
7839   // Build the FILD
7840   DebugLoc DL = Op.getDebugLoc();
7841   SDVTList Tys;
7842   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7843   if (useSSE)
7844     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7845   else
7846     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7847
7848   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7849
7850   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7851   MachineMemOperand *MMO;
7852   if (FI) {
7853     int SSFI = FI->getIndex();
7854     MMO =
7855       DAG.getMachineFunction()
7856       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7857                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7858   } else {
7859     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7860     StackSlot = StackSlot.getOperand(1);
7861   }
7862   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7863   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7864                                            X86ISD::FILD, DL,
7865                                            Tys, Ops, array_lengthof(Ops),
7866                                            SrcVT, MMO);
7867
7868   if (useSSE) {
7869     Chain = Result.getValue(1);
7870     SDValue InFlag = Result.getValue(2);
7871
7872     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7873     // shouldn't be necessary except that RFP cannot be live across
7874     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7875     MachineFunction &MF = DAG.getMachineFunction();
7876     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7877     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7878     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7879     Tys = DAG.getVTList(MVT::Other);
7880     SDValue Ops[] = {
7881       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7882     };
7883     MachineMemOperand *MMO =
7884       DAG.getMachineFunction()
7885       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7886                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7887
7888     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7889                                     Ops, array_lengthof(Ops),
7890                                     Op.getValueType(), MMO);
7891     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7892                          MachinePointerInfo::getFixedStack(SSFI),
7893                          false, false, false, 0);
7894   }
7895
7896   return Result;
7897 }
7898
7899 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7900 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7901                                                SelectionDAG &DAG) const {
7902   // This algorithm is not obvious. Here it is what we're trying to output:
7903   /*
7904      movq       %rax,  %xmm0
7905      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7906      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7907      #ifdef __SSE3__
7908        haddpd   %xmm0, %xmm0
7909      #else
7910        pshufd   $0x4e, %xmm0, %xmm1
7911        addpd    %xmm1, %xmm0
7912      #endif
7913   */
7914
7915   DebugLoc dl = Op.getDebugLoc();
7916   LLVMContext *Context = DAG.getContext();
7917
7918   // Build some magic constants.
7919   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7920   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7921   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7922
7923   SmallVector<Constant*,2> CV1;
7924   CV1.push_back(
7925         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7926   CV1.push_back(
7927         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7928   Constant *C1 = ConstantVector::get(CV1);
7929   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7930
7931   // Load the 64-bit value into an XMM register.
7932   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7933                             Op.getOperand(0));
7934   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7935                               MachinePointerInfo::getConstantPool(),
7936                               false, false, false, 16);
7937   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7938                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7939                               CLod0);
7940
7941   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7942                               MachinePointerInfo::getConstantPool(),
7943                               false, false, false, 16);
7944   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7945   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7946   SDValue Result;
7947
7948   if (Subtarget->hasSSE3()) {
7949     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7950     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7951   } else {
7952     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7953     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7954                                            S2F, 0x4E, DAG);
7955     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7956                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7957                          Sub);
7958   }
7959
7960   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7961                      DAG.getIntPtrConstant(0));
7962 }
7963
7964 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7965 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7966                                                SelectionDAG &DAG) const {
7967   DebugLoc dl = Op.getDebugLoc();
7968   // FP constant to bias correct the final result.
7969   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7970                                    MVT::f64);
7971
7972   // Load the 32-bit value into an XMM register.
7973   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7974                              Op.getOperand(0));
7975
7976   // Zero out the upper parts of the register.
7977   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7978
7979   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7980                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7981                      DAG.getIntPtrConstant(0));
7982
7983   // Or the load with the bias.
7984   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7985                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7986                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7987                                                    MVT::v2f64, Load)),
7988                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7989                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7990                                                    MVT::v2f64, Bias)));
7991   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7992                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7993                    DAG.getIntPtrConstant(0));
7994
7995   // Subtract the bias.
7996   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7997
7998   // Handle final rounding.
7999   EVT DestVT = Op.getValueType();
8000
8001   if (DestVT.bitsLT(MVT::f64))
8002     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8003                        DAG.getIntPtrConstant(0));
8004   if (DestVT.bitsGT(MVT::f64))
8005     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8006
8007   // Handle final rounding.
8008   return Sub;
8009 }
8010
8011 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8012                                            SelectionDAG &DAG) const {
8013   SDValue N0 = Op.getOperand(0);
8014   DebugLoc dl = Op.getDebugLoc();
8015
8016   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8017   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8018   // the optimization here.
8019   if (DAG.SignBitIsZero(N0))
8020     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8021
8022   EVT SrcVT = N0.getValueType();
8023   EVT DstVT = Op.getValueType();
8024   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8025     return LowerUINT_TO_FP_i64(Op, DAG);
8026   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8027     return LowerUINT_TO_FP_i32(Op, DAG);
8028   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8029     return SDValue();
8030
8031   // Make a 64-bit buffer, and use it to build an FILD.
8032   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8033   if (SrcVT == MVT::i32) {
8034     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8035     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8036                                      getPointerTy(), StackSlot, WordOff);
8037     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8038                                   StackSlot, MachinePointerInfo(),
8039                                   false, false, 0);
8040     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8041                                   OffsetSlot, MachinePointerInfo(),
8042                                   false, false, 0);
8043     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8044     return Fild;
8045   }
8046
8047   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8048   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8049                                StackSlot, MachinePointerInfo(),
8050                                false, false, 0);
8051   // For i64 source, we need to add the appropriate power of 2 if the input
8052   // was negative.  This is the same as the optimization in
8053   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8054   // we must be careful to do the computation in x87 extended precision, not
8055   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8056   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8057   MachineMemOperand *MMO =
8058     DAG.getMachineFunction()
8059     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8060                           MachineMemOperand::MOLoad, 8, 8);
8061
8062   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8063   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8064   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8065                                          MVT::i64, MMO);
8066
8067   APInt FF(32, 0x5F800000ULL);
8068
8069   // Check whether the sign bit is set.
8070   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8071                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8072                                  ISD::SETLT);
8073
8074   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8075   SDValue FudgePtr = DAG.getConstantPool(
8076                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8077                                          getPointerTy());
8078
8079   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8080   SDValue Zero = DAG.getIntPtrConstant(0);
8081   SDValue Four = DAG.getIntPtrConstant(4);
8082   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8083                                Zero, Four);
8084   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8085
8086   // Load the value out, extending it from f32 to f80.
8087   // FIXME: Avoid the extend by constructing the right constant pool?
8088   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8089                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8090                                  MVT::f32, false, false, 4);
8091   // Extend everything to 80 bits to force it to be done on x87.
8092   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8093   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8094 }
8095
8096 std::pair<SDValue,SDValue> X86TargetLowering::
8097 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8098   DebugLoc DL = Op.getDebugLoc();
8099
8100   EVT DstTy = Op.getValueType();
8101
8102   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8103     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8104     DstTy = MVT::i64;
8105   }
8106
8107   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8108          DstTy.getSimpleVT() >= MVT::i16 &&
8109          "Unknown FP_TO_INT to lower!");
8110
8111   // These are really Legal.
8112   if (DstTy == MVT::i32 &&
8113       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8114     return std::make_pair(SDValue(), SDValue());
8115   if (Subtarget->is64Bit() &&
8116       DstTy == MVT::i64 &&
8117       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8118     return std::make_pair(SDValue(), SDValue());
8119
8120   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8121   // stack slot, or into the FTOL runtime function.
8122   MachineFunction &MF = DAG.getMachineFunction();
8123   unsigned MemSize = DstTy.getSizeInBits()/8;
8124   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8125   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8126
8127   unsigned Opc;
8128   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8129     Opc = X86ISD::WIN_FTOL;
8130   else
8131     switch (DstTy.getSimpleVT().SimpleTy) {
8132     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8133     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8134     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8135     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8136     }
8137
8138   SDValue Chain = DAG.getEntryNode();
8139   SDValue Value = Op.getOperand(0);
8140   EVT TheVT = Op.getOperand(0).getValueType();
8141   // FIXME This causes a redundant load/store if the SSE-class value is already
8142   // in memory, such as if it is on the callstack.
8143   if (isScalarFPTypeInSSEReg(TheVT)) {
8144     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8145     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8146                          MachinePointerInfo::getFixedStack(SSFI),
8147                          false, false, 0);
8148     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8149     SDValue Ops[] = {
8150       Chain, StackSlot, DAG.getValueType(TheVT)
8151     };
8152
8153     MachineMemOperand *MMO =
8154       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8155                               MachineMemOperand::MOLoad, MemSize, MemSize);
8156     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8157                                     DstTy, MMO);
8158     Chain = Value.getValue(1);
8159     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8160     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8161   }
8162
8163   MachineMemOperand *MMO =
8164     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8165                             MachineMemOperand::MOStore, MemSize, MemSize);
8166
8167   if (Opc != X86ISD::WIN_FTOL) {
8168     // Build the FP_TO_INT*_IN_MEM
8169     SDValue Ops[] = { Chain, Value, StackSlot };
8170     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8171                                            Ops, 3, DstTy, MMO);
8172     return std::make_pair(FIST, StackSlot);
8173   } else {
8174     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8175       DAG.getVTList(MVT::Other, MVT::Glue),
8176       Chain, Value);
8177     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8178       MVT::i32, ftol.getValue(1));
8179     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8180       MVT::i32, eax.getValue(2));
8181     SDValue Ops[] = { eax, edx };
8182     SDValue pair = IsReplace
8183       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8184       : DAG.getMergeValues(Ops, 2, DL);
8185     return std::make_pair(pair, SDValue());
8186   }
8187 }
8188
8189 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8190   DebugLoc DL = Op.getDebugLoc();
8191   EVT VT = Op.getValueType();
8192   EVT SVT = Op.getOperand(0).getValueType();
8193
8194   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8195       VT.getVectorNumElements() != SVT.getVectorNumElements())
8196     return SDValue();
8197
8198   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8199
8200   unsigned NumElems = VT.getVectorNumElements();
8201   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8202                              NumElems * 2);
8203
8204   SDValue In = Op.getOperand(0);
8205   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8206   // Prepare truncation shuffle mask
8207   for (unsigned i = 0; i != NumElems; ++i)
8208     MaskVec[i] = i * 2;
8209   SDValue V = DAG.getVectorShuffle(NVT, DL,
8210                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8211                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8212   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8213                      DAG.getIntPtrConstant(0));
8214 }
8215
8216 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8217                                            SelectionDAG &DAG) const {
8218   if (Op.getValueType().isVector()) {
8219     if (Op.getValueType() == MVT::v8i16)
8220       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8221                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8222                                      MVT::v8i32, Op.getOperand(0)));
8223     return SDValue();
8224   }
8225
8226   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8227     /*IsSigned=*/ true, /*IsReplace=*/ false);
8228   SDValue FIST = Vals.first, StackSlot = Vals.second;
8229   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8230   if (FIST.getNode() == 0) return Op;
8231
8232   if (StackSlot.getNode())
8233     // Load the result.
8234     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8235                        FIST, StackSlot, MachinePointerInfo(),
8236                        false, false, false, 0);
8237
8238   // The node is the result.
8239   return FIST;
8240 }
8241
8242 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8243                                            SelectionDAG &DAG) const {
8244   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8245     /*IsSigned=*/ false, /*IsReplace=*/ false);
8246   SDValue FIST = Vals.first, StackSlot = Vals.second;
8247   assert(FIST.getNode() && "Unexpected failure");
8248
8249   if (StackSlot.getNode())
8250     // Load the result.
8251     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8252                        FIST, StackSlot, MachinePointerInfo(),
8253                        false, false, false, 0);
8254
8255   // The node is the result.
8256   return FIST;
8257 }
8258
8259 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8260                                           SelectionDAG &DAG) const {
8261   DebugLoc DL = Op.getDebugLoc();
8262   EVT VT = Op.getValueType();
8263   SDValue In = Op.getOperand(0);
8264   EVT SVT = In.getValueType();
8265
8266   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8267
8268   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8269                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8270                                  In, DAG.getUNDEF(SVT)));
8271 }
8272
8273 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8274   LLVMContext *Context = DAG.getContext();
8275   DebugLoc dl = Op.getDebugLoc();
8276   EVT VT = Op.getValueType();
8277   EVT EltVT = VT;
8278   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8279   if (VT.isVector()) {
8280     EltVT = VT.getVectorElementType();
8281     NumElts = VT.getVectorNumElements();
8282   }
8283   Constant *C;
8284   if (EltVT == MVT::f64)
8285     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8286   else
8287     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8288   C = ConstantVector::getSplat(NumElts, C);
8289   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8290   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8291   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8292                              MachinePointerInfo::getConstantPool(),
8293                              false, false, false, Alignment);
8294   if (VT.isVector()) {
8295     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8296     return DAG.getNode(ISD::BITCAST, dl, VT,
8297                        DAG.getNode(ISD::AND, dl, ANDVT,
8298                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8299                                                Op.getOperand(0)),
8300                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8301   }
8302   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8303 }
8304
8305 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8306   LLVMContext *Context = DAG.getContext();
8307   DebugLoc dl = Op.getDebugLoc();
8308   EVT VT = Op.getValueType();
8309   EVT EltVT = VT;
8310   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8311   if (VT.isVector()) {
8312     EltVT = VT.getVectorElementType();
8313     NumElts = VT.getVectorNumElements();
8314   }
8315   Constant *C;
8316   if (EltVT == MVT::f64)
8317     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8318   else
8319     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8320   C = ConstantVector::getSplat(NumElts, C);
8321   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8322   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8323   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8324                              MachinePointerInfo::getConstantPool(),
8325                              false, false, false, Alignment);
8326   if (VT.isVector()) {
8327     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8328     return DAG.getNode(ISD::BITCAST, dl, VT,
8329                        DAG.getNode(ISD::XOR, dl, XORVT,
8330                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8331                                                Op.getOperand(0)),
8332                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8333   }
8334
8335   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8336 }
8337
8338 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8339   LLVMContext *Context = DAG.getContext();
8340   SDValue Op0 = Op.getOperand(0);
8341   SDValue Op1 = Op.getOperand(1);
8342   DebugLoc dl = Op.getDebugLoc();
8343   EVT VT = Op.getValueType();
8344   EVT SrcVT = Op1.getValueType();
8345
8346   // If second operand is smaller, extend it first.
8347   if (SrcVT.bitsLT(VT)) {
8348     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8349     SrcVT = VT;
8350   }
8351   // And if it is bigger, shrink it first.
8352   if (SrcVT.bitsGT(VT)) {
8353     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8354     SrcVT = VT;
8355   }
8356
8357   // At this point the operands and the result should have the same
8358   // type, and that won't be f80 since that is not custom lowered.
8359
8360   // First get the sign bit of second operand.
8361   SmallVector<Constant*,4> CV;
8362   if (SrcVT == MVT::f64) {
8363     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8364     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8365   } else {
8366     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8367     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8368     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8369     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8370   }
8371   Constant *C = ConstantVector::get(CV);
8372   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8373   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8374                               MachinePointerInfo::getConstantPool(),
8375                               false, false, false, 16);
8376   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8377
8378   // Shift sign bit right or left if the two operands have different types.
8379   if (SrcVT.bitsGT(VT)) {
8380     // Op0 is MVT::f32, Op1 is MVT::f64.
8381     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8382     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8383                           DAG.getConstant(32, MVT::i32));
8384     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8385     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8386                           DAG.getIntPtrConstant(0));
8387   }
8388
8389   // Clear first operand sign bit.
8390   CV.clear();
8391   if (VT == MVT::f64) {
8392     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8393     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8394   } else {
8395     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8396     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8397     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8398     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8399   }
8400   C = ConstantVector::get(CV);
8401   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8402   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8403                               MachinePointerInfo::getConstantPool(),
8404                               false, false, false, 16);
8405   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8406
8407   // Or the value with the sign bit.
8408   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8409 }
8410
8411 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8412   SDValue N0 = Op.getOperand(0);
8413   DebugLoc dl = Op.getDebugLoc();
8414   EVT VT = Op.getValueType();
8415
8416   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8417   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8418                                   DAG.getConstant(1, VT));
8419   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8420 }
8421
8422 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8423 //
8424 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8425   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8426
8427   if (!Subtarget->hasSSE41())
8428     return SDValue();
8429
8430   if (!Op->hasOneUse())
8431     return SDValue();
8432
8433   SDNode *N = Op.getNode();
8434   DebugLoc DL = N->getDebugLoc();
8435
8436   SmallVector<SDValue, 8> Opnds;
8437   DenseMap<SDValue, unsigned> VecInMap;
8438   EVT VT = MVT::Other;
8439
8440   // Recognize a special case where a vector is casted into wide integer to
8441   // test all 0s.
8442   Opnds.push_back(N->getOperand(0));
8443   Opnds.push_back(N->getOperand(1));
8444
8445   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8446     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8447     // BFS traverse all OR'd operands.
8448     if (I->getOpcode() == ISD::OR) {
8449       Opnds.push_back(I->getOperand(0));
8450       Opnds.push_back(I->getOperand(1));
8451       // Re-evaluate the number of nodes to be traversed.
8452       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8453       continue;
8454     }
8455
8456     // Quit if a non-EXTRACT_VECTOR_ELT
8457     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8458       return SDValue();
8459
8460     // Quit if without a constant index.
8461     SDValue Idx = I->getOperand(1);
8462     if (!isa<ConstantSDNode>(Idx))
8463       return SDValue();
8464
8465     SDValue ExtractedFromVec = I->getOperand(0);
8466     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8467     if (M == VecInMap.end()) {
8468       VT = ExtractedFromVec.getValueType();
8469       // Quit if not 128/256-bit vector.
8470       if (!VT.is128BitVector() && !VT.is256BitVector())
8471         return SDValue();
8472       // Quit if not the same type.
8473       if (VecInMap.begin() != VecInMap.end() &&
8474           VT != VecInMap.begin()->first.getValueType())
8475         return SDValue();
8476       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8477     }
8478     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8479   }
8480
8481   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8482          "Not extracted from 128-/256-bit vector.");
8483
8484   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8485   SmallVector<SDValue, 8> VecIns;
8486
8487   for (DenseMap<SDValue, unsigned>::const_iterator
8488         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8489     // Quit if not all elements are used.
8490     if (I->second != FullMask)
8491       return SDValue();
8492     VecIns.push_back(I->first);
8493   }
8494
8495   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8496
8497   // Cast all vectors into TestVT for PTEST.
8498   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8499     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8500
8501   // If more than one full vectors are evaluated, OR them first before PTEST.
8502   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8503     // Each iteration will OR 2 nodes and append the result until there is only
8504     // 1 node left, i.e. the final OR'd value of all vectors.
8505     SDValue LHS = VecIns[Slot];
8506     SDValue RHS = VecIns[Slot + 1];
8507     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8508   }
8509
8510   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8511                      VecIns.back(), VecIns.back());
8512 }
8513
8514 /// Emit nodes that will be selected as "test Op0,Op0", or something
8515 /// equivalent.
8516 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8517                                     SelectionDAG &DAG) const {
8518   DebugLoc dl = Op.getDebugLoc();
8519
8520   // CF and OF aren't always set the way we want. Determine which
8521   // of these we need.
8522   bool NeedCF = false;
8523   bool NeedOF = false;
8524   switch (X86CC) {
8525   default: break;
8526   case X86::COND_A: case X86::COND_AE:
8527   case X86::COND_B: case X86::COND_BE:
8528     NeedCF = true;
8529     break;
8530   case X86::COND_G: case X86::COND_GE:
8531   case X86::COND_L: case X86::COND_LE:
8532   case X86::COND_O: case X86::COND_NO:
8533     NeedOF = true;
8534     break;
8535   }
8536
8537   // See if we can use the EFLAGS value from the operand instead of
8538   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8539   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8540   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8541     // Emit a CMP with 0, which is the TEST pattern.
8542     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8543                        DAG.getConstant(0, Op.getValueType()));
8544
8545   unsigned Opcode = 0;
8546   unsigned NumOperands = 0;
8547
8548   // Truncate operations may prevent the merge of the SETCC instruction
8549   // and the arithmetic intruction before it. Attempt to truncate the operands
8550   // of the arithmetic instruction and use a reduced bit-width instruction.
8551   bool NeedTruncation = false;
8552   SDValue ArithOp = Op;
8553   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8554     SDValue Arith = Op->getOperand(0);
8555     // Both the trunc and the arithmetic op need to have one user each.
8556     if (Arith->hasOneUse())
8557       switch (Arith.getOpcode()) {
8558         default: break;
8559         case ISD::ADD:
8560         case ISD::SUB:
8561         case ISD::AND:
8562         case ISD::OR:
8563         case ISD::XOR: {
8564           NeedTruncation = true;
8565           ArithOp = Arith;
8566         }
8567       }
8568   }
8569
8570   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8571   // which may be the result of a CAST.  We use the variable 'Op', which is the
8572   // non-casted variable when we check for possible users.
8573   switch (ArithOp.getOpcode()) {
8574   case ISD::ADD:
8575     // Due to an isel shortcoming, be conservative if this add is likely to be
8576     // selected as part of a load-modify-store instruction. When the root node
8577     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8578     // uses of other nodes in the match, such as the ADD in this case. This
8579     // leads to the ADD being left around and reselected, with the result being
8580     // two adds in the output.  Alas, even if none our users are stores, that
8581     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8582     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8583     // climbing the DAG back to the root, and it doesn't seem to be worth the
8584     // effort.
8585     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8586          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8587       if (UI->getOpcode() != ISD::CopyToReg &&
8588           UI->getOpcode() != ISD::SETCC &&
8589           UI->getOpcode() != ISD::STORE)
8590         goto default_case;
8591
8592     if (ConstantSDNode *C =
8593         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8594       // An add of one will be selected as an INC.
8595       if (C->getAPIntValue() == 1) {
8596         Opcode = X86ISD::INC;
8597         NumOperands = 1;
8598         break;
8599       }
8600
8601       // An add of negative one (subtract of one) will be selected as a DEC.
8602       if (C->getAPIntValue().isAllOnesValue()) {
8603         Opcode = X86ISD::DEC;
8604         NumOperands = 1;
8605         break;
8606       }
8607     }
8608
8609     // Otherwise use a regular EFLAGS-setting add.
8610     Opcode = X86ISD::ADD;
8611     NumOperands = 2;
8612     break;
8613   case ISD::AND: {
8614     // If the primary and result isn't used, don't bother using X86ISD::AND,
8615     // because a TEST instruction will be better.
8616     bool NonFlagUse = false;
8617     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8618            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8619       SDNode *User = *UI;
8620       unsigned UOpNo = UI.getOperandNo();
8621       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8622         // Look pass truncate.
8623         UOpNo = User->use_begin().getOperandNo();
8624         User = *User->use_begin();
8625       }
8626
8627       if (User->getOpcode() != ISD::BRCOND &&
8628           User->getOpcode() != ISD::SETCC &&
8629           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8630         NonFlagUse = true;
8631         break;
8632       }
8633     }
8634
8635     if (!NonFlagUse)
8636       break;
8637   }
8638     // FALL THROUGH
8639   case ISD::SUB:
8640   case ISD::OR:
8641   case ISD::XOR:
8642     // Due to the ISEL shortcoming noted above, be conservative if this op is
8643     // likely to be selected as part of a load-modify-store instruction.
8644     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8645            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8646       if (UI->getOpcode() == ISD::STORE)
8647         goto default_case;
8648
8649     // Otherwise use a regular EFLAGS-setting instruction.
8650     switch (ArithOp.getOpcode()) {
8651     default: llvm_unreachable("unexpected operator!");
8652     case ISD::SUB: Opcode = X86ISD::SUB; break;
8653     case ISD::XOR: Opcode = X86ISD::XOR; break;
8654     case ISD::AND: Opcode = X86ISD::AND; break;
8655     case ISD::OR: {
8656       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8657         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8658         if (EFLAGS.getNode())
8659           return EFLAGS;
8660       }
8661       Opcode = X86ISD::OR;
8662       break;
8663     }
8664     }
8665
8666     NumOperands = 2;
8667     break;
8668   case X86ISD::ADD:
8669   case X86ISD::SUB:
8670   case X86ISD::INC:
8671   case X86ISD::DEC:
8672   case X86ISD::OR:
8673   case X86ISD::XOR:
8674   case X86ISD::AND:
8675     return SDValue(Op.getNode(), 1);
8676   default:
8677   default_case:
8678     break;
8679   }
8680
8681   // If we found that truncation is beneficial, perform the truncation and
8682   // update 'Op'.
8683   if (NeedTruncation) {
8684     EVT VT = Op.getValueType();
8685     SDValue WideVal = Op->getOperand(0);
8686     EVT WideVT = WideVal.getValueType();
8687     unsigned ConvertedOp = 0;
8688     // Use a target machine opcode to prevent further DAGCombine
8689     // optimizations that may separate the arithmetic operations
8690     // from the setcc node.
8691     switch (WideVal.getOpcode()) {
8692       default: break;
8693       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8694       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8695       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8696       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8697       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8698     }
8699
8700     if (ConvertedOp) {
8701       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8702       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8703         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8704         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8705         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8706       }
8707     }
8708   }
8709
8710   if (Opcode == 0)
8711     // Emit a CMP with 0, which is the TEST pattern.
8712     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8713                        DAG.getConstant(0, Op.getValueType()));
8714
8715   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8716   SmallVector<SDValue, 4> Ops;
8717   for (unsigned i = 0; i != NumOperands; ++i)
8718     Ops.push_back(Op.getOperand(i));
8719
8720   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8721   DAG.ReplaceAllUsesWith(Op, New);
8722   return SDValue(New.getNode(), 1);
8723 }
8724
8725 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8726 /// equivalent.
8727 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8728                                    SelectionDAG &DAG) const {
8729   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8730     if (C->getAPIntValue() == 0)
8731       return EmitTest(Op0, X86CC, DAG);
8732
8733   DebugLoc dl = Op0.getDebugLoc();
8734   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8735        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8736     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8737     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8738     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8739                               Op0, Op1);
8740     return SDValue(Sub.getNode(), 1);
8741   }
8742   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8743 }
8744
8745 /// Convert a comparison if required by the subtarget.
8746 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8747                                                  SelectionDAG &DAG) const {
8748   // If the subtarget does not support the FUCOMI instruction, floating-point
8749   // comparisons have to be converted.
8750   if (Subtarget->hasCMov() ||
8751       Cmp.getOpcode() != X86ISD::CMP ||
8752       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8753       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8754     return Cmp;
8755
8756   // The instruction selector will select an FUCOM instruction instead of
8757   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8758   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8759   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8760   DebugLoc dl = Cmp.getDebugLoc();
8761   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8762   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8763   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8764                             DAG.getConstant(8, MVT::i8));
8765   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8766   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8767 }
8768
8769 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8770 /// if it's possible.
8771 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8772                                      DebugLoc dl, SelectionDAG &DAG) const {
8773   SDValue Op0 = And.getOperand(0);
8774   SDValue Op1 = And.getOperand(1);
8775   if (Op0.getOpcode() == ISD::TRUNCATE)
8776     Op0 = Op0.getOperand(0);
8777   if (Op1.getOpcode() == ISD::TRUNCATE)
8778     Op1 = Op1.getOperand(0);
8779
8780   SDValue LHS, RHS;
8781   if (Op1.getOpcode() == ISD::SHL)
8782     std::swap(Op0, Op1);
8783   if (Op0.getOpcode() == ISD::SHL) {
8784     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8785       if (And00C->getZExtValue() == 1) {
8786         // If we looked past a truncate, check that it's only truncating away
8787         // known zeros.
8788         unsigned BitWidth = Op0.getValueSizeInBits();
8789         unsigned AndBitWidth = And.getValueSizeInBits();
8790         if (BitWidth > AndBitWidth) {
8791           APInt Zeros, Ones;
8792           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8793           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8794             return SDValue();
8795         }
8796         LHS = Op1;
8797         RHS = Op0.getOperand(1);
8798       }
8799   } else if (Op1.getOpcode() == ISD::Constant) {
8800     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8801     uint64_t AndRHSVal = AndRHS->getZExtValue();
8802     SDValue AndLHS = Op0;
8803
8804     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8805       LHS = AndLHS.getOperand(0);
8806       RHS = AndLHS.getOperand(1);
8807     }
8808
8809     // Use BT if the immediate can't be encoded in a TEST instruction.
8810     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8811       LHS = AndLHS;
8812       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8813     }
8814   }
8815
8816   if (LHS.getNode()) {
8817     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8818     // instruction.  Since the shift amount is in-range-or-undefined, we know
8819     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8820     // the encoding for the i16 version is larger than the i32 version.
8821     // Also promote i16 to i32 for performance / code size reason.
8822     if (LHS.getValueType() == MVT::i8 ||
8823         LHS.getValueType() == MVT::i16)
8824       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8825
8826     // If the operand types disagree, extend the shift amount to match.  Since
8827     // BT ignores high bits (like shifts) we can use anyextend.
8828     if (LHS.getValueType() != RHS.getValueType())
8829       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8830
8831     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8832     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8833     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8834                        DAG.getConstant(Cond, MVT::i8), BT);
8835   }
8836
8837   return SDValue();
8838 }
8839
8840 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8841
8842   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8843
8844   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8845   SDValue Op0 = Op.getOperand(0);
8846   SDValue Op1 = Op.getOperand(1);
8847   DebugLoc dl = Op.getDebugLoc();
8848   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8849
8850   // Optimize to BT if possible.
8851   // Lower (X & (1 << N)) == 0 to BT(X, N).
8852   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8853   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8854   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8855       Op1.getOpcode() == ISD::Constant &&
8856       cast<ConstantSDNode>(Op1)->isNullValue() &&
8857       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8858     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8859     if (NewSetCC.getNode())
8860       return NewSetCC;
8861   }
8862
8863   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8864   // these.
8865   if (Op1.getOpcode() == ISD::Constant &&
8866       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8867        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8868       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8869
8870     // If the input is a setcc, then reuse the input setcc or use a new one with
8871     // the inverted condition.
8872     if (Op0.getOpcode() == X86ISD::SETCC) {
8873       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8874       bool Invert = (CC == ISD::SETNE) ^
8875         cast<ConstantSDNode>(Op1)->isNullValue();
8876       if (!Invert) return Op0;
8877
8878       CCode = X86::GetOppositeBranchCondition(CCode);
8879       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8880                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8881     }
8882   }
8883
8884   bool isFP = Op1.getValueType().isFloatingPoint();
8885   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8886   if (X86CC == X86::COND_INVALID)
8887     return SDValue();
8888
8889   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8890   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8891   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8892                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8893 }
8894
8895 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8896 // ones, and then concatenate the result back.
8897 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8898   EVT VT = Op.getValueType();
8899
8900   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8901          "Unsupported value type for operation");
8902
8903   unsigned NumElems = VT.getVectorNumElements();
8904   DebugLoc dl = Op.getDebugLoc();
8905   SDValue CC = Op.getOperand(2);
8906
8907   // Extract the LHS vectors
8908   SDValue LHS = Op.getOperand(0);
8909   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8910   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8911
8912   // Extract the RHS vectors
8913   SDValue RHS = Op.getOperand(1);
8914   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8915   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8916
8917   // Issue the operation on the smaller types and concatenate the result back
8918   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8919   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8920   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8921                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8922                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8923 }
8924
8925
8926 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8927   SDValue Cond;
8928   SDValue Op0 = Op.getOperand(0);
8929   SDValue Op1 = Op.getOperand(1);
8930   SDValue CC = Op.getOperand(2);
8931   EVT VT = Op.getValueType();
8932   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8933   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8934   DebugLoc dl = Op.getDebugLoc();
8935
8936   if (isFP) {
8937 #ifndef NDEBUG
8938     EVT EltVT = Op0.getValueType().getVectorElementType();
8939     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8940 #endif
8941
8942     unsigned SSECC;
8943     bool Swap = false;
8944
8945     // SSE Condition code mapping:
8946     //  0 - EQ
8947     //  1 - LT
8948     //  2 - LE
8949     //  3 - UNORD
8950     //  4 - NEQ
8951     //  5 - NLT
8952     //  6 - NLE
8953     //  7 - ORD
8954     switch (SetCCOpcode) {
8955     default: llvm_unreachable("Unexpected SETCC condition");
8956     case ISD::SETOEQ:
8957     case ISD::SETEQ:  SSECC = 0; break;
8958     case ISD::SETOGT:
8959     case ISD::SETGT: Swap = true; // Fallthrough
8960     case ISD::SETLT:
8961     case ISD::SETOLT: SSECC = 1; break;
8962     case ISD::SETOGE:
8963     case ISD::SETGE: Swap = true; // Fallthrough
8964     case ISD::SETLE:
8965     case ISD::SETOLE: SSECC = 2; break;
8966     case ISD::SETUO:  SSECC = 3; break;
8967     case ISD::SETUNE:
8968     case ISD::SETNE:  SSECC = 4; break;
8969     case ISD::SETULE: Swap = true; // Fallthrough
8970     case ISD::SETUGE: SSECC = 5; break;
8971     case ISD::SETULT: Swap = true; // Fallthrough
8972     case ISD::SETUGT: SSECC = 6; break;
8973     case ISD::SETO:   SSECC = 7; break;
8974     case ISD::SETUEQ:
8975     case ISD::SETONE: SSECC = 8; break;
8976     }
8977     if (Swap)
8978       std::swap(Op0, Op1);
8979
8980     // In the two special cases we can't handle, emit two comparisons.
8981     if (SSECC == 8) {
8982       unsigned CC0, CC1;
8983       unsigned CombineOpc;
8984       if (SetCCOpcode == ISD::SETUEQ) {
8985         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8986       } else {
8987         assert(SetCCOpcode == ISD::SETONE);
8988         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8989       }
8990
8991       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8992                                  DAG.getConstant(CC0, MVT::i8));
8993       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8994                                  DAG.getConstant(CC1, MVT::i8));
8995       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8996     }
8997     // Handle all other FP comparisons here.
8998     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8999                        DAG.getConstant(SSECC, MVT::i8));
9000   }
9001
9002   // Break 256-bit integer vector compare into smaller ones.
9003   if (VT.is256BitVector() && !Subtarget->hasAVX2())
9004     return Lower256IntVSETCC(Op, DAG);
9005
9006   // We are handling one of the integer comparisons here.  Since SSE only has
9007   // GT and EQ comparisons for integer, swapping operands and multiple
9008   // operations may be required for some comparisons.
9009   unsigned Opc;
9010   bool Swap = false, Invert = false, FlipSigns = false;
9011
9012   switch (SetCCOpcode) {
9013   default: llvm_unreachable("Unexpected SETCC condition");
9014   case ISD::SETNE:  Invert = true;
9015   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9016   case ISD::SETLT:  Swap = true;
9017   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9018   case ISD::SETGE:  Swap = true;
9019   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9020   case ISD::SETULT: Swap = true;
9021   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9022   case ISD::SETUGE: Swap = true;
9023   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9024   }
9025   if (Swap)
9026     std::swap(Op0, Op1);
9027
9028   // Check that the operation in question is available (most are plain SSE2,
9029   // but PCMPGTQ and PCMPEQQ have different requirements).
9030   if (VT == MVT::v2i64) {
9031     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9032       return SDValue();
9033     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9034       return SDValue();
9035   }
9036
9037   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9038   // bits of the inputs before performing those operations.
9039   if (FlipSigns) {
9040     EVT EltVT = VT.getVectorElementType();
9041     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9042                                       EltVT);
9043     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9044     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9045                                     SignBits.size());
9046     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9047     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9048   }
9049
9050   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9051
9052   // If the logical-not of the result is required, perform that now.
9053   if (Invert)
9054     Result = DAG.getNOT(dl, Result, VT);
9055
9056   return Result;
9057 }
9058
9059 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9060 static bool isX86LogicalCmp(SDValue Op) {
9061   unsigned Opc = Op.getNode()->getOpcode();
9062   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9063       Opc == X86ISD::SAHF)
9064     return true;
9065   if (Op.getResNo() == 1 &&
9066       (Opc == X86ISD::ADD ||
9067        Opc == X86ISD::SUB ||
9068        Opc == X86ISD::ADC ||
9069        Opc == X86ISD::SBB ||
9070        Opc == X86ISD::SMUL ||
9071        Opc == X86ISD::UMUL ||
9072        Opc == X86ISD::INC ||
9073        Opc == X86ISD::DEC ||
9074        Opc == X86ISD::OR ||
9075        Opc == X86ISD::XOR ||
9076        Opc == X86ISD::AND))
9077     return true;
9078
9079   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9080     return true;
9081
9082   return false;
9083 }
9084
9085 static bool isZero(SDValue V) {
9086   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9087   return C && C->isNullValue();
9088 }
9089
9090 static bool isAllOnes(SDValue V) {
9091   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9092   return C && C->isAllOnesValue();
9093 }
9094
9095 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9096   if (V.getOpcode() != ISD::TRUNCATE)
9097     return false;
9098
9099   SDValue VOp0 = V.getOperand(0);
9100   unsigned InBits = VOp0.getValueSizeInBits();
9101   unsigned Bits = V.getValueSizeInBits();
9102   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9103 }
9104
9105 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9106   bool addTest = true;
9107   SDValue Cond  = Op.getOperand(0);
9108   SDValue Op1 = Op.getOperand(1);
9109   SDValue Op2 = Op.getOperand(2);
9110   DebugLoc DL = Op.getDebugLoc();
9111   SDValue CC;
9112
9113   if (Cond.getOpcode() == ISD::SETCC) {
9114     SDValue NewCond = LowerSETCC(Cond, DAG);
9115     if (NewCond.getNode())
9116       Cond = NewCond;
9117   }
9118
9119   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9120   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9121   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9122   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9123   if (Cond.getOpcode() == X86ISD::SETCC &&
9124       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9125       isZero(Cond.getOperand(1).getOperand(1))) {
9126     SDValue Cmp = Cond.getOperand(1);
9127
9128     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9129
9130     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9131         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9132       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9133
9134       SDValue CmpOp0 = Cmp.getOperand(0);
9135       // Apply further optimizations for special cases
9136       // (select (x != 0), -1, 0) -> neg & sbb
9137       // (select (x == 0), 0, -1) -> neg & sbb
9138       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9139         if (YC->isNullValue() &&
9140             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9141           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9142           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9143                                     DAG.getConstant(0, CmpOp0.getValueType()),
9144                                     CmpOp0);
9145           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9146                                     DAG.getConstant(X86::COND_B, MVT::i8),
9147                                     SDValue(Neg.getNode(), 1));
9148           return Res;
9149         }
9150
9151       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9152                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9153       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9154
9155       SDValue Res =   // Res = 0 or -1.
9156         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9157                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9158
9159       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9160         Res = DAG.getNOT(DL, Res, Res.getValueType());
9161
9162       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9163       if (N2C == 0 || !N2C->isNullValue())
9164         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9165       return Res;
9166     }
9167   }
9168
9169   // Look past (and (setcc_carry (cmp ...)), 1).
9170   if (Cond.getOpcode() == ISD::AND &&
9171       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9172     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9173     if (C && C->getAPIntValue() == 1)
9174       Cond = Cond.getOperand(0);
9175   }
9176
9177   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9178   // setting operand in place of the X86ISD::SETCC.
9179   unsigned CondOpcode = Cond.getOpcode();
9180   if (CondOpcode == X86ISD::SETCC ||
9181       CondOpcode == X86ISD::SETCC_CARRY) {
9182     CC = Cond.getOperand(0);
9183
9184     SDValue Cmp = Cond.getOperand(1);
9185     unsigned Opc = Cmp.getOpcode();
9186     EVT VT = Op.getValueType();
9187
9188     bool IllegalFPCMov = false;
9189     if (VT.isFloatingPoint() && !VT.isVector() &&
9190         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9191       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9192
9193     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9194         Opc == X86ISD::BT) { // FIXME
9195       Cond = Cmp;
9196       addTest = false;
9197     }
9198   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9199              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9200              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9201               Cond.getOperand(0).getValueType() != MVT::i8)) {
9202     SDValue LHS = Cond.getOperand(0);
9203     SDValue RHS = Cond.getOperand(1);
9204     unsigned X86Opcode;
9205     unsigned X86Cond;
9206     SDVTList VTs;
9207     switch (CondOpcode) {
9208     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9209     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9210     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9211     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9212     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9213     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9214     default: llvm_unreachable("unexpected overflowing operator");
9215     }
9216     if (CondOpcode == ISD::UMULO)
9217       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9218                           MVT::i32);
9219     else
9220       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9221
9222     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9223
9224     if (CondOpcode == ISD::UMULO)
9225       Cond = X86Op.getValue(2);
9226     else
9227       Cond = X86Op.getValue(1);
9228
9229     CC = DAG.getConstant(X86Cond, MVT::i8);
9230     addTest = false;
9231   }
9232
9233   if (addTest) {
9234     // Look pass the truncate if the high bits are known zero.
9235     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9236         Cond = Cond.getOperand(0);
9237
9238     // We know the result of AND is compared against zero. Try to match
9239     // it to BT.
9240     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9241       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9242       if (NewSetCC.getNode()) {
9243         CC = NewSetCC.getOperand(0);
9244         Cond = NewSetCC.getOperand(1);
9245         addTest = false;
9246       }
9247     }
9248   }
9249
9250   if (addTest) {
9251     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9252     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9253   }
9254
9255   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9256   // a <  b ?  0 : -1 -> RES = setcc_carry
9257   // a >= b ? -1 :  0 -> RES = setcc_carry
9258   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9259   if (Cond.getOpcode() == X86ISD::SUB) {
9260     Cond = ConvertCmpIfNecessary(Cond, DAG);
9261     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9262
9263     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9264         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9265       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9266                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9267       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9268         return DAG.getNOT(DL, Res, Res.getValueType());
9269       return Res;
9270     }
9271   }
9272
9273   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9274   // widen the cmov and push the truncate through. This avoids introducing a new
9275   // branch during isel and doesn't add any extensions.
9276   if (Op.getValueType() == MVT::i8 &&
9277       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9278     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9279     if (T1.getValueType() == T2.getValueType() &&
9280         // Blacklist CopyFromReg to avoid partial register stalls.
9281         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9282       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9283       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9284       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9285     }
9286   }
9287
9288   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9289   // condition is true.
9290   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9291   SDValue Ops[] = { Op2, Op1, CC, Cond };
9292   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9293 }
9294
9295 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9296 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9297 // from the AND / OR.
9298 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9299   Opc = Op.getOpcode();
9300   if (Opc != ISD::OR && Opc != ISD::AND)
9301     return false;
9302   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9303           Op.getOperand(0).hasOneUse() &&
9304           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9305           Op.getOperand(1).hasOneUse());
9306 }
9307
9308 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9309 // 1 and that the SETCC node has a single use.
9310 static bool isXor1OfSetCC(SDValue Op) {
9311   if (Op.getOpcode() != ISD::XOR)
9312     return false;
9313   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9314   if (N1C && N1C->getAPIntValue() == 1) {
9315     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9316       Op.getOperand(0).hasOneUse();
9317   }
9318   return false;
9319 }
9320
9321 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9322   bool addTest = true;
9323   SDValue Chain = Op.getOperand(0);
9324   SDValue Cond  = Op.getOperand(1);
9325   SDValue Dest  = Op.getOperand(2);
9326   DebugLoc dl = Op.getDebugLoc();
9327   SDValue CC;
9328   bool Inverted = false;
9329
9330   if (Cond.getOpcode() == ISD::SETCC) {
9331     // Check for setcc([su]{add,sub,mul}o == 0).
9332     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9333         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9334         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9335         Cond.getOperand(0).getResNo() == 1 &&
9336         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9337          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9338          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9339          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9340          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9341          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9342       Inverted = true;
9343       Cond = Cond.getOperand(0);
9344     } else {
9345       SDValue NewCond = LowerSETCC(Cond, DAG);
9346       if (NewCond.getNode())
9347         Cond = NewCond;
9348     }
9349   }
9350 #if 0
9351   // FIXME: LowerXALUO doesn't handle these!!
9352   else if (Cond.getOpcode() == X86ISD::ADD  ||
9353            Cond.getOpcode() == X86ISD::SUB  ||
9354            Cond.getOpcode() == X86ISD::SMUL ||
9355            Cond.getOpcode() == X86ISD::UMUL)
9356     Cond = LowerXALUO(Cond, DAG);
9357 #endif
9358
9359   // Look pass (and (setcc_carry (cmp ...)), 1).
9360   if (Cond.getOpcode() == ISD::AND &&
9361       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9362     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9363     if (C && C->getAPIntValue() == 1)
9364       Cond = Cond.getOperand(0);
9365   }
9366
9367   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9368   // setting operand in place of the X86ISD::SETCC.
9369   unsigned CondOpcode = Cond.getOpcode();
9370   if (CondOpcode == X86ISD::SETCC ||
9371       CondOpcode == X86ISD::SETCC_CARRY) {
9372     CC = Cond.getOperand(0);
9373
9374     SDValue Cmp = Cond.getOperand(1);
9375     unsigned Opc = Cmp.getOpcode();
9376     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9377     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9378       Cond = Cmp;
9379       addTest = false;
9380     } else {
9381       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9382       default: break;
9383       case X86::COND_O:
9384       case X86::COND_B:
9385         // These can only come from an arithmetic instruction with overflow,
9386         // e.g. SADDO, UADDO.
9387         Cond = Cond.getNode()->getOperand(1);
9388         addTest = false;
9389         break;
9390       }
9391     }
9392   }
9393   CondOpcode = Cond.getOpcode();
9394   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9395       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9396       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9397        Cond.getOperand(0).getValueType() != MVT::i8)) {
9398     SDValue LHS = Cond.getOperand(0);
9399     SDValue RHS = Cond.getOperand(1);
9400     unsigned X86Opcode;
9401     unsigned X86Cond;
9402     SDVTList VTs;
9403     switch (CondOpcode) {
9404     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9405     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9406     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9407     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9408     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9409     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9410     default: llvm_unreachable("unexpected overflowing operator");
9411     }
9412     if (Inverted)
9413       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9414     if (CondOpcode == ISD::UMULO)
9415       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9416                           MVT::i32);
9417     else
9418       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9419
9420     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9421
9422     if (CondOpcode == ISD::UMULO)
9423       Cond = X86Op.getValue(2);
9424     else
9425       Cond = X86Op.getValue(1);
9426
9427     CC = DAG.getConstant(X86Cond, MVT::i8);
9428     addTest = false;
9429   } else {
9430     unsigned CondOpc;
9431     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9432       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9433       if (CondOpc == ISD::OR) {
9434         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9435         // two branches instead of an explicit OR instruction with a
9436         // separate test.
9437         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9438             isX86LogicalCmp(Cmp)) {
9439           CC = Cond.getOperand(0).getOperand(0);
9440           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9441                               Chain, Dest, CC, Cmp);
9442           CC = Cond.getOperand(1).getOperand(0);
9443           Cond = Cmp;
9444           addTest = false;
9445         }
9446       } else { // ISD::AND
9447         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9448         // two branches instead of an explicit AND instruction with a
9449         // separate test. However, we only do this if this block doesn't
9450         // have a fall-through edge, because this requires an explicit
9451         // jmp when the condition is false.
9452         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9453             isX86LogicalCmp(Cmp) &&
9454             Op.getNode()->hasOneUse()) {
9455           X86::CondCode CCode =
9456             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9457           CCode = X86::GetOppositeBranchCondition(CCode);
9458           CC = DAG.getConstant(CCode, MVT::i8);
9459           SDNode *User = *Op.getNode()->use_begin();
9460           // Look for an unconditional branch following this conditional branch.
9461           // We need this because we need to reverse the successors in order
9462           // to implement FCMP_OEQ.
9463           if (User->getOpcode() == ISD::BR) {
9464             SDValue FalseBB = User->getOperand(1);
9465             SDNode *NewBR =
9466               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9467             assert(NewBR == User);
9468             (void)NewBR;
9469             Dest = FalseBB;
9470
9471             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9472                                 Chain, Dest, CC, Cmp);
9473             X86::CondCode CCode =
9474               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9475             CCode = X86::GetOppositeBranchCondition(CCode);
9476             CC = DAG.getConstant(CCode, MVT::i8);
9477             Cond = Cmp;
9478             addTest = false;
9479           }
9480         }
9481       }
9482     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9483       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9484       // It should be transformed during dag combiner except when the condition
9485       // is set by a arithmetics with overflow node.
9486       X86::CondCode CCode =
9487         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9488       CCode = X86::GetOppositeBranchCondition(CCode);
9489       CC = DAG.getConstant(CCode, MVT::i8);
9490       Cond = Cond.getOperand(0).getOperand(1);
9491       addTest = false;
9492     } else if (Cond.getOpcode() == ISD::SETCC &&
9493                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9494       // For FCMP_OEQ, we can emit
9495       // two branches instead of an explicit AND instruction with a
9496       // separate test. However, we only do this if this block doesn't
9497       // have a fall-through edge, because this requires an explicit
9498       // jmp when the condition is false.
9499       if (Op.getNode()->hasOneUse()) {
9500         SDNode *User = *Op.getNode()->use_begin();
9501         // Look for an unconditional branch following this conditional branch.
9502         // We need this because we need to reverse the successors in order
9503         // to implement FCMP_OEQ.
9504         if (User->getOpcode() == ISD::BR) {
9505           SDValue FalseBB = User->getOperand(1);
9506           SDNode *NewBR =
9507             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9508           assert(NewBR == User);
9509           (void)NewBR;
9510           Dest = FalseBB;
9511
9512           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9513                                     Cond.getOperand(0), Cond.getOperand(1));
9514           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9515           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9516           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9517                               Chain, Dest, CC, Cmp);
9518           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9519           Cond = Cmp;
9520           addTest = false;
9521         }
9522       }
9523     } else if (Cond.getOpcode() == ISD::SETCC &&
9524                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9525       // For FCMP_UNE, we can emit
9526       // two branches instead of an explicit AND instruction with a
9527       // separate test. However, we only do this if this block doesn't
9528       // have a fall-through edge, because this requires an explicit
9529       // jmp when the condition is false.
9530       if (Op.getNode()->hasOneUse()) {
9531         SDNode *User = *Op.getNode()->use_begin();
9532         // Look for an unconditional branch following this conditional branch.
9533         // We need this because we need to reverse the successors in order
9534         // to implement FCMP_UNE.
9535         if (User->getOpcode() == ISD::BR) {
9536           SDValue FalseBB = User->getOperand(1);
9537           SDNode *NewBR =
9538             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9539           assert(NewBR == User);
9540           (void)NewBR;
9541
9542           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9543                                     Cond.getOperand(0), Cond.getOperand(1));
9544           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9545           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9546           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9547                               Chain, Dest, CC, Cmp);
9548           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9549           Cond = Cmp;
9550           addTest = false;
9551           Dest = FalseBB;
9552         }
9553       }
9554     }
9555   }
9556
9557   if (addTest) {
9558     // Look pass the truncate if the high bits are known zero.
9559     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9560         Cond = Cond.getOperand(0);
9561
9562     // We know the result of AND is compared against zero. Try to match
9563     // it to BT.
9564     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9565       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9566       if (NewSetCC.getNode()) {
9567         CC = NewSetCC.getOperand(0);
9568         Cond = NewSetCC.getOperand(1);
9569         addTest = false;
9570       }
9571     }
9572   }
9573
9574   if (addTest) {
9575     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9576     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9577   }
9578   Cond = ConvertCmpIfNecessary(Cond, DAG);
9579   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9580                      Chain, Dest, CC, Cond);
9581 }
9582
9583
9584 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9585 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9586 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9587 // that the guard pages used by the OS virtual memory manager are allocated in
9588 // correct sequence.
9589 SDValue
9590 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9591                                            SelectionDAG &DAG) const {
9592   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9593           getTargetMachine().Options.EnableSegmentedStacks) &&
9594          "This should be used only on Windows targets or when segmented stacks "
9595          "are being used");
9596   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9597   DebugLoc dl = Op.getDebugLoc();
9598
9599   // Get the inputs.
9600   SDValue Chain = Op.getOperand(0);
9601   SDValue Size  = Op.getOperand(1);
9602   // FIXME: Ensure alignment here
9603
9604   bool Is64Bit = Subtarget->is64Bit();
9605   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9606
9607   if (getTargetMachine().Options.EnableSegmentedStacks) {
9608     MachineFunction &MF = DAG.getMachineFunction();
9609     MachineRegisterInfo &MRI = MF.getRegInfo();
9610
9611     if (Is64Bit) {
9612       // The 64 bit implementation of segmented stacks needs to clobber both r10
9613       // r11. This makes it impossible to use it along with nested parameters.
9614       const Function *F = MF.getFunction();
9615
9616       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9617            I != E; ++I)
9618         if (I->hasNestAttr())
9619           report_fatal_error("Cannot use segmented stacks with functions that "
9620                              "have nested arguments.");
9621     }
9622
9623     const TargetRegisterClass *AddrRegClass =
9624       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9625     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9626     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9627     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9628                                 DAG.getRegister(Vreg, SPTy));
9629     SDValue Ops1[2] = { Value, Chain };
9630     return DAG.getMergeValues(Ops1, 2, dl);
9631   } else {
9632     SDValue Flag;
9633     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9634
9635     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9636     Flag = Chain.getValue(1);
9637     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9638
9639     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9640     Flag = Chain.getValue(1);
9641
9642     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9643
9644     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9645     return DAG.getMergeValues(Ops1, 2, dl);
9646   }
9647 }
9648
9649 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9650   MachineFunction &MF = DAG.getMachineFunction();
9651   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9652
9653   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9654   DebugLoc DL = Op.getDebugLoc();
9655
9656   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9657     // vastart just stores the address of the VarArgsFrameIndex slot into the
9658     // memory location argument.
9659     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9660                                    getPointerTy());
9661     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9662                         MachinePointerInfo(SV), false, false, 0);
9663   }
9664
9665   // __va_list_tag:
9666   //   gp_offset         (0 - 6 * 8)
9667   //   fp_offset         (48 - 48 + 8 * 16)
9668   //   overflow_arg_area (point to parameters coming in memory).
9669   //   reg_save_area
9670   SmallVector<SDValue, 8> MemOps;
9671   SDValue FIN = Op.getOperand(1);
9672   // Store gp_offset
9673   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9674                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9675                                                MVT::i32),
9676                                FIN, MachinePointerInfo(SV), false, false, 0);
9677   MemOps.push_back(Store);
9678
9679   // Store fp_offset
9680   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9681                     FIN, DAG.getIntPtrConstant(4));
9682   Store = DAG.getStore(Op.getOperand(0), DL,
9683                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9684                                        MVT::i32),
9685                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9686   MemOps.push_back(Store);
9687
9688   // Store ptr to overflow_arg_area
9689   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9690                     FIN, DAG.getIntPtrConstant(4));
9691   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9692                                     getPointerTy());
9693   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9694                        MachinePointerInfo(SV, 8),
9695                        false, false, 0);
9696   MemOps.push_back(Store);
9697
9698   // Store ptr to reg_save_area.
9699   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9700                     FIN, DAG.getIntPtrConstant(8));
9701   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9702                                     getPointerTy());
9703   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9704                        MachinePointerInfo(SV, 16), false, false, 0);
9705   MemOps.push_back(Store);
9706   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9707                      &MemOps[0], MemOps.size());
9708 }
9709
9710 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9711   assert(Subtarget->is64Bit() &&
9712          "LowerVAARG only handles 64-bit va_arg!");
9713   assert((Subtarget->isTargetLinux() ||
9714           Subtarget->isTargetDarwin()) &&
9715           "Unhandled target in LowerVAARG");
9716   assert(Op.getNode()->getNumOperands() == 4);
9717   SDValue Chain = Op.getOperand(0);
9718   SDValue SrcPtr = Op.getOperand(1);
9719   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9720   unsigned Align = Op.getConstantOperandVal(3);
9721   DebugLoc dl = Op.getDebugLoc();
9722
9723   EVT ArgVT = Op.getNode()->getValueType(0);
9724   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9725   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9726   uint8_t ArgMode;
9727
9728   // Decide which area this value should be read from.
9729   // TODO: Implement the AMD64 ABI in its entirety. This simple
9730   // selection mechanism works only for the basic types.
9731   if (ArgVT == MVT::f80) {
9732     llvm_unreachable("va_arg for f80 not yet implemented");
9733   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9734     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9735   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9736     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9737   } else {
9738     llvm_unreachable("Unhandled argument type in LowerVAARG");
9739   }
9740
9741   if (ArgMode == 2) {
9742     // Sanity Check: Make sure using fp_offset makes sense.
9743     assert(!getTargetMachine().Options.UseSoftFloat &&
9744            !(DAG.getMachineFunction()
9745                 .getFunction()->getFnAttributes()
9746                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9747            Subtarget->hasSSE1());
9748   }
9749
9750   // Insert VAARG_64 node into the DAG
9751   // VAARG_64 returns two values: Variable Argument Address, Chain
9752   SmallVector<SDValue, 11> InstOps;
9753   InstOps.push_back(Chain);
9754   InstOps.push_back(SrcPtr);
9755   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9756   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9757   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9758   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9759   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9760                                           VTs, &InstOps[0], InstOps.size(),
9761                                           MVT::i64,
9762                                           MachinePointerInfo(SV),
9763                                           /*Align=*/0,
9764                                           /*Volatile=*/false,
9765                                           /*ReadMem=*/true,
9766                                           /*WriteMem=*/true);
9767   Chain = VAARG.getValue(1);
9768
9769   // Load the next argument and return it
9770   return DAG.getLoad(ArgVT, dl,
9771                      Chain,
9772                      VAARG,
9773                      MachinePointerInfo(),
9774                      false, false, false, 0);
9775 }
9776
9777 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9778                            SelectionDAG &DAG) {
9779   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9780   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9781   SDValue Chain = Op.getOperand(0);
9782   SDValue DstPtr = Op.getOperand(1);
9783   SDValue SrcPtr = Op.getOperand(2);
9784   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9785   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9786   DebugLoc DL = Op.getDebugLoc();
9787
9788   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9789                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9790                        false,
9791                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9792 }
9793
9794 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9795 // may or may not be a constant. Takes immediate version of shift as input.
9796 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9797                                    SDValue SrcOp, SDValue ShAmt,
9798                                    SelectionDAG &DAG) {
9799   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9800
9801   if (isa<ConstantSDNode>(ShAmt)) {
9802     // Constant may be a TargetConstant. Use a regular constant.
9803     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9804     switch (Opc) {
9805       default: llvm_unreachable("Unknown target vector shift node");
9806       case X86ISD::VSHLI:
9807       case X86ISD::VSRLI:
9808       case X86ISD::VSRAI:
9809         return DAG.getNode(Opc, dl, VT, SrcOp,
9810                            DAG.getConstant(ShiftAmt, MVT::i32));
9811     }
9812   }
9813
9814   // Change opcode to non-immediate version
9815   switch (Opc) {
9816     default: llvm_unreachable("Unknown target vector shift node");
9817     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9818     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9819     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9820   }
9821
9822   // Need to build a vector containing shift amount
9823   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9824   SDValue ShOps[4];
9825   ShOps[0] = ShAmt;
9826   ShOps[1] = DAG.getConstant(0, MVT::i32);
9827   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9828   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9829
9830   // The return type has to be a 128-bit type with the same element
9831   // type as the input type.
9832   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9833   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9834
9835   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9836   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9837 }
9838
9839 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9840   DebugLoc dl = Op.getDebugLoc();
9841   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9842   switch (IntNo) {
9843   default: return SDValue();    // Don't custom lower most intrinsics.
9844   // Comparison intrinsics.
9845   case Intrinsic::x86_sse_comieq_ss:
9846   case Intrinsic::x86_sse_comilt_ss:
9847   case Intrinsic::x86_sse_comile_ss:
9848   case Intrinsic::x86_sse_comigt_ss:
9849   case Intrinsic::x86_sse_comige_ss:
9850   case Intrinsic::x86_sse_comineq_ss:
9851   case Intrinsic::x86_sse_ucomieq_ss:
9852   case Intrinsic::x86_sse_ucomilt_ss:
9853   case Intrinsic::x86_sse_ucomile_ss:
9854   case Intrinsic::x86_sse_ucomigt_ss:
9855   case Intrinsic::x86_sse_ucomige_ss:
9856   case Intrinsic::x86_sse_ucomineq_ss:
9857   case Intrinsic::x86_sse2_comieq_sd:
9858   case Intrinsic::x86_sse2_comilt_sd:
9859   case Intrinsic::x86_sse2_comile_sd:
9860   case Intrinsic::x86_sse2_comigt_sd:
9861   case Intrinsic::x86_sse2_comige_sd:
9862   case Intrinsic::x86_sse2_comineq_sd:
9863   case Intrinsic::x86_sse2_ucomieq_sd:
9864   case Intrinsic::x86_sse2_ucomilt_sd:
9865   case Intrinsic::x86_sse2_ucomile_sd:
9866   case Intrinsic::x86_sse2_ucomigt_sd:
9867   case Intrinsic::x86_sse2_ucomige_sd:
9868   case Intrinsic::x86_sse2_ucomineq_sd: {
9869     unsigned Opc;
9870     ISD::CondCode CC;
9871     switch (IntNo) {
9872     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9873     case Intrinsic::x86_sse_comieq_ss:
9874     case Intrinsic::x86_sse2_comieq_sd:
9875       Opc = X86ISD::COMI;
9876       CC = ISD::SETEQ;
9877       break;
9878     case Intrinsic::x86_sse_comilt_ss:
9879     case Intrinsic::x86_sse2_comilt_sd:
9880       Opc = X86ISD::COMI;
9881       CC = ISD::SETLT;
9882       break;
9883     case Intrinsic::x86_sse_comile_ss:
9884     case Intrinsic::x86_sse2_comile_sd:
9885       Opc = X86ISD::COMI;
9886       CC = ISD::SETLE;
9887       break;
9888     case Intrinsic::x86_sse_comigt_ss:
9889     case Intrinsic::x86_sse2_comigt_sd:
9890       Opc = X86ISD::COMI;
9891       CC = ISD::SETGT;
9892       break;
9893     case Intrinsic::x86_sse_comige_ss:
9894     case Intrinsic::x86_sse2_comige_sd:
9895       Opc = X86ISD::COMI;
9896       CC = ISD::SETGE;
9897       break;
9898     case Intrinsic::x86_sse_comineq_ss:
9899     case Intrinsic::x86_sse2_comineq_sd:
9900       Opc = X86ISD::COMI;
9901       CC = ISD::SETNE;
9902       break;
9903     case Intrinsic::x86_sse_ucomieq_ss:
9904     case Intrinsic::x86_sse2_ucomieq_sd:
9905       Opc = X86ISD::UCOMI;
9906       CC = ISD::SETEQ;
9907       break;
9908     case Intrinsic::x86_sse_ucomilt_ss:
9909     case Intrinsic::x86_sse2_ucomilt_sd:
9910       Opc = X86ISD::UCOMI;
9911       CC = ISD::SETLT;
9912       break;
9913     case Intrinsic::x86_sse_ucomile_ss:
9914     case Intrinsic::x86_sse2_ucomile_sd:
9915       Opc = X86ISD::UCOMI;
9916       CC = ISD::SETLE;
9917       break;
9918     case Intrinsic::x86_sse_ucomigt_ss:
9919     case Intrinsic::x86_sse2_ucomigt_sd:
9920       Opc = X86ISD::UCOMI;
9921       CC = ISD::SETGT;
9922       break;
9923     case Intrinsic::x86_sse_ucomige_ss:
9924     case Intrinsic::x86_sse2_ucomige_sd:
9925       Opc = X86ISD::UCOMI;
9926       CC = ISD::SETGE;
9927       break;
9928     case Intrinsic::x86_sse_ucomineq_ss:
9929     case Intrinsic::x86_sse2_ucomineq_sd:
9930       Opc = X86ISD::UCOMI;
9931       CC = ISD::SETNE;
9932       break;
9933     }
9934
9935     SDValue LHS = Op.getOperand(1);
9936     SDValue RHS = Op.getOperand(2);
9937     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9938     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9939     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9940     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9941                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9942     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9943   }
9944
9945   // Arithmetic intrinsics.
9946   case Intrinsic::x86_sse2_pmulu_dq:
9947   case Intrinsic::x86_avx2_pmulu_dq:
9948     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9949                        Op.getOperand(1), Op.getOperand(2));
9950
9951   // SSE3/AVX horizontal add/sub intrinsics
9952   case Intrinsic::x86_sse3_hadd_ps:
9953   case Intrinsic::x86_sse3_hadd_pd:
9954   case Intrinsic::x86_avx_hadd_ps_256:
9955   case Intrinsic::x86_avx_hadd_pd_256:
9956   case Intrinsic::x86_sse3_hsub_ps:
9957   case Intrinsic::x86_sse3_hsub_pd:
9958   case Intrinsic::x86_avx_hsub_ps_256:
9959   case Intrinsic::x86_avx_hsub_pd_256:
9960   case Intrinsic::x86_ssse3_phadd_w_128:
9961   case Intrinsic::x86_ssse3_phadd_d_128:
9962   case Intrinsic::x86_avx2_phadd_w:
9963   case Intrinsic::x86_avx2_phadd_d:
9964   case Intrinsic::x86_ssse3_phsub_w_128:
9965   case Intrinsic::x86_ssse3_phsub_d_128:
9966   case Intrinsic::x86_avx2_phsub_w:
9967   case Intrinsic::x86_avx2_phsub_d: {
9968     unsigned Opcode;
9969     switch (IntNo) {
9970     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9971     case Intrinsic::x86_sse3_hadd_ps:
9972     case Intrinsic::x86_sse3_hadd_pd:
9973     case Intrinsic::x86_avx_hadd_ps_256:
9974     case Intrinsic::x86_avx_hadd_pd_256:
9975       Opcode = X86ISD::FHADD;
9976       break;
9977     case Intrinsic::x86_sse3_hsub_ps:
9978     case Intrinsic::x86_sse3_hsub_pd:
9979     case Intrinsic::x86_avx_hsub_ps_256:
9980     case Intrinsic::x86_avx_hsub_pd_256:
9981       Opcode = X86ISD::FHSUB;
9982       break;
9983     case Intrinsic::x86_ssse3_phadd_w_128:
9984     case Intrinsic::x86_ssse3_phadd_d_128:
9985     case Intrinsic::x86_avx2_phadd_w:
9986     case Intrinsic::x86_avx2_phadd_d:
9987       Opcode = X86ISD::HADD;
9988       break;
9989     case Intrinsic::x86_ssse3_phsub_w_128:
9990     case Intrinsic::x86_ssse3_phsub_d_128:
9991     case Intrinsic::x86_avx2_phsub_w:
9992     case Intrinsic::x86_avx2_phsub_d:
9993       Opcode = X86ISD::HSUB;
9994       break;
9995     }
9996     return DAG.getNode(Opcode, dl, Op.getValueType(),
9997                        Op.getOperand(1), Op.getOperand(2));
9998   }
9999
10000   // AVX2 variable shift intrinsics
10001   case Intrinsic::x86_avx2_psllv_d:
10002   case Intrinsic::x86_avx2_psllv_q:
10003   case Intrinsic::x86_avx2_psllv_d_256:
10004   case Intrinsic::x86_avx2_psllv_q_256:
10005   case Intrinsic::x86_avx2_psrlv_d:
10006   case Intrinsic::x86_avx2_psrlv_q:
10007   case Intrinsic::x86_avx2_psrlv_d_256:
10008   case Intrinsic::x86_avx2_psrlv_q_256:
10009   case Intrinsic::x86_avx2_psrav_d:
10010   case Intrinsic::x86_avx2_psrav_d_256: {
10011     unsigned Opcode;
10012     switch (IntNo) {
10013     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10014     case Intrinsic::x86_avx2_psllv_d:
10015     case Intrinsic::x86_avx2_psllv_q:
10016     case Intrinsic::x86_avx2_psllv_d_256:
10017     case Intrinsic::x86_avx2_psllv_q_256:
10018       Opcode = ISD::SHL;
10019       break;
10020     case Intrinsic::x86_avx2_psrlv_d:
10021     case Intrinsic::x86_avx2_psrlv_q:
10022     case Intrinsic::x86_avx2_psrlv_d_256:
10023     case Intrinsic::x86_avx2_psrlv_q_256:
10024       Opcode = ISD::SRL;
10025       break;
10026     case Intrinsic::x86_avx2_psrav_d:
10027     case Intrinsic::x86_avx2_psrav_d_256:
10028       Opcode = ISD::SRA;
10029       break;
10030     }
10031     return DAG.getNode(Opcode, dl, Op.getValueType(),
10032                        Op.getOperand(1), Op.getOperand(2));
10033   }
10034
10035   case Intrinsic::x86_ssse3_pshuf_b_128:
10036   case Intrinsic::x86_avx2_pshuf_b:
10037     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10038                        Op.getOperand(1), Op.getOperand(2));
10039
10040   case Intrinsic::x86_ssse3_psign_b_128:
10041   case Intrinsic::x86_ssse3_psign_w_128:
10042   case Intrinsic::x86_ssse3_psign_d_128:
10043   case Intrinsic::x86_avx2_psign_b:
10044   case Intrinsic::x86_avx2_psign_w:
10045   case Intrinsic::x86_avx2_psign_d:
10046     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10047                        Op.getOperand(1), Op.getOperand(2));
10048
10049   case Intrinsic::x86_sse41_insertps:
10050     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10051                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10052
10053   case Intrinsic::x86_avx_vperm2f128_ps_256:
10054   case Intrinsic::x86_avx_vperm2f128_pd_256:
10055   case Intrinsic::x86_avx_vperm2f128_si_256:
10056   case Intrinsic::x86_avx2_vperm2i128:
10057     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10058                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10059
10060   case Intrinsic::x86_avx2_permd:
10061   case Intrinsic::x86_avx2_permps:
10062     // Operands intentionally swapped. Mask is last operand to intrinsic,
10063     // but second operand for node/intruction.
10064     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10065                        Op.getOperand(2), Op.getOperand(1));
10066
10067   // ptest and testp intrinsics. The intrinsic these come from are designed to
10068   // return an integer value, not just an instruction so lower it to the ptest
10069   // or testp pattern and a setcc for the result.
10070   case Intrinsic::x86_sse41_ptestz:
10071   case Intrinsic::x86_sse41_ptestc:
10072   case Intrinsic::x86_sse41_ptestnzc:
10073   case Intrinsic::x86_avx_ptestz_256:
10074   case Intrinsic::x86_avx_ptestc_256:
10075   case Intrinsic::x86_avx_ptestnzc_256:
10076   case Intrinsic::x86_avx_vtestz_ps:
10077   case Intrinsic::x86_avx_vtestc_ps:
10078   case Intrinsic::x86_avx_vtestnzc_ps:
10079   case Intrinsic::x86_avx_vtestz_pd:
10080   case Intrinsic::x86_avx_vtestc_pd:
10081   case Intrinsic::x86_avx_vtestnzc_pd:
10082   case Intrinsic::x86_avx_vtestz_ps_256:
10083   case Intrinsic::x86_avx_vtestc_ps_256:
10084   case Intrinsic::x86_avx_vtestnzc_ps_256:
10085   case Intrinsic::x86_avx_vtestz_pd_256:
10086   case Intrinsic::x86_avx_vtestc_pd_256:
10087   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10088     bool IsTestPacked = false;
10089     unsigned X86CC;
10090     switch (IntNo) {
10091     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10092     case Intrinsic::x86_avx_vtestz_ps:
10093     case Intrinsic::x86_avx_vtestz_pd:
10094     case Intrinsic::x86_avx_vtestz_ps_256:
10095     case Intrinsic::x86_avx_vtestz_pd_256:
10096       IsTestPacked = true; // Fallthrough
10097     case Intrinsic::x86_sse41_ptestz:
10098     case Intrinsic::x86_avx_ptestz_256:
10099       // ZF = 1
10100       X86CC = X86::COND_E;
10101       break;
10102     case Intrinsic::x86_avx_vtestc_ps:
10103     case Intrinsic::x86_avx_vtestc_pd:
10104     case Intrinsic::x86_avx_vtestc_ps_256:
10105     case Intrinsic::x86_avx_vtestc_pd_256:
10106       IsTestPacked = true; // Fallthrough
10107     case Intrinsic::x86_sse41_ptestc:
10108     case Intrinsic::x86_avx_ptestc_256:
10109       // CF = 1
10110       X86CC = X86::COND_B;
10111       break;
10112     case Intrinsic::x86_avx_vtestnzc_ps:
10113     case Intrinsic::x86_avx_vtestnzc_pd:
10114     case Intrinsic::x86_avx_vtestnzc_ps_256:
10115     case Intrinsic::x86_avx_vtestnzc_pd_256:
10116       IsTestPacked = true; // Fallthrough
10117     case Intrinsic::x86_sse41_ptestnzc:
10118     case Intrinsic::x86_avx_ptestnzc_256:
10119       // ZF and CF = 0
10120       X86CC = X86::COND_A;
10121       break;
10122     }
10123
10124     SDValue LHS = Op.getOperand(1);
10125     SDValue RHS = Op.getOperand(2);
10126     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10127     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10128     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10129     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10130     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10131   }
10132
10133   // SSE/AVX shift intrinsics
10134   case Intrinsic::x86_sse2_psll_w:
10135   case Intrinsic::x86_sse2_psll_d:
10136   case Intrinsic::x86_sse2_psll_q:
10137   case Intrinsic::x86_avx2_psll_w:
10138   case Intrinsic::x86_avx2_psll_d:
10139   case Intrinsic::x86_avx2_psll_q:
10140   case Intrinsic::x86_sse2_psrl_w:
10141   case Intrinsic::x86_sse2_psrl_d:
10142   case Intrinsic::x86_sse2_psrl_q:
10143   case Intrinsic::x86_avx2_psrl_w:
10144   case Intrinsic::x86_avx2_psrl_d:
10145   case Intrinsic::x86_avx2_psrl_q:
10146   case Intrinsic::x86_sse2_psra_w:
10147   case Intrinsic::x86_sse2_psra_d:
10148   case Intrinsic::x86_avx2_psra_w:
10149   case Intrinsic::x86_avx2_psra_d: {
10150     unsigned Opcode;
10151     switch (IntNo) {
10152     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10153     case Intrinsic::x86_sse2_psll_w:
10154     case Intrinsic::x86_sse2_psll_d:
10155     case Intrinsic::x86_sse2_psll_q:
10156     case Intrinsic::x86_avx2_psll_w:
10157     case Intrinsic::x86_avx2_psll_d:
10158     case Intrinsic::x86_avx2_psll_q:
10159       Opcode = X86ISD::VSHL;
10160       break;
10161     case Intrinsic::x86_sse2_psrl_w:
10162     case Intrinsic::x86_sse2_psrl_d:
10163     case Intrinsic::x86_sse2_psrl_q:
10164     case Intrinsic::x86_avx2_psrl_w:
10165     case Intrinsic::x86_avx2_psrl_d:
10166     case Intrinsic::x86_avx2_psrl_q:
10167       Opcode = X86ISD::VSRL;
10168       break;
10169     case Intrinsic::x86_sse2_psra_w:
10170     case Intrinsic::x86_sse2_psra_d:
10171     case Intrinsic::x86_avx2_psra_w:
10172     case Intrinsic::x86_avx2_psra_d:
10173       Opcode = X86ISD::VSRA;
10174       break;
10175     }
10176     return DAG.getNode(Opcode, dl, Op.getValueType(),
10177                        Op.getOperand(1), Op.getOperand(2));
10178   }
10179
10180   // SSE/AVX immediate shift intrinsics
10181   case Intrinsic::x86_sse2_pslli_w:
10182   case Intrinsic::x86_sse2_pslli_d:
10183   case Intrinsic::x86_sse2_pslli_q:
10184   case Intrinsic::x86_avx2_pslli_w:
10185   case Intrinsic::x86_avx2_pslli_d:
10186   case Intrinsic::x86_avx2_pslli_q:
10187   case Intrinsic::x86_sse2_psrli_w:
10188   case Intrinsic::x86_sse2_psrli_d:
10189   case Intrinsic::x86_sse2_psrli_q:
10190   case Intrinsic::x86_avx2_psrli_w:
10191   case Intrinsic::x86_avx2_psrli_d:
10192   case Intrinsic::x86_avx2_psrli_q:
10193   case Intrinsic::x86_sse2_psrai_w:
10194   case Intrinsic::x86_sse2_psrai_d:
10195   case Intrinsic::x86_avx2_psrai_w:
10196   case Intrinsic::x86_avx2_psrai_d: {
10197     unsigned Opcode;
10198     switch (IntNo) {
10199     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10200     case Intrinsic::x86_sse2_pslli_w:
10201     case Intrinsic::x86_sse2_pslli_d:
10202     case Intrinsic::x86_sse2_pslli_q:
10203     case Intrinsic::x86_avx2_pslli_w:
10204     case Intrinsic::x86_avx2_pslli_d:
10205     case Intrinsic::x86_avx2_pslli_q:
10206       Opcode = X86ISD::VSHLI;
10207       break;
10208     case Intrinsic::x86_sse2_psrli_w:
10209     case Intrinsic::x86_sse2_psrli_d:
10210     case Intrinsic::x86_sse2_psrli_q:
10211     case Intrinsic::x86_avx2_psrli_w:
10212     case Intrinsic::x86_avx2_psrli_d:
10213     case Intrinsic::x86_avx2_psrli_q:
10214       Opcode = X86ISD::VSRLI;
10215       break;
10216     case Intrinsic::x86_sse2_psrai_w:
10217     case Intrinsic::x86_sse2_psrai_d:
10218     case Intrinsic::x86_avx2_psrai_w:
10219     case Intrinsic::x86_avx2_psrai_d:
10220       Opcode = X86ISD::VSRAI;
10221       break;
10222     }
10223     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10224                                Op.getOperand(1), Op.getOperand(2), DAG);
10225   }
10226
10227   case Intrinsic::x86_sse42_pcmpistria128:
10228   case Intrinsic::x86_sse42_pcmpestria128:
10229   case Intrinsic::x86_sse42_pcmpistric128:
10230   case Intrinsic::x86_sse42_pcmpestric128:
10231   case Intrinsic::x86_sse42_pcmpistrio128:
10232   case Intrinsic::x86_sse42_pcmpestrio128:
10233   case Intrinsic::x86_sse42_pcmpistris128:
10234   case Intrinsic::x86_sse42_pcmpestris128:
10235   case Intrinsic::x86_sse42_pcmpistriz128:
10236   case Intrinsic::x86_sse42_pcmpestriz128: {
10237     unsigned Opcode;
10238     unsigned X86CC;
10239     switch (IntNo) {
10240     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10241     case Intrinsic::x86_sse42_pcmpistria128:
10242       Opcode = X86ISD::PCMPISTRI;
10243       X86CC = X86::COND_A;
10244       break;
10245     case Intrinsic::x86_sse42_pcmpestria128:
10246       Opcode = X86ISD::PCMPESTRI;
10247       X86CC = X86::COND_A;
10248       break;
10249     case Intrinsic::x86_sse42_pcmpistric128:
10250       Opcode = X86ISD::PCMPISTRI;
10251       X86CC = X86::COND_B;
10252       break;
10253     case Intrinsic::x86_sse42_pcmpestric128:
10254       Opcode = X86ISD::PCMPESTRI;
10255       X86CC = X86::COND_B;
10256       break;
10257     case Intrinsic::x86_sse42_pcmpistrio128:
10258       Opcode = X86ISD::PCMPISTRI;
10259       X86CC = X86::COND_O;
10260       break;
10261     case Intrinsic::x86_sse42_pcmpestrio128:
10262       Opcode = X86ISD::PCMPESTRI;
10263       X86CC = X86::COND_O;
10264       break;
10265     case Intrinsic::x86_sse42_pcmpistris128:
10266       Opcode = X86ISD::PCMPISTRI;
10267       X86CC = X86::COND_S;
10268       break;
10269     case Intrinsic::x86_sse42_pcmpestris128:
10270       Opcode = X86ISD::PCMPESTRI;
10271       X86CC = X86::COND_S;
10272       break;
10273     case Intrinsic::x86_sse42_pcmpistriz128:
10274       Opcode = X86ISD::PCMPISTRI;
10275       X86CC = X86::COND_E;
10276       break;
10277     case Intrinsic::x86_sse42_pcmpestriz128:
10278       Opcode = X86ISD::PCMPESTRI;
10279       X86CC = X86::COND_E;
10280       break;
10281     }
10282     SmallVector<SDValue, 5> NewOps;
10283     NewOps.append(Op->op_begin()+1, Op->op_end());
10284     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10285     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10286     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10287                                 DAG.getConstant(X86CC, MVT::i8),
10288                                 SDValue(PCMP.getNode(), 1));
10289     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10290   }
10291
10292   case Intrinsic::x86_sse42_pcmpistri128:
10293   case Intrinsic::x86_sse42_pcmpestri128: {
10294     unsigned Opcode;
10295     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10296       Opcode = X86ISD::PCMPISTRI;
10297     else
10298       Opcode = X86ISD::PCMPESTRI;
10299
10300     SmallVector<SDValue, 5> NewOps;
10301     NewOps.append(Op->op_begin()+1, Op->op_end());
10302     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10303     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10304   }
10305   case Intrinsic::x86_fma_vfmadd_ps:
10306   case Intrinsic::x86_fma_vfmadd_pd:
10307   case Intrinsic::x86_fma_vfmsub_ps:
10308   case Intrinsic::x86_fma_vfmsub_pd:
10309   case Intrinsic::x86_fma_vfnmadd_ps:
10310   case Intrinsic::x86_fma_vfnmadd_pd:
10311   case Intrinsic::x86_fma_vfnmsub_ps:
10312   case Intrinsic::x86_fma_vfnmsub_pd:
10313   case Intrinsic::x86_fma_vfmaddsub_ps:
10314   case Intrinsic::x86_fma_vfmaddsub_pd:
10315   case Intrinsic::x86_fma_vfmsubadd_ps:
10316   case Intrinsic::x86_fma_vfmsubadd_pd:
10317   case Intrinsic::x86_fma_vfmadd_ps_256:
10318   case Intrinsic::x86_fma_vfmadd_pd_256:
10319   case Intrinsic::x86_fma_vfmsub_ps_256:
10320   case Intrinsic::x86_fma_vfmsub_pd_256:
10321   case Intrinsic::x86_fma_vfnmadd_ps_256:
10322   case Intrinsic::x86_fma_vfnmadd_pd_256:
10323   case Intrinsic::x86_fma_vfnmsub_ps_256:
10324   case Intrinsic::x86_fma_vfnmsub_pd_256:
10325   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10326   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10327   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10328   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10329     unsigned Opc;
10330     switch (IntNo) {
10331     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10332     case Intrinsic::x86_fma_vfmadd_ps:
10333     case Intrinsic::x86_fma_vfmadd_pd:
10334     case Intrinsic::x86_fma_vfmadd_ps_256:
10335     case Intrinsic::x86_fma_vfmadd_pd_256:
10336       Opc = X86ISD::FMADD;
10337       break;
10338     case Intrinsic::x86_fma_vfmsub_ps:
10339     case Intrinsic::x86_fma_vfmsub_pd:
10340     case Intrinsic::x86_fma_vfmsub_ps_256:
10341     case Intrinsic::x86_fma_vfmsub_pd_256:
10342       Opc = X86ISD::FMSUB;
10343       break;
10344     case Intrinsic::x86_fma_vfnmadd_ps:
10345     case Intrinsic::x86_fma_vfnmadd_pd:
10346     case Intrinsic::x86_fma_vfnmadd_ps_256:
10347     case Intrinsic::x86_fma_vfnmadd_pd_256:
10348       Opc = X86ISD::FNMADD;
10349       break;
10350     case Intrinsic::x86_fma_vfnmsub_ps:
10351     case Intrinsic::x86_fma_vfnmsub_pd:
10352     case Intrinsic::x86_fma_vfnmsub_ps_256:
10353     case Intrinsic::x86_fma_vfnmsub_pd_256:
10354       Opc = X86ISD::FNMSUB;
10355       break;
10356     case Intrinsic::x86_fma_vfmaddsub_ps:
10357     case Intrinsic::x86_fma_vfmaddsub_pd:
10358     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10359     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10360       Opc = X86ISD::FMADDSUB;
10361       break;
10362     case Intrinsic::x86_fma_vfmsubadd_ps:
10363     case Intrinsic::x86_fma_vfmsubadd_pd:
10364     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10365     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10366       Opc = X86ISD::FMSUBADD;
10367       break;
10368     }
10369
10370     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10371                        Op.getOperand(2), Op.getOperand(3));
10372   }
10373   }
10374 }
10375
10376 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10377   DebugLoc dl = Op.getDebugLoc();
10378   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10379   switch (IntNo) {
10380   default: return SDValue();    // Don't custom lower most intrinsics.
10381
10382   // RDRAND intrinsics.
10383   case Intrinsic::x86_rdrand_16:
10384   case Intrinsic::x86_rdrand_32:
10385   case Intrinsic::x86_rdrand_64: {
10386     // Emit the node with the right value type.
10387     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10388     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10389
10390     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10391     // return the value from Rand, which is always 0, casted to i32.
10392     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10393                       DAG.getConstant(1, Op->getValueType(1)),
10394                       DAG.getConstant(X86::COND_B, MVT::i32),
10395                       SDValue(Result.getNode(), 1) };
10396     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10397                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10398                                   Ops, 4);
10399
10400     // Return { result, isValid, chain }.
10401     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10402                        SDValue(Result.getNode(), 2));
10403   }
10404   }
10405 }
10406
10407 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10408                                            SelectionDAG &DAG) const {
10409   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10410   MFI->setReturnAddressIsTaken(true);
10411
10412   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10413   DebugLoc dl = Op.getDebugLoc();
10414
10415   if (Depth > 0) {
10416     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10417     SDValue Offset =
10418       DAG.getConstant(TD->getPointerSize(0),
10419                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10420     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10421                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10422                                    FrameAddr, Offset),
10423                        MachinePointerInfo(), false, false, false, 0);
10424   }
10425
10426   // Just load the return address.
10427   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10428   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10429                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10430 }
10431
10432 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10433   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10434   MFI->setFrameAddressIsTaken(true);
10435
10436   EVT VT = Op.getValueType();
10437   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10438   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10439   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10440   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10441   while (Depth--)
10442     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10443                             MachinePointerInfo(),
10444                             false, false, false, 0);
10445   return FrameAddr;
10446 }
10447
10448 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10449                                                      SelectionDAG &DAG) const {
10450   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10451 }
10452
10453 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10454   SDValue Chain     = Op.getOperand(0);
10455   SDValue Offset    = Op.getOperand(1);
10456   SDValue Handler   = Op.getOperand(2);
10457   DebugLoc dl       = Op.getDebugLoc();
10458
10459   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10460                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10461                                      getPointerTy());
10462   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10463
10464   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10465                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10466   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10467   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10468                        false, false, 0);
10469   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10470
10471   return DAG.getNode(X86ISD::EH_RETURN, dl,
10472                      MVT::Other,
10473                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10474 }
10475
10476 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10477                                                SelectionDAG &DAG) const {
10478   DebugLoc DL = Op.getDebugLoc();
10479   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10480                      DAG.getVTList(MVT::i32, MVT::Other),
10481                      Op.getOperand(0), Op.getOperand(1));
10482 }
10483
10484 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10485                                                 SelectionDAG &DAG) const {
10486   DebugLoc DL = Op.getDebugLoc();
10487   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10488                      Op.getOperand(0), Op.getOperand(1));
10489 }
10490
10491 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10492   return Op.getOperand(0);
10493 }
10494
10495 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10496                                                 SelectionDAG &DAG) const {
10497   SDValue Root = Op.getOperand(0);
10498   SDValue Trmp = Op.getOperand(1); // trampoline
10499   SDValue FPtr = Op.getOperand(2); // nested function
10500   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10501   DebugLoc dl  = Op.getDebugLoc();
10502
10503   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10504   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10505
10506   if (Subtarget->is64Bit()) {
10507     SDValue OutChains[6];
10508
10509     // Large code-model.
10510     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10511     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10512
10513     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10514     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10515
10516     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10517
10518     // Load the pointer to the nested function into R11.
10519     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10520     SDValue Addr = Trmp;
10521     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10522                                 Addr, MachinePointerInfo(TrmpAddr),
10523                                 false, false, 0);
10524
10525     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10526                        DAG.getConstant(2, MVT::i64));
10527     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10528                                 MachinePointerInfo(TrmpAddr, 2),
10529                                 false, false, 2);
10530
10531     // Load the 'nest' parameter value into R10.
10532     // R10 is specified in X86CallingConv.td
10533     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10534     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10535                        DAG.getConstant(10, MVT::i64));
10536     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10537                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10538                                 false, false, 0);
10539
10540     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10541                        DAG.getConstant(12, MVT::i64));
10542     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10543                                 MachinePointerInfo(TrmpAddr, 12),
10544                                 false, false, 2);
10545
10546     // Jump to the nested function.
10547     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10549                        DAG.getConstant(20, MVT::i64));
10550     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10551                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10552                                 false, false, 0);
10553
10554     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10555     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10556                        DAG.getConstant(22, MVT::i64));
10557     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10558                                 MachinePointerInfo(TrmpAddr, 22),
10559                                 false, false, 0);
10560
10561     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10562   } else {
10563     const Function *Func =
10564       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10565     CallingConv::ID CC = Func->getCallingConv();
10566     unsigned NestReg;
10567
10568     switch (CC) {
10569     default:
10570       llvm_unreachable("Unsupported calling convention");
10571     case CallingConv::C:
10572     case CallingConv::X86_StdCall: {
10573       // Pass 'nest' parameter in ECX.
10574       // Must be kept in sync with X86CallingConv.td
10575       NestReg = X86::ECX;
10576
10577       // Check that ECX wasn't needed by an 'inreg' parameter.
10578       FunctionType *FTy = Func->getFunctionType();
10579       const AttrListPtr &Attrs = Func->getAttributes();
10580
10581       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10582         unsigned InRegCount = 0;
10583         unsigned Idx = 1;
10584
10585         for (FunctionType::param_iterator I = FTy->param_begin(),
10586              E = FTy->param_end(); I != E; ++I, ++Idx)
10587           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10588             // FIXME: should only count parameters that are lowered to integers.
10589             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10590
10591         if (InRegCount > 2) {
10592           report_fatal_error("Nest register in use - reduce number of inreg"
10593                              " parameters!");
10594         }
10595       }
10596       break;
10597     }
10598     case CallingConv::X86_FastCall:
10599     case CallingConv::X86_ThisCall:
10600     case CallingConv::Fast:
10601       // Pass 'nest' parameter in EAX.
10602       // Must be kept in sync with X86CallingConv.td
10603       NestReg = X86::EAX;
10604       break;
10605     }
10606
10607     SDValue OutChains[4];
10608     SDValue Addr, Disp;
10609
10610     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10611                        DAG.getConstant(10, MVT::i32));
10612     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10613
10614     // This is storing the opcode for MOV32ri.
10615     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10616     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10617     OutChains[0] = DAG.getStore(Root, dl,
10618                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10619                                 Trmp, MachinePointerInfo(TrmpAddr),
10620                                 false, false, 0);
10621
10622     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10623                        DAG.getConstant(1, MVT::i32));
10624     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10625                                 MachinePointerInfo(TrmpAddr, 1),
10626                                 false, false, 1);
10627
10628     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10629     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10630                        DAG.getConstant(5, MVT::i32));
10631     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10632                                 MachinePointerInfo(TrmpAddr, 5),
10633                                 false, false, 1);
10634
10635     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10636                        DAG.getConstant(6, MVT::i32));
10637     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10638                                 MachinePointerInfo(TrmpAddr, 6),
10639                                 false, false, 1);
10640
10641     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10642   }
10643 }
10644
10645 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10646                                             SelectionDAG &DAG) const {
10647   /*
10648    The rounding mode is in bits 11:10 of FPSR, and has the following
10649    settings:
10650      00 Round to nearest
10651      01 Round to -inf
10652      10 Round to +inf
10653      11 Round to 0
10654
10655   FLT_ROUNDS, on the other hand, expects the following:
10656     -1 Undefined
10657      0 Round to 0
10658      1 Round to nearest
10659      2 Round to +inf
10660      3 Round to -inf
10661
10662   To perform the conversion, we do:
10663     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10664   */
10665
10666   MachineFunction &MF = DAG.getMachineFunction();
10667   const TargetMachine &TM = MF.getTarget();
10668   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10669   unsigned StackAlignment = TFI.getStackAlignment();
10670   EVT VT = Op.getValueType();
10671   DebugLoc DL = Op.getDebugLoc();
10672
10673   // Save FP Control Word to stack slot
10674   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10675   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10676
10677
10678   MachineMemOperand *MMO =
10679    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10680                            MachineMemOperand::MOStore, 2, 2);
10681
10682   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10683   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10684                                           DAG.getVTList(MVT::Other),
10685                                           Ops, 2, MVT::i16, MMO);
10686
10687   // Load FP Control Word from stack slot
10688   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10689                             MachinePointerInfo(), false, false, false, 0);
10690
10691   // Transform as necessary
10692   SDValue CWD1 =
10693     DAG.getNode(ISD::SRL, DL, MVT::i16,
10694                 DAG.getNode(ISD::AND, DL, MVT::i16,
10695                             CWD, DAG.getConstant(0x800, MVT::i16)),
10696                 DAG.getConstant(11, MVT::i8));
10697   SDValue CWD2 =
10698     DAG.getNode(ISD::SRL, DL, MVT::i16,
10699                 DAG.getNode(ISD::AND, DL, MVT::i16,
10700                             CWD, DAG.getConstant(0x400, MVT::i16)),
10701                 DAG.getConstant(9, MVT::i8));
10702
10703   SDValue RetVal =
10704     DAG.getNode(ISD::AND, DL, MVT::i16,
10705                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10706                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10707                             DAG.getConstant(1, MVT::i16)),
10708                 DAG.getConstant(3, MVT::i16));
10709
10710
10711   return DAG.getNode((VT.getSizeInBits() < 16 ?
10712                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10713 }
10714
10715 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10716   EVT VT = Op.getValueType();
10717   EVT OpVT = VT;
10718   unsigned NumBits = VT.getSizeInBits();
10719   DebugLoc dl = Op.getDebugLoc();
10720
10721   Op = Op.getOperand(0);
10722   if (VT == MVT::i8) {
10723     // Zero extend to i32 since there is not an i8 bsr.
10724     OpVT = MVT::i32;
10725     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10726   }
10727
10728   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10729   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10730   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10731
10732   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10733   SDValue Ops[] = {
10734     Op,
10735     DAG.getConstant(NumBits+NumBits-1, OpVT),
10736     DAG.getConstant(X86::COND_E, MVT::i8),
10737     Op.getValue(1)
10738   };
10739   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10740
10741   // Finally xor with NumBits-1.
10742   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10743
10744   if (VT == MVT::i8)
10745     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10746   return Op;
10747 }
10748
10749 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10750   EVT VT = Op.getValueType();
10751   EVT OpVT = VT;
10752   unsigned NumBits = VT.getSizeInBits();
10753   DebugLoc dl = Op.getDebugLoc();
10754
10755   Op = Op.getOperand(0);
10756   if (VT == MVT::i8) {
10757     // Zero extend to i32 since there is not an i8 bsr.
10758     OpVT = MVT::i32;
10759     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10760   }
10761
10762   // Issue a bsr (scan bits in reverse).
10763   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10764   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10765
10766   // And xor with NumBits-1.
10767   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10768
10769   if (VT == MVT::i8)
10770     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10771   return Op;
10772 }
10773
10774 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10775   EVT VT = Op.getValueType();
10776   unsigned NumBits = VT.getSizeInBits();
10777   DebugLoc dl = Op.getDebugLoc();
10778   Op = Op.getOperand(0);
10779
10780   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10781   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10782   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10783
10784   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10785   SDValue Ops[] = {
10786     Op,
10787     DAG.getConstant(NumBits, VT),
10788     DAG.getConstant(X86::COND_E, MVT::i8),
10789     Op.getValue(1)
10790   };
10791   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10792 }
10793
10794 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10795 // ones, and then concatenate the result back.
10796 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10797   EVT VT = Op.getValueType();
10798
10799   assert(VT.is256BitVector() && VT.isInteger() &&
10800          "Unsupported value type for operation");
10801
10802   unsigned NumElems = VT.getVectorNumElements();
10803   DebugLoc dl = Op.getDebugLoc();
10804
10805   // Extract the LHS vectors
10806   SDValue LHS = Op.getOperand(0);
10807   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10808   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10809
10810   // Extract the RHS vectors
10811   SDValue RHS = Op.getOperand(1);
10812   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10813   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10814
10815   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10816   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10817
10818   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10819                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10820                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10821 }
10822
10823 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10824   assert(Op.getValueType().is256BitVector() &&
10825          Op.getValueType().isInteger() &&
10826          "Only handle AVX 256-bit vector integer operation");
10827   return Lower256IntArith(Op, DAG);
10828 }
10829
10830 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10831   assert(Op.getValueType().is256BitVector() &&
10832          Op.getValueType().isInteger() &&
10833          "Only handle AVX 256-bit vector integer operation");
10834   return Lower256IntArith(Op, DAG);
10835 }
10836
10837 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10838                         SelectionDAG &DAG) {
10839   EVT VT = Op.getValueType();
10840
10841   // Decompose 256-bit ops into smaller 128-bit ops.
10842   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10843     return Lower256IntArith(Op, DAG);
10844
10845   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10846          "Only know how to lower V2I64/V4I64 multiply");
10847
10848   DebugLoc dl = Op.getDebugLoc();
10849
10850   //  Ahi = psrlqi(a, 32);
10851   //  Bhi = psrlqi(b, 32);
10852   //
10853   //  AloBlo = pmuludq(a, b);
10854   //  AloBhi = pmuludq(a, Bhi);
10855   //  AhiBlo = pmuludq(Ahi, b);
10856
10857   //  AloBhi = psllqi(AloBhi, 32);
10858   //  AhiBlo = psllqi(AhiBlo, 32);
10859   //  return AloBlo + AloBhi + AhiBlo;
10860
10861   SDValue A = Op.getOperand(0);
10862   SDValue B = Op.getOperand(1);
10863
10864   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10865
10866   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10867   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10868
10869   // Bit cast to 32-bit vectors for MULUDQ
10870   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10871   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10872   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10873   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10874   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10875
10876   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10877   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10878   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10879
10880   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10881   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10882
10883   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10884   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10885 }
10886
10887 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10888
10889   EVT VT = Op.getValueType();
10890   DebugLoc dl = Op.getDebugLoc();
10891   SDValue R = Op.getOperand(0);
10892   SDValue Amt = Op.getOperand(1);
10893   LLVMContext *Context = DAG.getContext();
10894
10895   if (!Subtarget->hasSSE2())
10896     return SDValue();
10897
10898   // Optimize shl/srl/sra with constant shift amount.
10899   if (isSplatVector(Amt.getNode())) {
10900     SDValue SclrAmt = Amt->getOperand(0);
10901     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10902       uint64_t ShiftAmt = C->getZExtValue();
10903
10904       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10905           (Subtarget->hasAVX2() &&
10906            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10907         if (Op.getOpcode() == ISD::SHL)
10908           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10909                              DAG.getConstant(ShiftAmt, MVT::i32));
10910         if (Op.getOpcode() == ISD::SRL)
10911           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10912                              DAG.getConstant(ShiftAmt, MVT::i32));
10913         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10914           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10915                              DAG.getConstant(ShiftAmt, MVT::i32));
10916       }
10917
10918       if (VT == MVT::v16i8) {
10919         if (Op.getOpcode() == ISD::SHL) {
10920           // Make a large shift.
10921           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10922                                     DAG.getConstant(ShiftAmt, MVT::i32));
10923           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10924           // Zero out the rightmost bits.
10925           SmallVector<SDValue, 16> V(16,
10926                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10927                                                      MVT::i8));
10928           return DAG.getNode(ISD::AND, dl, VT, SHL,
10929                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10930         }
10931         if (Op.getOpcode() == ISD::SRL) {
10932           // Make a large shift.
10933           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10934                                     DAG.getConstant(ShiftAmt, MVT::i32));
10935           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10936           // Zero out the leftmost bits.
10937           SmallVector<SDValue, 16> V(16,
10938                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10939                                                      MVT::i8));
10940           return DAG.getNode(ISD::AND, dl, VT, SRL,
10941                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10942         }
10943         if (Op.getOpcode() == ISD::SRA) {
10944           if (ShiftAmt == 7) {
10945             // R s>> 7  ===  R s< 0
10946             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10947             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10948           }
10949
10950           // R s>> a === ((R u>> a) ^ m) - m
10951           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10952           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10953                                                          MVT::i8));
10954           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10955           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10956           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10957           return Res;
10958         }
10959         llvm_unreachable("Unknown shift opcode.");
10960       }
10961
10962       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10963         if (Op.getOpcode() == ISD::SHL) {
10964           // Make a large shift.
10965           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10966                                     DAG.getConstant(ShiftAmt, MVT::i32));
10967           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10968           // Zero out the rightmost bits.
10969           SmallVector<SDValue, 32> V(32,
10970                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10971                                                      MVT::i8));
10972           return DAG.getNode(ISD::AND, dl, VT, SHL,
10973                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10974         }
10975         if (Op.getOpcode() == ISD::SRL) {
10976           // Make a large shift.
10977           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10978                                     DAG.getConstant(ShiftAmt, MVT::i32));
10979           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10980           // Zero out the leftmost bits.
10981           SmallVector<SDValue, 32> V(32,
10982                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10983                                                      MVT::i8));
10984           return DAG.getNode(ISD::AND, dl, VT, SRL,
10985                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10986         }
10987         if (Op.getOpcode() == ISD::SRA) {
10988           if (ShiftAmt == 7) {
10989             // R s>> 7  ===  R s< 0
10990             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10991             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10992           }
10993
10994           // R s>> a === ((R u>> a) ^ m) - m
10995           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10996           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10997                                                          MVT::i8));
10998           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10999           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11000           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11001           return Res;
11002         }
11003         llvm_unreachable("Unknown shift opcode.");
11004       }
11005     }
11006   }
11007
11008   // Lower SHL with variable shift amount.
11009   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11010     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11011                      DAG.getConstant(23, MVT::i32));
11012
11013     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11014     Constant *C = ConstantDataVector::get(*Context, CV);
11015     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11016     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11017                                  MachinePointerInfo::getConstantPool(),
11018                                  false, false, false, 16);
11019
11020     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11021     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11022     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11023     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11024   }
11025   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11026     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11027
11028     // a = a << 5;
11029     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11030                      DAG.getConstant(5, MVT::i32));
11031     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11032
11033     // Turn 'a' into a mask suitable for VSELECT
11034     SDValue VSelM = DAG.getConstant(0x80, VT);
11035     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11036     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11037
11038     SDValue CM1 = DAG.getConstant(0x0f, VT);
11039     SDValue CM2 = DAG.getConstant(0x3f, VT);
11040
11041     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11042     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11043     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11044                             DAG.getConstant(4, MVT::i32), DAG);
11045     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11046     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11047
11048     // a += a
11049     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11050     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11051     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11052
11053     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11054     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11055     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11056                             DAG.getConstant(2, MVT::i32), DAG);
11057     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11058     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11059
11060     // a += a
11061     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11062     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11063     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11064
11065     // return VSELECT(r, r+r, a);
11066     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11067                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11068     return R;
11069   }
11070
11071   // Decompose 256-bit shifts into smaller 128-bit shifts.
11072   if (VT.is256BitVector()) {
11073     unsigned NumElems = VT.getVectorNumElements();
11074     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11075     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11076
11077     // Extract the two vectors
11078     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11079     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11080
11081     // Recreate the shift amount vectors
11082     SDValue Amt1, Amt2;
11083     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11084       // Constant shift amount
11085       SmallVector<SDValue, 4> Amt1Csts;
11086       SmallVector<SDValue, 4> Amt2Csts;
11087       for (unsigned i = 0; i != NumElems/2; ++i)
11088         Amt1Csts.push_back(Amt->getOperand(i));
11089       for (unsigned i = NumElems/2; i != NumElems; ++i)
11090         Amt2Csts.push_back(Amt->getOperand(i));
11091
11092       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11093                                  &Amt1Csts[0], NumElems/2);
11094       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11095                                  &Amt2Csts[0], NumElems/2);
11096     } else {
11097       // Variable shift amount
11098       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11099       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11100     }
11101
11102     // Issue new vector shifts for the smaller types
11103     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11104     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11105
11106     // Concatenate the result back
11107     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11108   }
11109
11110   return SDValue();
11111 }
11112
11113 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11114   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11115   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11116   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11117   // has only one use.
11118   SDNode *N = Op.getNode();
11119   SDValue LHS = N->getOperand(0);
11120   SDValue RHS = N->getOperand(1);
11121   unsigned BaseOp = 0;
11122   unsigned Cond = 0;
11123   DebugLoc DL = Op.getDebugLoc();
11124   switch (Op.getOpcode()) {
11125   default: llvm_unreachable("Unknown ovf instruction!");
11126   case ISD::SADDO:
11127     // A subtract of one will be selected as a INC. Note that INC doesn't
11128     // set CF, so we can't do this for UADDO.
11129     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11130       if (C->isOne()) {
11131         BaseOp = X86ISD::INC;
11132         Cond = X86::COND_O;
11133         break;
11134       }
11135     BaseOp = X86ISD::ADD;
11136     Cond = X86::COND_O;
11137     break;
11138   case ISD::UADDO:
11139     BaseOp = X86ISD::ADD;
11140     Cond = X86::COND_B;
11141     break;
11142   case ISD::SSUBO:
11143     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11144     // set CF, so we can't do this for USUBO.
11145     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11146       if (C->isOne()) {
11147         BaseOp = X86ISD::DEC;
11148         Cond = X86::COND_O;
11149         break;
11150       }
11151     BaseOp = X86ISD::SUB;
11152     Cond = X86::COND_O;
11153     break;
11154   case ISD::USUBO:
11155     BaseOp = X86ISD::SUB;
11156     Cond = X86::COND_B;
11157     break;
11158   case ISD::SMULO:
11159     BaseOp = X86ISD::SMUL;
11160     Cond = X86::COND_O;
11161     break;
11162   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11163     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11164                                  MVT::i32);
11165     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11166
11167     SDValue SetCC =
11168       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11169                   DAG.getConstant(X86::COND_O, MVT::i32),
11170                   SDValue(Sum.getNode(), 2));
11171
11172     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11173   }
11174   }
11175
11176   // Also sets EFLAGS.
11177   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11178   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11179
11180   SDValue SetCC =
11181     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11182                 DAG.getConstant(Cond, MVT::i32),
11183                 SDValue(Sum.getNode(), 1));
11184
11185   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11186 }
11187
11188 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11189                                                   SelectionDAG &DAG) const {
11190   DebugLoc dl = Op.getDebugLoc();
11191   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11192   EVT VT = Op.getValueType();
11193
11194   if (!Subtarget->hasSSE2() || !VT.isVector())
11195     return SDValue();
11196
11197   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11198                       ExtraVT.getScalarType().getSizeInBits();
11199   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11200
11201   switch (VT.getSimpleVT().SimpleTy) {
11202     default: return SDValue();
11203     case MVT::v8i32:
11204     case MVT::v16i16:
11205       if (!Subtarget->hasAVX())
11206         return SDValue();
11207       if (!Subtarget->hasAVX2()) {
11208         // needs to be split
11209         unsigned NumElems = VT.getVectorNumElements();
11210
11211         // Extract the LHS vectors
11212         SDValue LHS = Op.getOperand(0);
11213         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11214         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11215
11216         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11217         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11218
11219         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11220         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11221         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11222                                    ExtraNumElems/2);
11223         SDValue Extra = DAG.getValueType(ExtraVT);
11224
11225         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11226         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11227
11228         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11229       }
11230       // fall through
11231     case MVT::v4i32:
11232     case MVT::v8i16: {
11233       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11234                                          Op.getOperand(0), ShAmt, DAG);
11235       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11236     }
11237   }
11238 }
11239
11240
11241 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11242                               SelectionDAG &DAG) {
11243   DebugLoc dl = Op.getDebugLoc();
11244
11245   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11246   // There isn't any reason to disable it if the target processor supports it.
11247   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11248     SDValue Chain = Op.getOperand(0);
11249     SDValue Zero = DAG.getConstant(0, MVT::i32);
11250     SDValue Ops[] = {
11251       DAG.getRegister(X86::ESP, MVT::i32), // Base
11252       DAG.getTargetConstant(1, MVT::i8),   // Scale
11253       DAG.getRegister(0, MVT::i32),        // Index
11254       DAG.getTargetConstant(0, MVT::i32),  // Disp
11255       DAG.getRegister(0, MVT::i32),        // Segment.
11256       Zero,
11257       Chain
11258     };
11259     SDNode *Res =
11260       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11261                           array_lengthof(Ops));
11262     return SDValue(Res, 0);
11263   }
11264
11265   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11266   if (!isDev)
11267     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11268
11269   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11270   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11271   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11272   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11273
11274   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11275   if (!Op1 && !Op2 && !Op3 && Op4)
11276     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11277
11278   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11279   if (Op1 && !Op2 && !Op3 && !Op4)
11280     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11281
11282   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11283   //           (MFENCE)>;
11284   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11285 }
11286
11287 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11288                                  SelectionDAG &DAG) {
11289   DebugLoc dl = Op.getDebugLoc();
11290   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11291     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11292   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11293     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11294
11295   // The only fence that needs an instruction is a sequentially-consistent
11296   // cross-thread fence.
11297   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11298     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11299     // no-sse2). There isn't any reason to disable it if the target processor
11300     // supports it.
11301     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11302       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11303
11304     SDValue Chain = Op.getOperand(0);
11305     SDValue Zero = DAG.getConstant(0, MVT::i32);
11306     SDValue Ops[] = {
11307       DAG.getRegister(X86::ESP, MVT::i32), // Base
11308       DAG.getTargetConstant(1, MVT::i8),   // Scale
11309       DAG.getRegister(0, MVT::i32),        // Index
11310       DAG.getTargetConstant(0, MVT::i32),  // Disp
11311       DAG.getRegister(0, MVT::i32),        // Segment.
11312       Zero,
11313       Chain
11314     };
11315     SDNode *Res =
11316       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11317                          array_lengthof(Ops));
11318     return SDValue(Res, 0);
11319   }
11320
11321   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11322   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11323 }
11324
11325
11326 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11327                              SelectionDAG &DAG) {
11328   EVT T = Op.getValueType();
11329   DebugLoc DL = Op.getDebugLoc();
11330   unsigned Reg = 0;
11331   unsigned size = 0;
11332   switch(T.getSimpleVT().SimpleTy) {
11333   default: llvm_unreachable("Invalid value type!");
11334   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11335   case MVT::i16: Reg = X86::AX;  size = 2; break;
11336   case MVT::i32: Reg = X86::EAX; size = 4; break;
11337   case MVT::i64:
11338     assert(Subtarget->is64Bit() && "Node not type legal!");
11339     Reg = X86::RAX; size = 8;
11340     break;
11341   }
11342   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11343                                     Op.getOperand(2), SDValue());
11344   SDValue Ops[] = { cpIn.getValue(0),
11345                     Op.getOperand(1),
11346                     Op.getOperand(3),
11347                     DAG.getTargetConstant(size, MVT::i8),
11348                     cpIn.getValue(1) };
11349   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11350   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11351   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11352                                            Ops, 5, T, MMO);
11353   SDValue cpOut =
11354     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11355   return cpOut;
11356 }
11357
11358 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11359                                      SelectionDAG &DAG) {
11360   assert(Subtarget->is64Bit() && "Result not type legalized?");
11361   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11362   SDValue TheChain = Op.getOperand(0);
11363   DebugLoc dl = Op.getDebugLoc();
11364   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11365   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11366   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11367                                    rax.getValue(2));
11368   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11369                             DAG.getConstant(32, MVT::i8));
11370   SDValue Ops[] = {
11371     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11372     rdx.getValue(1)
11373   };
11374   return DAG.getMergeValues(Ops, 2, dl);
11375 }
11376
11377 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11378   EVT SrcVT = Op.getOperand(0).getValueType();
11379   EVT DstVT = Op.getValueType();
11380   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11381          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11382   assert((DstVT == MVT::i64 ||
11383           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11384          "Unexpected custom BITCAST");
11385   // i64 <=> MMX conversions are Legal.
11386   if (SrcVT==MVT::i64 && DstVT.isVector())
11387     return Op;
11388   if (DstVT==MVT::i64 && SrcVT.isVector())
11389     return Op;
11390   // MMX <=> MMX conversions are Legal.
11391   if (SrcVT.isVector() && DstVT.isVector())
11392     return Op;
11393   // All other conversions need to be expanded.
11394   return SDValue();
11395 }
11396
11397 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11398   SDNode *Node = Op.getNode();
11399   DebugLoc dl = Node->getDebugLoc();
11400   EVT T = Node->getValueType(0);
11401   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11402                               DAG.getConstant(0, T), Node->getOperand(2));
11403   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11404                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11405                        Node->getOperand(0),
11406                        Node->getOperand(1), negOp,
11407                        cast<AtomicSDNode>(Node)->getSrcValue(),
11408                        cast<AtomicSDNode>(Node)->getAlignment(),
11409                        cast<AtomicSDNode>(Node)->getOrdering(),
11410                        cast<AtomicSDNode>(Node)->getSynchScope());
11411 }
11412
11413 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11414   SDNode *Node = Op.getNode();
11415   DebugLoc dl = Node->getDebugLoc();
11416   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11417
11418   // Convert seq_cst store -> xchg
11419   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11420   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11421   //        (The only way to get a 16-byte store is cmpxchg16b)
11422   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11423   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11424       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11425     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11426                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11427                                  Node->getOperand(0),
11428                                  Node->getOperand(1), Node->getOperand(2),
11429                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11430                                  cast<AtomicSDNode>(Node)->getOrdering(),
11431                                  cast<AtomicSDNode>(Node)->getSynchScope());
11432     return Swap.getValue(1);
11433   }
11434   // Other atomic stores have a simple pattern.
11435   return Op;
11436 }
11437
11438 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11439   EVT VT = Op.getNode()->getValueType(0);
11440
11441   // Let legalize expand this if it isn't a legal type yet.
11442   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11443     return SDValue();
11444
11445   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11446
11447   unsigned Opc;
11448   bool ExtraOp = false;
11449   switch (Op.getOpcode()) {
11450   default: llvm_unreachable("Invalid code");
11451   case ISD::ADDC: Opc = X86ISD::ADD; break;
11452   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11453   case ISD::SUBC: Opc = X86ISD::SUB; break;
11454   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11455   }
11456
11457   if (!ExtraOp)
11458     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11459                        Op.getOperand(1));
11460   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11461                      Op.getOperand(1), Op.getOperand(2));
11462 }
11463
11464 /// LowerOperation - Provide custom lowering hooks for some operations.
11465 ///
11466 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11467   switch (Op.getOpcode()) {
11468   default: llvm_unreachable("Should not custom lower this!");
11469   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11470   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11471   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11472   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11473   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11474   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11475   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11476   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11477   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11478   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11479   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11480   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11481   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11482   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11483   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11484   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11485   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11486   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11487   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11488   case ISD::SHL_PARTS:
11489   case ISD::SRA_PARTS:
11490   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11491   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11492   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11493   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11494   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11495   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11496   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11497   case ISD::FABS:               return LowerFABS(Op, DAG);
11498   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11499   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11500   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11501   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11502   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11503   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11504   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11505   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11506   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11507   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11508   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11509   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11510   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11511   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11512   case ISD::FRAME_TO_ARGS_OFFSET:
11513                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11514   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11515   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11516   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11517   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11518   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11519   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11520   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11521   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11522   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11523   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11524   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11525   case ISD::SRA:
11526   case ISD::SRL:
11527   case ISD::SHL:                return LowerShift(Op, DAG);
11528   case ISD::SADDO:
11529   case ISD::UADDO:
11530   case ISD::SSUBO:
11531   case ISD::USUBO:
11532   case ISD::SMULO:
11533   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11534   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11535   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11536   case ISD::ADDC:
11537   case ISD::ADDE:
11538   case ISD::SUBC:
11539   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11540   case ISD::ADD:                return LowerADD(Op, DAG);
11541   case ISD::SUB:                return LowerSUB(Op, DAG);
11542   }
11543 }
11544
11545 static void ReplaceATOMIC_LOAD(SDNode *Node,
11546                                   SmallVectorImpl<SDValue> &Results,
11547                                   SelectionDAG &DAG) {
11548   DebugLoc dl = Node->getDebugLoc();
11549   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11550
11551   // Convert wide load -> cmpxchg8b/cmpxchg16b
11552   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11553   //        (The only way to get a 16-byte load is cmpxchg16b)
11554   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11555   SDValue Zero = DAG.getConstant(0, VT);
11556   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11557                                Node->getOperand(0),
11558                                Node->getOperand(1), Zero, Zero,
11559                                cast<AtomicSDNode>(Node)->getMemOperand(),
11560                                cast<AtomicSDNode>(Node)->getOrdering(),
11561                                cast<AtomicSDNode>(Node)->getSynchScope());
11562   Results.push_back(Swap.getValue(0));
11563   Results.push_back(Swap.getValue(1));
11564 }
11565
11566 static void
11567 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11568                         SelectionDAG &DAG, unsigned NewOp) {
11569   DebugLoc dl = Node->getDebugLoc();
11570   assert (Node->getValueType(0) == MVT::i64 &&
11571           "Only know how to expand i64 atomics");
11572
11573   SDValue Chain = Node->getOperand(0);
11574   SDValue In1 = Node->getOperand(1);
11575   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11576                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11577   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11578                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11579   SDValue Ops[] = { Chain, In1, In2L, In2H };
11580   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11581   SDValue Result =
11582     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11583                             cast<MemSDNode>(Node)->getMemOperand());
11584   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11585   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11586   Results.push_back(Result.getValue(2));
11587 }
11588
11589 /// ReplaceNodeResults - Replace a node with an illegal result type
11590 /// with a new node built out of custom code.
11591 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11592                                            SmallVectorImpl<SDValue>&Results,
11593                                            SelectionDAG &DAG) const {
11594   DebugLoc dl = N->getDebugLoc();
11595   switch (N->getOpcode()) {
11596   default:
11597     llvm_unreachable("Do not know how to custom type legalize this operation!");
11598   case ISD::SIGN_EXTEND_INREG:
11599   case ISD::ADDC:
11600   case ISD::ADDE:
11601   case ISD::SUBC:
11602   case ISD::SUBE:
11603     // We don't want to expand or promote these.
11604     return;
11605   case ISD::FP_TO_SINT:
11606   case ISD::FP_TO_UINT: {
11607     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11608
11609     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11610       return;
11611
11612     std::pair<SDValue,SDValue> Vals =
11613         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11614     SDValue FIST = Vals.first, StackSlot = Vals.second;
11615     if (FIST.getNode() != 0) {
11616       EVT VT = N->getValueType(0);
11617       // Return a load from the stack slot.
11618       if (StackSlot.getNode() != 0)
11619         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11620                                       MachinePointerInfo(),
11621                                       false, false, false, 0));
11622       else
11623         Results.push_back(FIST);
11624     }
11625     return;
11626   }
11627   case ISD::FP_ROUND: {
11628     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11629     Results.push_back(V);
11630     return;
11631   }
11632   case ISD::READCYCLECOUNTER: {
11633     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11634     SDValue TheChain = N->getOperand(0);
11635     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11636     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11637                                      rd.getValue(1));
11638     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11639                                      eax.getValue(2));
11640     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11641     SDValue Ops[] = { eax, edx };
11642     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11643     Results.push_back(edx.getValue(1));
11644     return;
11645   }
11646   case ISD::ATOMIC_CMP_SWAP: {
11647     EVT T = N->getValueType(0);
11648     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11649     bool Regs64bit = T == MVT::i128;
11650     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11651     SDValue cpInL, cpInH;
11652     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11653                         DAG.getConstant(0, HalfT));
11654     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11655                         DAG.getConstant(1, HalfT));
11656     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11657                              Regs64bit ? X86::RAX : X86::EAX,
11658                              cpInL, SDValue());
11659     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11660                              Regs64bit ? X86::RDX : X86::EDX,
11661                              cpInH, cpInL.getValue(1));
11662     SDValue swapInL, swapInH;
11663     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11664                           DAG.getConstant(0, HalfT));
11665     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11666                           DAG.getConstant(1, HalfT));
11667     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11668                                Regs64bit ? X86::RBX : X86::EBX,
11669                                swapInL, cpInH.getValue(1));
11670     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11671                                Regs64bit ? X86::RCX : X86::ECX,
11672                                swapInH, swapInL.getValue(1));
11673     SDValue Ops[] = { swapInH.getValue(0),
11674                       N->getOperand(1),
11675                       swapInH.getValue(1) };
11676     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11677     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11678     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11679                                   X86ISD::LCMPXCHG8_DAG;
11680     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11681                                              Ops, 3, T, MMO);
11682     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11683                                         Regs64bit ? X86::RAX : X86::EAX,
11684                                         HalfT, Result.getValue(1));
11685     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11686                                         Regs64bit ? X86::RDX : X86::EDX,
11687                                         HalfT, cpOutL.getValue(2));
11688     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11689     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11690     Results.push_back(cpOutH.getValue(1));
11691     return;
11692   }
11693   case ISD::ATOMIC_LOAD_ADD:
11694   case ISD::ATOMIC_LOAD_AND:
11695   case ISD::ATOMIC_LOAD_NAND:
11696   case ISD::ATOMIC_LOAD_OR:
11697   case ISD::ATOMIC_LOAD_SUB:
11698   case ISD::ATOMIC_LOAD_XOR:
11699   case ISD::ATOMIC_LOAD_MAX:
11700   case ISD::ATOMIC_LOAD_MIN:
11701   case ISD::ATOMIC_LOAD_UMAX:
11702   case ISD::ATOMIC_LOAD_UMIN:
11703   case ISD::ATOMIC_SWAP: {
11704     unsigned Opc;
11705     switch (N->getOpcode()) {
11706     default: llvm_unreachable("Unexpected opcode");
11707     case ISD::ATOMIC_LOAD_ADD:
11708       Opc = X86ISD::ATOMADD64_DAG;
11709       break;
11710     case ISD::ATOMIC_LOAD_AND:
11711       Opc = X86ISD::ATOMAND64_DAG;
11712       break;
11713     case ISD::ATOMIC_LOAD_NAND:
11714       Opc = X86ISD::ATOMNAND64_DAG;
11715       break;
11716     case ISD::ATOMIC_LOAD_OR:
11717       Opc = X86ISD::ATOMOR64_DAG;
11718       break;
11719     case ISD::ATOMIC_LOAD_SUB:
11720       Opc = X86ISD::ATOMSUB64_DAG;
11721       break;
11722     case ISD::ATOMIC_LOAD_XOR:
11723       Opc = X86ISD::ATOMXOR64_DAG;
11724       break;
11725     case ISD::ATOMIC_LOAD_MAX:
11726       Opc = X86ISD::ATOMMAX64_DAG;
11727       break;
11728     case ISD::ATOMIC_LOAD_MIN:
11729       Opc = X86ISD::ATOMMIN64_DAG;
11730       break;
11731     case ISD::ATOMIC_LOAD_UMAX:
11732       Opc = X86ISD::ATOMUMAX64_DAG;
11733       break;
11734     case ISD::ATOMIC_LOAD_UMIN:
11735       Opc = X86ISD::ATOMUMIN64_DAG;
11736       break;
11737     case ISD::ATOMIC_SWAP:
11738       Opc = X86ISD::ATOMSWAP64_DAG;
11739       break;
11740     }
11741     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11742     return;
11743   }
11744   case ISD::ATOMIC_LOAD:
11745     ReplaceATOMIC_LOAD(N, Results, DAG);
11746   }
11747 }
11748
11749 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11750   switch (Opcode) {
11751   default: return NULL;
11752   case X86ISD::BSF:                return "X86ISD::BSF";
11753   case X86ISD::BSR:                return "X86ISD::BSR";
11754   case X86ISD::SHLD:               return "X86ISD::SHLD";
11755   case X86ISD::SHRD:               return "X86ISD::SHRD";
11756   case X86ISD::FAND:               return "X86ISD::FAND";
11757   case X86ISD::FOR:                return "X86ISD::FOR";
11758   case X86ISD::FXOR:               return "X86ISD::FXOR";
11759   case X86ISD::FSRL:               return "X86ISD::FSRL";
11760   case X86ISD::FILD:               return "X86ISD::FILD";
11761   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11762   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11763   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11764   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11765   case X86ISD::FLD:                return "X86ISD::FLD";
11766   case X86ISD::FST:                return "X86ISD::FST";
11767   case X86ISD::CALL:               return "X86ISD::CALL";
11768   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11769   case X86ISD::BT:                 return "X86ISD::BT";
11770   case X86ISD::CMP:                return "X86ISD::CMP";
11771   case X86ISD::COMI:               return "X86ISD::COMI";
11772   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11773   case X86ISD::SETCC:              return "X86ISD::SETCC";
11774   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11775   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11776   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11777   case X86ISD::CMOV:               return "X86ISD::CMOV";
11778   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11779   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11780   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11781   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11782   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11783   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11784   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11785   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11786   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11787   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11788   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11789   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11790   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11791   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11792   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11793   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11794   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11795   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11796   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11797   case X86ISD::HADD:               return "X86ISD::HADD";
11798   case X86ISD::HSUB:               return "X86ISD::HSUB";
11799   case X86ISD::FHADD:              return "X86ISD::FHADD";
11800   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11801   case X86ISD::FMAX:               return "X86ISD::FMAX";
11802   case X86ISD::FMIN:               return "X86ISD::FMIN";
11803   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11804   case X86ISD::FMINC:              return "X86ISD::FMINC";
11805   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11806   case X86ISD::FRCP:               return "X86ISD::FRCP";
11807   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11808   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11809   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11810   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11811   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11812   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11813   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11814   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11815   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11816   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11817   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11818   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11819   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11820   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11821   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11822   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11823   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11824   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11825   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11826   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11827   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11828   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11829   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11830   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11831   case X86ISD::VSHL:               return "X86ISD::VSHL";
11832   case X86ISD::VSRL:               return "X86ISD::VSRL";
11833   case X86ISD::VSRA:               return "X86ISD::VSRA";
11834   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11835   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11836   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11837   case X86ISD::CMPP:               return "X86ISD::CMPP";
11838   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11839   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11840   case X86ISD::ADD:                return "X86ISD::ADD";
11841   case X86ISD::SUB:                return "X86ISD::SUB";
11842   case X86ISD::ADC:                return "X86ISD::ADC";
11843   case X86ISD::SBB:                return "X86ISD::SBB";
11844   case X86ISD::SMUL:               return "X86ISD::SMUL";
11845   case X86ISD::UMUL:               return "X86ISD::UMUL";
11846   case X86ISD::INC:                return "X86ISD::INC";
11847   case X86ISD::DEC:                return "X86ISD::DEC";
11848   case X86ISD::OR:                 return "X86ISD::OR";
11849   case X86ISD::XOR:                return "X86ISD::XOR";
11850   case X86ISD::AND:                return "X86ISD::AND";
11851   case X86ISD::ANDN:               return "X86ISD::ANDN";
11852   case X86ISD::BLSI:               return "X86ISD::BLSI";
11853   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11854   case X86ISD::BLSR:               return "X86ISD::BLSR";
11855   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11856   case X86ISD::PTEST:              return "X86ISD::PTEST";
11857   case X86ISD::TESTP:              return "X86ISD::TESTP";
11858   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11859   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11860   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11861   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11862   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11863   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11864   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11865   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11866   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11867   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11868   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11869   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11870   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11871   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11872   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11873   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11874   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11875   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11876   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11877   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11878   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11879   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11880   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11881   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11882   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11883   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11884   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11885   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11886   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11887   case X86ISD::SAHF:               return "X86ISD::SAHF";
11888   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11889   case X86ISD::FMADD:              return "X86ISD::FMADD";
11890   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11891   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11892   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11893   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11894   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11895   }
11896 }
11897
11898 // isLegalAddressingMode - Return true if the addressing mode represented
11899 // by AM is legal for this target, for a load/store of the specified type.
11900 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11901                                               Type *Ty) const {
11902   // X86 supports extremely general addressing modes.
11903   CodeModel::Model M = getTargetMachine().getCodeModel();
11904   Reloc::Model R = getTargetMachine().getRelocationModel();
11905
11906   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11907   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11908     return false;
11909
11910   if (AM.BaseGV) {
11911     unsigned GVFlags =
11912       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11913
11914     // If a reference to this global requires an extra load, we can't fold it.
11915     if (isGlobalStubReference(GVFlags))
11916       return false;
11917
11918     // If BaseGV requires a register for the PIC base, we cannot also have a
11919     // BaseReg specified.
11920     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11921       return false;
11922
11923     // If lower 4G is not available, then we must use rip-relative addressing.
11924     if ((M != CodeModel::Small || R != Reloc::Static) &&
11925         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11926       return false;
11927   }
11928
11929   switch (AM.Scale) {
11930   case 0:
11931   case 1:
11932   case 2:
11933   case 4:
11934   case 8:
11935     // These scales always work.
11936     break;
11937   case 3:
11938   case 5:
11939   case 9:
11940     // These scales are formed with basereg+scalereg.  Only accept if there is
11941     // no basereg yet.
11942     if (AM.HasBaseReg)
11943       return false;
11944     break;
11945   default:  // Other stuff never works.
11946     return false;
11947   }
11948
11949   return true;
11950 }
11951
11952
11953 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11954   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11955     return false;
11956   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11957   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11958   if (NumBits1 <= NumBits2)
11959     return false;
11960   return true;
11961 }
11962
11963 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11964   return Imm == (int32_t)Imm;
11965 }
11966
11967 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11968   // Can also use sub to handle negated immediates.
11969   return Imm == (int32_t)Imm;
11970 }
11971
11972 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11973   if (!VT1.isInteger() || !VT2.isInteger())
11974     return false;
11975   unsigned NumBits1 = VT1.getSizeInBits();
11976   unsigned NumBits2 = VT2.getSizeInBits();
11977   if (NumBits1 <= NumBits2)
11978     return false;
11979   return true;
11980 }
11981
11982 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11983   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11984   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11985 }
11986
11987 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11988   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11989   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11990 }
11991
11992 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11993   // i16 instructions are longer (0x66 prefix) and potentially slower.
11994   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11995 }
11996
11997 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11998 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11999 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12000 /// are assumed to be legal.
12001 bool
12002 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12003                                       EVT VT) const {
12004   // Very little shuffling can be done for 64-bit vectors right now.
12005   if (VT.getSizeInBits() == 64)
12006     return false;
12007
12008   // FIXME: pshufb, blends, shifts.
12009   return (VT.getVectorNumElements() == 2 ||
12010           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12011           isMOVLMask(M, VT) ||
12012           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12013           isPSHUFDMask(M, VT) ||
12014           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12015           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12016           isPALIGNRMask(M, VT, Subtarget) ||
12017           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12018           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12019           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12020           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12021 }
12022
12023 bool
12024 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12025                                           EVT VT) const {
12026   unsigned NumElts = VT.getVectorNumElements();
12027   // FIXME: This collection of masks seems suspect.
12028   if (NumElts == 2)
12029     return true;
12030   if (NumElts == 4 && VT.is128BitVector()) {
12031     return (isMOVLMask(Mask, VT)  ||
12032             isCommutedMOVLMask(Mask, VT, true) ||
12033             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12034             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12035   }
12036   return false;
12037 }
12038
12039 //===----------------------------------------------------------------------===//
12040 //                           X86 Scheduler Hooks
12041 //===----------------------------------------------------------------------===//
12042
12043 // private utility function
12044
12045 // Get CMPXCHG opcode for the specified data type.
12046 static unsigned getCmpXChgOpcode(EVT VT) {
12047   switch (VT.getSimpleVT().SimpleTy) {
12048   case MVT::i8:  return X86::LCMPXCHG8;
12049   case MVT::i16: return X86::LCMPXCHG16;
12050   case MVT::i32: return X86::LCMPXCHG32;
12051   case MVT::i64: return X86::LCMPXCHG64;
12052   default:
12053     break;
12054   }
12055   llvm_unreachable("Invalid operand size!");
12056 }
12057
12058 // Get LOAD opcode for the specified data type.
12059 static unsigned getLoadOpcode(EVT VT) {
12060   switch (VT.getSimpleVT().SimpleTy) {
12061   case MVT::i8:  return X86::MOV8rm;
12062   case MVT::i16: return X86::MOV16rm;
12063   case MVT::i32: return X86::MOV32rm;
12064   case MVT::i64: return X86::MOV64rm;
12065   default:
12066     break;
12067   }
12068   llvm_unreachable("Invalid operand size!");
12069 }
12070
12071 // Get opcode of the non-atomic one from the specified atomic instruction.
12072 static unsigned getNonAtomicOpcode(unsigned Opc) {
12073   switch (Opc) {
12074   case X86::ATOMAND8:  return X86::AND8rr;
12075   case X86::ATOMAND16: return X86::AND16rr;
12076   case X86::ATOMAND32: return X86::AND32rr;
12077   case X86::ATOMAND64: return X86::AND64rr;
12078   case X86::ATOMOR8:   return X86::OR8rr;
12079   case X86::ATOMOR16:  return X86::OR16rr;
12080   case X86::ATOMOR32:  return X86::OR32rr;
12081   case X86::ATOMOR64:  return X86::OR64rr;
12082   case X86::ATOMXOR8:  return X86::XOR8rr;
12083   case X86::ATOMXOR16: return X86::XOR16rr;
12084   case X86::ATOMXOR32: return X86::XOR32rr;
12085   case X86::ATOMXOR64: return X86::XOR64rr;
12086   }
12087   llvm_unreachable("Unhandled atomic-load-op opcode!");
12088 }
12089
12090 // Get opcode of the non-atomic one from the specified atomic instruction with
12091 // extra opcode.
12092 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12093                                                unsigned &ExtraOpc) {
12094   switch (Opc) {
12095   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12096   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12097   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12098   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12099   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12100   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12101   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12102   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12103   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12104   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12105   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12106   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12107   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12108   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12109   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12110   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12111   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12112   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12113   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12114   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12115   }
12116   llvm_unreachable("Unhandled atomic-load-op opcode!");
12117 }
12118
12119 // Get opcode of the non-atomic one from the specified atomic instruction for
12120 // 64-bit data type on 32-bit target.
12121 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12122   switch (Opc) {
12123   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12124   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12125   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12126   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12127   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12128   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12129   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12130   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12131   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12132   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12133   }
12134   llvm_unreachable("Unhandled atomic-load-op opcode!");
12135 }
12136
12137 // Get opcode of the non-atomic one from the specified atomic instruction for
12138 // 64-bit data type on 32-bit target with extra opcode.
12139 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12140                                                    unsigned &HiOpc,
12141                                                    unsigned &ExtraOpc) {
12142   switch (Opc) {
12143   case X86::ATOMNAND6432:
12144     ExtraOpc = X86::NOT32r;
12145     HiOpc = X86::AND32rr;
12146     return X86::AND32rr;
12147   }
12148   llvm_unreachable("Unhandled atomic-load-op opcode!");
12149 }
12150
12151 // Get pseudo CMOV opcode from the specified data type.
12152 static unsigned getPseudoCMOVOpc(EVT VT) {
12153   switch (VT.getSimpleVT().SimpleTy) {
12154   case MVT::i8:  return X86::CMOV_GR8;
12155   case MVT::i16: return X86::CMOV_GR16;
12156   case MVT::i32: return X86::CMOV_GR32;
12157   default:
12158     break;
12159   }
12160   llvm_unreachable("Unknown CMOV opcode!");
12161 }
12162
12163 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12164 // They will be translated into a spin-loop or compare-exchange loop from
12165 //
12166 //    ...
12167 //    dst = atomic-fetch-op MI.addr, MI.val
12168 //    ...
12169 //
12170 // to
12171 //
12172 //    ...
12173 //    EAX = LOAD MI.addr
12174 // loop:
12175 //    t1 = OP MI.val, EAX
12176 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12177 //    JNE loop
12178 // sink:
12179 //    dst = EAX
12180 //    ...
12181 MachineBasicBlock *
12182 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12183                                        MachineBasicBlock *MBB) const {
12184   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12185   DebugLoc DL = MI->getDebugLoc();
12186
12187   MachineFunction *MF = MBB->getParent();
12188   MachineRegisterInfo &MRI = MF->getRegInfo();
12189
12190   const BasicBlock *BB = MBB->getBasicBlock();
12191   MachineFunction::iterator I = MBB;
12192   ++I;
12193
12194   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12195          "Unexpected number of operands");
12196
12197   assert(MI->hasOneMemOperand() &&
12198          "Expected atomic-load-op to have one memoperand");
12199
12200   // Memory Reference
12201   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12202   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12203
12204   unsigned DstReg, SrcReg;
12205   unsigned MemOpndSlot;
12206
12207   unsigned CurOp = 0;
12208
12209   DstReg = MI->getOperand(CurOp++).getReg();
12210   MemOpndSlot = CurOp;
12211   CurOp += X86::AddrNumOperands;
12212   SrcReg = MI->getOperand(CurOp++).getReg();
12213
12214   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12215   MVT::SimpleValueType VT = *RC->vt_begin();
12216   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12217
12218   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12219   unsigned LOADOpc = getLoadOpcode(VT);
12220
12221   // For the atomic load-arith operator, we generate
12222   //
12223   //  thisMBB:
12224   //    EAX = LOAD [MI.addr]
12225   //  mainMBB:
12226   //    t1 = OP MI.val, EAX
12227   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12228   //    JNE mainMBB
12229   //  sinkMBB:
12230
12231   MachineBasicBlock *thisMBB = MBB;
12232   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12233   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12234   MF->insert(I, mainMBB);
12235   MF->insert(I, sinkMBB);
12236
12237   MachineInstrBuilder MIB;
12238
12239   // Transfer the remainder of BB and its successor edges to sinkMBB.
12240   sinkMBB->splice(sinkMBB->begin(), MBB,
12241                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12242   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12243
12244   // thisMBB:
12245   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12246   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12247     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12248   MIB.setMemRefs(MMOBegin, MMOEnd);
12249
12250   thisMBB->addSuccessor(mainMBB);
12251
12252   // mainMBB:
12253   MachineBasicBlock *origMainMBB = mainMBB;
12254   mainMBB->addLiveIn(AccPhyReg);
12255
12256   // Copy AccPhyReg as it is used more than once.
12257   unsigned AccReg = MRI.createVirtualRegister(RC);
12258   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12259     .addReg(AccPhyReg);
12260
12261   unsigned t1 = MRI.createVirtualRegister(RC);
12262   unsigned Opc = MI->getOpcode();
12263   switch (Opc) {
12264   default:
12265     llvm_unreachable("Unhandled atomic-load-op opcode!");
12266   case X86::ATOMAND8:
12267   case X86::ATOMAND16:
12268   case X86::ATOMAND32:
12269   case X86::ATOMAND64:
12270   case X86::ATOMOR8:
12271   case X86::ATOMOR16:
12272   case X86::ATOMOR32:
12273   case X86::ATOMOR64:
12274   case X86::ATOMXOR8:
12275   case X86::ATOMXOR16:
12276   case X86::ATOMXOR32:
12277   case X86::ATOMXOR64: {
12278     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12279     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12280       .addReg(AccReg);
12281     break;
12282   }
12283   case X86::ATOMNAND8:
12284   case X86::ATOMNAND16:
12285   case X86::ATOMNAND32:
12286   case X86::ATOMNAND64: {
12287     unsigned t2 = MRI.createVirtualRegister(RC);
12288     unsigned NOTOpc;
12289     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12290     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12291       .addReg(AccReg);
12292     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12293     break;
12294   }
12295   case X86::ATOMMAX8:
12296   case X86::ATOMMAX16:
12297   case X86::ATOMMAX32:
12298   case X86::ATOMMAX64:
12299   case X86::ATOMMIN8:
12300   case X86::ATOMMIN16:
12301   case X86::ATOMMIN32:
12302   case X86::ATOMMIN64:
12303   case X86::ATOMUMAX8:
12304   case X86::ATOMUMAX16:
12305   case X86::ATOMUMAX32:
12306   case X86::ATOMUMAX64:
12307   case X86::ATOMUMIN8:
12308   case X86::ATOMUMIN16:
12309   case X86::ATOMUMIN32:
12310   case X86::ATOMUMIN64: {
12311     unsigned CMPOpc;
12312     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12313
12314     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12315       .addReg(SrcReg)
12316       .addReg(AccReg);
12317
12318     if (Subtarget->hasCMov()) {
12319       if (VT != MVT::i8) {
12320         // Native support
12321         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12322           .addReg(SrcReg)
12323           .addReg(AccReg);
12324       } else {
12325         // Promote i8 to i32 to use CMOV32
12326         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12327         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12328         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12329         unsigned t2 = MRI.createVirtualRegister(RC32);
12330
12331         unsigned Undef = MRI.createVirtualRegister(RC32);
12332         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12333
12334         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12335           .addReg(Undef)
12336           .addReg(SrcReg)
12337           .addImm(X86::sub_8bit);
12338         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12339           .addReg(Undef)
12340           .addReg(AccReg)
12341           .addImm(X86::sub_8bit);
12342
12343         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12344           .addReg(SrcReg32)
12345           .addReg(AccReg32);
12346
12347         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12348           .addReg(t2, 0, X86::sub_8bit);
12349       }
12350     } else {
12351       // Use pseudo select and lower them.
12352       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12353              "Invalid atomic-load-op transformation!");
12354       unsigned SelOpc = getPseudoCMOVOpc(VT);
12355       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12356       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12357       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12358               .addReg(SrcReg).addReg(AccReg)
12359               .addImm(CC);
12360       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12361     }
12362     break;
12363   }
12364   }
12365
12366   // Copy AccPhyReg back from virtual register.
12367   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12368     .addReg(AccReg);
12369
12370   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12371   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12372     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12373   MIB.addReg(t1);
12374   MIB.setMemRefs(MMOBegin, MMOEnd);
12375
12376   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12377
12378   mainMBB->addSuccessor(origMainMBB);
12379   mainMBB->addSuccessor(sinkMBB);
12380
12381   // sinkMBB:
12382   sinkMBB->addLiveIn(AccPhyReg);
12383
12384   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12385           TII->get(TargetOpcode::COPY), DstReg)
12386     .addReg(AccPhyReg);
12387
12388   MI->eraseFromParent();
12389   return sinkMBB;
12390 }
12391
12392 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12393 // instructions. They will be translated into a spin-loop or compare-exchange
12394 // loop from
12395 //
12396 //    ...
12397 //    dst = atomic-fetch-op MI.addr, MI.val
12398 //    ...
12399 //
12400 // to
12401 //
12402 //    ...
12403 //    EAX = LOAD [MI.addr + 0]
12404 //    EDX = LOAD [MI.addr + 4]
12405 // loop:
12406 //    EBX = OP MI.val.lo, EAX
12407 //    ECX = OP MI.val.hi, EDX
12408 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12409 //    JNE loop
12410 // sink:
12411 //    dst = EDX:EAX
12412 //    ...
12413 MachineBasicBlock *
12414 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12415                                            MachineBasicBlock *MBB) const {
12416   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12417   DebugLoc DL = MI->getDebugLoc();
12418
12419   MachineFunction *MF = MBB->getParent();
12420   MachineRegisterInfo &MRI = MF->getRegInfo();
12421
12422   const BasicBlock *BB = MBB->getBasicBlock();
12423   MachineFunction::iterator I = MBB;
12424   ++I;
12425
12426   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12427          "Unexpected number of operands");
12428
12429   assert(MI->hasOneMemOperand() &&
12430          "Expected atomic-load-op32 to have one memoperand");
12431
12432   // Memory Reference
12433   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12434   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12435
12436   unsigned DstLoReg, DstHiReg;
12437   unsigned SrcLoReg, SrcHiReg;
12438   unsigned MemOpndSlot;
12439
12440   unsigned CurOp = 0;
12441
12442   DstLoReg = MI->getOperand(CurOp++).getReg();
12443   DstHiReg = MI->getOperand(CurOp++).getReg();
12444   MemOpndSlot = CurOp;
12445   CurOp += X86::AddrNumOperands;
12446   SrcLoReg = MI->getOperand(CurOp++).getReg();
12447   SrcHiReg = MI->getOperand(CurOp++).getReg();
12448
12449   const TargetRegisterClass *RC = &X86::GR32RegClass;
12450   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12451
12452   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12453   unsigned LOADOpc = X86::MOV32rm;
12454
12455   // For the atomic load-arith operator, we generate
12456   //
12457   //  thisMBB:
12458   //    EAX = LOAD [MI.addr + 0]
12459   //    EDX = LOAD [MI.addr + 4]
12460   //  mainMBB:
12461   //    EBX = OP MI.vallo, EAX
12462   //    ECX = OP MI.valhi, EDX
12463   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12464   //    JNE mainMBB
12465   //  sinkMBB:
12466
12467   MachineBasicBlock *thisMBB = MBB;
12468   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12469   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12470   MF->insert(I, mainMBB);
12471   MF->insert(I, sinkMBB);
12472
12473   MachineInstrBuilder MIB;
12474
12475   // Transfer the remainder of BB and its successor edges to sinkMBB.
12476   sinkMBB->splice(sinkMBB->begin(), MBB,
12477                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12478   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12479
12480   // thisMBB:
12481   // Lo
12482   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12483   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12484     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12485   MIB.setMemRefs(MMOBegin, MMOEnd);
12486   // Hi
12487   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12488   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12489     if (i == X86::AddrDisp)
12490       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12491     else
12492       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12493   }
12494   MIB.setMemRefs(MMOBegin, MMOEnd);
12495
12496   thisMBB->addSuccessor(mainMBB);
12497
12498   // mainMBB:
12499   MachineBasicBlock *origMainMBB = mainMBB;
12500   mainMBB->addLiveIn(X86::EAX);
12501   mainMBB->addLiveIn(X86::EDX);
12502
12503   // Copy EDX:EAX as they are used more than once.
12504   unsigned LoReg = MRI.createVirtualRegister(RC);
12505   unsigned HiReg = MRI.createVirtualRegister(RC);
12506   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12507   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12508
12509   unsigned t1L = MRI.createVirtualRegister(RC);
12510   unsigned t1H = MRI.createVirtualRegister(RC);
12511
12512   unsigned Opc = MI->getOpcode();
12513   switch (Opc) {
12514   default:
12515     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12516   case X86::ATOMAND6432:
12517   case X86::ATOMOR6432:
12518   case X86::ATOMXOR6432:
12519   case X86::ATOMADD6432:
12520   case X86::ATOMSUB6432: {
12521     unsigned HiOpc;
12522     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12523     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12524     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12525     break;
12526   }
12527   case X86::ATOMNAND6432: {
12528     unsigned HiOpc, NOTOpc;
12529     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12530     unsigned t2L = MRI.createVirtualRegister(RC);
12531     unsigned t2H = MRI.createVirtualRegister(RC);
12532     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12533     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12534     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12535     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12536     break;
12537   }
12538   case X86::ATOMMAX6432:
12539   case X86::ATOMMIN6432:
12540   case X86::ATOMUMAX6432:
12541   case X86::ATOMUMIN6432: {
12542     unsigned HiOpc;
12543     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12544     unsigned cL = MRI.createVirtualRegister(RC8);
12545     unsigned cH = MRI.createVirtualRegister(RC8);
12546     unsigned cL32 = MRI.createVirtualRegister(RC);
12547     unsigned cH32 = MRI.createVirtualRegister(RC);
12548     unsigned cc = MRI.createVirtualRegister(RC);
12549     // cl := cmp src_lo, lo
12550     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12551       .addReg(SrcLoReg).addReg(LoReg);
12552     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12553     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12554     // ch := cmp src_hi, hi
12555     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12556       .addReg(SrcHiReg).addReg(HiReg);
12557     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12558     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12559     // cc := if (src_hi == hi) ? cl : ch;
12560     if (Subtarget->hasCMov()) {
12561       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12562         .addReg(cH32).addReg(cL32);
12563     } else {
12564       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12565               .addReg(cH32).addReg(cL32)
12566               .addImm(X86::COND_E);
12567       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12568     }
12569     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12570     if (Subtarget->hasCMov()) {
12571       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12572         .addReg(SrcLoReg).addReg(LoReg);
12573       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12574         .addReg(SrcHiReg).addReg(HiReg);
12575     } else {
12576       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12577               .addReg(SrcLoReg).addReg(LoReg)
12578               .addImm(X86::COND_NE);
12579       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12580       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12581               .addReg(SrcHiReg).addReg(HiReg)
12582               .addImm(X86::COND_NE);
12583       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12584     }
12585     break;
12586   }
12587   case X86::ATOMSWAP6432: {
12588     unsigned HiOpc;
12589     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12590     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12591     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12592     break;
12593   }
12594   }
12595
12596   // Copy EDX:EAX back from HiReg:LoReg
12597   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12598   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12599   // Copy ECX:EBX from t1H:t1L
12600   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12601   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12602
12603   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12604   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12605     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12606   MIB.setMemRefs(MMOBegin, MMOEnd);
12607
12608   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12609
12610   mainMBB->addSuccessor(origMainMBB);
12611   mainMBB->addSuccessor(sinkMBB);
12612
12613   // sinkMBB:
12614   sinkMBB->addLiveIn(X86::EAX);
12615   sinkMBB->addLiveIn(X86::EDX);
12616
12617   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12618           TII->get(TargetOpcode::COPY), DstLoReg)
12619     .addReg(X86::EAX);
12620   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12621           TII->get(TargetOpcode::COPY), DstHiReg)
12622     .addReg(X86::EDX);
12623
12624   MI->eraseFromParent();
12625   return sinkMBB;
12626 }
12627
12628 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12629 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12630 // in the .td file.
12631 MachineBasicBlock *
12632 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12633                             unsigned numArgs, bool memArg) const {
12634   assert(Subtarget->hasSSE42() &&
12635          "Target must have SSE4.2 or AVX features enabled");
12636
12637   DebugLoc dl = MI->getDebugLoc();
12638   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12639   unsigned Opc;
12640   if (!Subtarget->hasAVX()) {
12641     if (memArg)
12642       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12643     else
12644       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12645   } else {
12646     if (memArg)
12647       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12648     else
12649       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12650   }
12651
12652   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12653   for (unsigned i = 0; i < numArgs; ++i) {
12654     MachineOperand &Op = MI->getOperand(i+1);
12655     if (!(Op.isReg() && Op.isImplicit()))
12656       MIB.addOperand(Op);
12657   }
12658   BuildMI(*BB, MI, dl,
12659     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12660     .addReg(X86::XMM0);
12661
12662   MI->eraseFromParent();
12663   return BB;
12664 }
12665
12666 MachineBasicBlock *
12667 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12668   DebugLoc dl = MI->getDebugLoc();
12669   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12670
12671   // Address into RAX/EAX, other two args into ECX, EDX.
12672   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12673   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12674   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12675   for (int i = 0; i < X86::AddrNumOperands; ++i)
12676     MIB.addOperand(MI->getOperand(i));
12677
12678   unsigned ValOps = X86::AddrNumOperands;
12679   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12680     .addReg(MI->getOperand(ValOps).getReg());
12681   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12682     .addReg(MI->getOperand(ValOps+1).getReg());
12683
12684   // The instruction doesn't actually take any operands though.
12685   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12686
12687   MI->eraseFromParent(); // The pseudo is gone now.
12688   return BB;
12689 }
12690
12691 MachineBasicBlock *
12692 X86TargetLowering::EmitVAARG64WithCustomInserter(
12693                    MachineInstr *MI,
12694                    MachineBasicBlock *MBB) const {
12695   // Emit va_arg instruction on X86-64.
12696
12697   // Operands to this pseudo-instruction:
12698   // 0  ) Output        : destination address (reg)
12699   // 1-5) Input         : va_list address (addr, i64mem)
12700   // 6  ) ArgSize       : Size (in bytes) of vararg type
12701   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12702   // 8  ) Align         : Alignment of type
12703   // 9  ) EFLAGS (implicit-def)
12704
12705   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12706   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12707
12708   unsigned DestReg = MI->getOperand(0).getReg();
12709   MachineOperand &Base = MI->getOperand(1);
12710   MachineOperand &Scale = MI->getOperand(2);
12711   MachineOperand &Index = MI->getOperand(3);
12712   MachineOperand &Disp = MI->getOperand(4);
12713   MachineOperand &Segment = MI->getOperand(5);
12714   unsigned ArgSize = MI->getOperand(6).getImm();
12715   unsigned ArgMode = MI->getOperand(7).getImm();
12716   unsigned Align = MI->getOperand(8).getImm();
12717
12718   // Memory Reference
12719   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12720   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12721   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12722
12723   // Machine Information
12724   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12725   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12726   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12727   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12728   DebugLoc DL = MI->getDebugLoc();
12729
12730   // struct va_list {
12731   //   i32   gp_offset
12732   //   i32   fp_offset
12733   //   i64   overflow_area (address)
12734   //   i64   reg_save_area (address)
12735   // }
12736   // sizeof(va_list) = 24
12737   // alignment(va_list) = 8
12738
12739   unsigned TotalNumIntRegs = 6;
12740   unsigned TotalNumXMMRegs = 8;
12741   bool UseGPOffset = (ArgMode == 1);
12742   bool UseFPOffset = (ArgMode == 2);
12743   unsigned MaxOffset = TotalNumIntRegs * 8 +
12744                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12745
12746   /* Align ArgSize to a multiple of 8 */
12747   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12748   bool NeedsAlign = (Align > 8);
12749
12750   MachineBasicBlock *thisMBB = MBB;
12751   MachineBasicBlock *overflowMBB;
12752   MachineBasicBlock *offsetMBB;
12753   MachineBasicBlock *endMBB;
12754
12755   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12756   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12757   unsigned OffsetReg = 0;
12758
12759   if (!UseGPOffset && !UseFPOffset) {
12760     // If we only pull from the overflow region, we don't create a branch.
12761     // We don't need to alter control flow.
12762     OffsetDestReg = 0; // unused
12763     OverflowDestReg = DestReg;
12764
12765     offsetMBB = NULL;
12766     overflowMBB = thisMBB;
12767     endMBB = thisMBB;
12768   } else {
12769     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12770     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12771     // If not, pull from overflow_area. (branch to overflowMBB)
12772     //
12773     //       thisMBB
12774     //         |     .
12775     //         |        .
12776     //     offsetMBB   overflowMBB
12777     //         |        .
12778     //         |     .
12779     //        endMBB
12780
12781     // Registers for the PHI in endMBB
12782     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12783     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12784
12785     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12786     MachineFunction *MF = MBB->getParent();
12787     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12788     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12789     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12790
12791     MachineFunction::iterator MBBIter = MBB;
12792     ++MBBIter;
12793
12794     // Insert the new basic blocks
12795     MF->insert(MBBIter, offsetMBB);
12796     MF->insert(MBBIter, overflowMBB);
12797     MF->insert(MBBIter, endMBB);
12798
12799     // Transfer the remainder of MBB and its successor edges to endMBB.
12800     endMBB->splice(endMBB->begin(), thisMBB,
12801                     llvm::next(MachineBasicBlock::iterator(MI)),
12802                     thisMBB->end());
12803     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12804
12805     // Make offsetMBB and overflowMBB successors of thisMBB
12806     thisMBB->addSuccessor(offsetMBB);
12807     thisMBB->addSuccessor(overflowMBB);
12808
12809     // endMBB is a successor of both offsetMBB and overflowMBB
12810     offsetMBB->addSuccessor(endMBB);
12811     overflowMBB->addSuccessor(endMBB);
12812
12813     // Load the offset value into a register
12814     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12815     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12816       .addOperand(Base)
12817       .addOperand(Scale)
12818       .addOperand(Index)
12819       .addDisp(Disp, UseFPOffset ? 4 : 0)
12820       .addOperand(Segment)
12821       .setMemRefs(MMOBegin, MMOEnd);
12822
12823     // Check if there is enough room left to pull this argument.
12824     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12825       .addReg(OffsetReg)
12826       .addImm(MaxOffset + 8 - ArgSizeA8);
12827
12828     // Branch to "overflowMBB" if offset >= max
12829     // Fall through to "offsetMBB" otherwise
12830     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12831       .addMBB(overflowMBB);
12832   }
12833
12834   // In offsetMBB, emit code to use the reg_save_area.
12835   if (offsetMBB) {
12836     assert(OffsetReg != 0);
12837
12838     // Read the reg_save_area address.
12839     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12840     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12841       .addOperand(Base)
12842       .addOperand(Scale)
12843       .addOperand(Index)
12844       .addDisp(Disp, 16)
12845       .addOperand(Segment)
12846       .setMemRefs(MMOBegin, MMOEnd);
12847
12848     // Zero-extend the offset
12849     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12850       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12851         .addImm(0)
12852         .addReg(OffsetReg)
12853         .addImm(X86::sub_32bit);
12854
12855     // Add the offset to the reg_save_area to get the final address.
12856     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12857       .addReg(OffsetReg64)
12858       .addReg(RegSaveReg);
12859
12860     // Compute the offset for the next argument
12861     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12862     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12863       .addReg(OffsetReg)
12864       .addImm(UseFPOffset ? 16 : 8);
12865
12866     // Store it back into the va_list.
12867     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12868       .addOperand(Base)
12869       .addOperand(Scale)
12870       .addOperand(Index)
12871       .addDisp(Disp, UseFPOffset ? 4 : 0)
12872       .addOperand(Segment)
12873       .addReg(NextOffsetReg)
12874       .setMemRefs(MMOBegin, MMOEnd);
12875
12876     // Jump to endMBB
12877     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12878       .addMBB(endMBB);
12879   }
12880
12881   //
12882   // Emit code to use overflow area
12883   //
12884
12885   // Load the overflow_area address into a register.
12886   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12887   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12888     .addOperand(Base)
12889     .addOperand(Scale)
12890     .addOperand(Index)
12891     .addDisp(Disp, 8)
12892     .addOperand(Segment)
12893     .setMemRefs(MMOBegin, MMOEnd);
12894
12895   // If we need to align it, do so. Otherwise, just copy the address
12896   // to OverflowDestReg.
12897   if (NeedsAlign) {
12898     // Align the overflow address
12899     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12900     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12901
12902     // aligned_addr = (addr + (align-1)) & ~(align-1)
12903     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12904       .addReg(OverflowAddrReg)
12905       .addImm(Align-1);
12906
12907     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12908       .addReg(TmpReg)
12909       .addImm(~(uint64_t)(Align-1));
12910   } else {
12911     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12912       .addReg(OverflowAddrReg);
12913   }
12914
12915   // Compute the next overflow address after this argument.
12916   // (the overflow address should be kept 8-byte aligned)
12917   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12918   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12919     .addReg(OverflowDestReg)
12920     .addImm(ArgSizeA8);
12921
12922   // Store the new overflow address.
12923   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12924     .addOperand(Base)
12925     .addOperand(Scale)
12926     .addOperand(Index)
12927     .addDisp(Disp, 8)
12928     .addOperand(Segment)
12929     .addReg(NextAddrReg)
12930     .setMemRefs(MMOBegin, MMOEnd);
12931
12932   // If we branched, emit the PHI to the front of endMBB.
12933   if (offsetMBB) {
12934     BuildMI(*endMBB, endMBB->begin(), DL,
12935             TII->get(X86::PHI), DestReg)
12936       .addReg(OffsetDestReg).addMBB(offsetMBB)
12937       .addReg(OverflowDestReg).addMBB(overflowMBB);
12938   }
12939
12940   // Erase the pseudo instruction
12941   MI->eraseFromParent();
12942
12943   return endMBB;
12944 }
12945
12946 MachineBasicBlock *
12947 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12948                                                  MachineInstr *MI,
12949                                                  MachineBasicBlock *MBB) const {
12950   // Emit code to save XMM registers to the stack. The ABI says that the
12951   // number of registers to save is given in %al, so it's theoretically
12952   // possible to do an indirect jump trick to avoid saving all of them,
12953   // however this code takes a simpler approach and just executes all
12954   // of the stores if %al is non-zero. It's less code, and it's probably
12955   // easier on the hardware branch predictor, and stores aren't all that
12956   // expensive anyway.
12957
12958   // Create the new basic blocks. One block contains all the XMM stores,
12959   // and one block is the final destination regardless of whether any
12960   // stores were performed.
12961   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12962   MachineFunction *F = MBB->getParent();
12963   MachineFunction::iterator MBBIter = MBB;
12964   ++MBBIter;
12965   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12966   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12967   F->insert(MBBIter, XMMSaveMBB);
12968   F->insert(MBBIter, EndMBB);
12969
12970   // Transfer the remainder of MBB and its successor edges to EndMBB.
12971   EndMBB->splice(EndMBB->begin(), MBB,
12972                  llvm::next(MachineBasicBlock::iterator(MI)),
12973                  MBB->end());
12974   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12975
12976   // The original block will now fall through to the XMM save block.
12977   MBB->addSuccessor(XMMSaveMBB);
12978   // The XMMSaveMBB will fall through to the end block.
12979   XMMSaveMBB->addSuccessor(EndMBB);
12980
12981   // Now add the instructions.
12982   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12983   DebugLoc DL = MI->getDebugLoc();
12984
12985   unsigned CountReg = MI->getOperand(0).getReg();
12986   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12987   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12988
12989   if (!Subtarget->isTargetWin64()) {
12990     // If %al is 0, branch around the XMM save block.
12991     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12992     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12993     MBB->addSuccessor(EndMBB);
12994   }
12995
12996   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12997   // In the XMM save block, save all the XMM argument registers.
12998   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12999     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13000     MachineMemOperand *MMO =
13001       F->getMachineMemOperand(
13002           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13003         MachineMemOperand::MOStore,
13004         /*Size=*/16, /*Align=*/16);
13005     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13006       .addFrameIndex(RegSaveFrameIndex)
13007       .addImm(/*Scale=*/1)
13008       .addReg(/*IndexReg=*/0)
13009       .addImm(/*Disp=*/Offset)
13010       .addReg(/*Segment=*/0)
13011       .addReg(MI->getOperand(i).getReg())
13012       .addMemOperand(MMO);
13013   }
13014
13015   MI->eraseFromParent();   // The pseudo instruction is gone now.
13016
13017   return EndMBB;
13018 }
13019
13020 // The EFLAGS operand of SelectItr might be missing a kill marker
13021 // because there were multiple uses of EFLAGS, and ISel didn't know
13022 // which to mark. Figure out whether SelectItr should have had a
13023 // kill marker, and set it if it should. Returns the correct kill
13024 // marker value.
13025 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13026                                      MachineBasicBlock* BB,
13027                                      const TargetRegisterInfo* TRI) {
13028   // Scan forward through BB for a use/def of EFLAGS.
13029   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13030   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13031     const MachineInstr& mi = *miI;
13032     if (mi.readsRegister(X86::EFLAGS))
13033       return false;
13034     if (mi.definesRegister(X86::EFLAGS))
13035       break; // Should have kill-flag - update below.
13036   }
13037
13038   // If we hit the end of the block, check whether EFLAGS is live into a
13039   // successor.
13040   if (miI == BB->end()) {
13041     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13042                                           sEnd = BB->succ_end();
13043          sItr != sEnd; ++sItr) {
13044       MachineBasicBlock* succ = *sItr;
13045       if (succ->isLiveIn(X86::EFLAGS))
13046         return false;
13047     }
13048   }
13049
13050   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13051   // out. SelectMI should have a kill flag on EFLAGS.
13052   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13053   return true;
13054 }
13055
13056 MachineBasicBlock *
13057 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13058                                      MachineBasicBlock *BB) const {
13059   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13060   DebugLoc DL = MI->getDebugLoc();
13061
13062   // To "insert" a SELECT_CC instruction, we actually have to insert the
13063   // diamond control-flow pattern.  The incoming instruction knows the
13064   // destination vreg to set, the condition code register to branch on, the
13065   // true/false values to select between, and a branch opcode to use.
13066   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13067   MachineFunction::iterator It = BB;
13068   ++It;
13069
13070   //  thisMBB:
13071   //  ...
13072   //   TrueVal = ...
13073   //   cmpTY ccX, r1, r2
13074   //   bCC copy1MBB
13075   //   fallthrough --> copy0MBB
13076   MachineBasicBlock *thisMBB = BB;
13077   MachineFunction *F = BB->getParent();
13078   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13079   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13080   F->insert(It, copy0MBB);
13081   F->insert(It, sinkMBB);
13082
13083   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13084   // live into the sink and copy blocks.
13085   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13086   if (!MI->killsRegister(X86::EFLAGS) &&
13087       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13088     copy0MBB->addLiveIn(X86::EFLAGS);
13089     sinkMBB->addLiveIn(X86::EFLAGS);
13090   }
13091
13092   // Transfer the remainder of BB and its successor edges to sinkMBB.
13093   sinkMBB->splice(sinkMBB->begin(), BB,
13094                   llvm::next(MachineBasicBlock::iterator(MI)),
13095                   BB->end());
13096   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13097
13098   // Add the true and fallthrough blocks as its successors.
13099   BB->addSuccessor(copy0MBB);
13100   BB->addSuccessor(sinkMBB);
13101
13102   // Create the conditional branch instruction.
13103   unsigned Opc =
13104     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13105   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13106
13107   //  copy0MBB:
13108   //   %FalseValue = ...
13109   //   # fallthrough to sinkMBB
13110   copy0MBB->addSuccessor(sinkMBB);
13111
13112   //  sinkMBB:
13113   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13114   //  ...
13115   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13116           TII->get(X86::PHI), MI->getOperand(0).getReg())
13117     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13118     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13119
13120   MI->eraseFromParent();   // The pseudo instruction is gone now.
13121   return sinkMBB;
13122 }
13123
13124 MachineBasicBlock *
13125 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13126                                         bool Is64Bit) const {
13127   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13128   DebugLoc DL = MI->getDebugLoc();
13129   MachineFunction *MF = BB->getParent();
13130   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13131
13132   assert(getTargetMachine().Options.EnableSegmentedStacks);
13133
13134   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13135   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13136
13137   // BB:
13138   //  ... [Till the alloca]
13139   // If stacklet is not large enough, jump to mallocMBB
13140   //
13141   // bumpMBB:
13142   //  Allocate by subtracting from RSP
13143   //  Jump to continueMBB
13144   //
13145   // mallocMBB:
13146   //  Allocate by call to runtime
13147   //
13148   // continueMBB:
13149   //  ...
13150   //  [rest of original BB]
13151   //
13152
13153   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13154   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13155   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13156
13157   MachineRegisterInfo &MRI = MF->getRegInfo();
13158   const TargetRegisterClass *AddrRegClass =
13159     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13160
13161   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13162     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13163     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13164     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13165     sizeVReg = MI->getOperand(1).getReg(),
13166     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13167
13168   MachineFunction::iterator MBBIter = BB;
13169   ++MBBIter;
13170
13171   MF->insert(MBBIter, bumpMBB);
13172   MF->insert(MBBIter, mallocMBB);
13173   MF->insert(MBBIter, continueMBB);
13174
13175   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13176                       (MachineBasicBlock::iterator(MI)), BB->end());
13177   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13178
13179   // Add code to the main basic block to check if the stack limit has been hit,
13180   // and if so, jump to mallocMBB otherwise to bumpMBB.
13181   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13182   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13183     .addReg(tmpSPVReg).addReg(sizeVReg);
13184   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13185     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13186     .addReg(SPLimitVReg);
13187   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13188
13189   // bumpMBB simply decreases the stack pointer, since we know the current
13190   // stacklet has enough space.
13191   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13192     .addReg(SPLimitVReg);
13193   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13194     .addReg(SPLimitVReg);
13195   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13196
13197   // Calls into a routine in libgcc to allocate more space from the heap.
13198   const uint32_t *RegMask =
13199     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13200   if (Is64Bit) {
13201     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13202       .addReg(sizeVReg);
13203     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13204       .addExternalSymbol("__morestack_allocate_stack_space")
13205       .addRegMask(RegMask)
13206       .addReg(X86::RDI, RegState::Implicit)
13207       .addReg(X86::RAX, RegState::ImplicitDefine);
13208   } else {
13209     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13210       .addImm(12);
13211     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13212     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13213       .addExternalSymbol("__morestack_allocate_stack_space")
13214       .addRegMask(RegMask)
13215       .addReg(X86::EAX, RegState::ImplicitDefine);
13216   }
13217
13218   if (!Is64Bit)
13219     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13220       .addImm(16);
13221
13222   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13223     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13224   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13225
13226   // Set up the CFG correctly.
13227   BB->addSuccessor(bumpMBB);
13228   BB->addSuccessor(mallocMBB);
13229   mallocMBB->addSuccessor(continueMBB);
13230   bumpMBB->addSuccessor(continueMBB);
13231
13232   // Take care of the PHI nodes.
13233   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13234           MI->getOperand(0).getReg())
13235     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13236     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13237
13238   // Delete the original pseudo instruction.
13239   MI->eraseFromParent();
13240
13241   // And we're done.
13242   return continueMBB;
13243 }
13244
13245 MachineBasicBlock *
13246 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13247                                           MachineBasicBlock *BB) const {
13248   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13249   DebugLoc DL = MI->getDebugLoc();
13250
13251   assert(!Subtarget->isTargetEnvMacho());
13252
13253   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13254   // non-trivial part is impdef of ESP.
13255
13256   if (Subtarget->isTargetWin64()) {
13257     if (Subtarget->isTargetCygMing()) {
13258       // ___chkstk(Mingw64):
13259       // Clobbers R10, R11, RAX and EFLAGS.
13260       // Updates RSP.
13261       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13262         .addExternalSymbol("___chkstk")
13263         .addReg(X86::RAX, RegState::Implicit)
13264         .addReg(X86::RSP, RegState::Implicit)
13265         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13266         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13267         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13268     } else {
13269       // __chkstk(MSVCRT): does not update stack pointer.
13270       // Clobbers R10, R11 and EFLAGS.
13271       // FIXME: RAX(allocated size) might be reused and not killed.
13272       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13273         .addExternalSymbol("__chkstk")
13274         .addReg(X86::RAX, RegState::Implicit)
13275         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13276       // RAX has the offset to subtracted from RSP.
13277       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13278         .addReg(X86::RSP)
13279         .addReg(X86::RAX);
13280     }
13281   } else {
13282     const char *StackProbeSymbol =
13283       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13284
13285     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13286       .addExternalSymbol(StackProbeSymbol)
13287       .addReg(X86::EAX, RegState::Implicit)
13288       .addReg(X86::ESP, RegState::Implicit)
13289       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13290       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13291       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13292   }
13293
13294   MI->eraseFromParent();   // The pseudo instruction is gone now.
13295   return BB;
13296 }
13297
13298 MachineBasicBlock *
13299 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13300                                       MachineBasicBlock *BB) const {
13301   // This is pretty easy.  We're taking the value that we received from
13302   // our load from the relocation, sticking it in either RDI (x86-64)
13303   // or EAX and doing an indirect call.  The return value will then
13304   // be in the normal return register.
13305   const X86InstrInfo *TII
13306     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13307   DebugLoc DL = MI->getDebugLoc();
13308   MachineFunction *F = BB->getParent();
13309
13310   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13311   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13312
13313   // Get a register mask for the lowered call.
13314   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13315   // proper register mask.
13316   const uint32_t *RegMask =
13317     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13318   if (Subtarget->is64Bit()) {
13319     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13320                                       TII->get(X86::MOV64rm), X86::RDI)
13321     .addReg(X86::RIP)
13322     .addImm(0).addReg(0)
13323     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13324                       MI->getOperand(3).getTargetFlags())
13325     .addReg(0);
13326     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13327     addDirectMem(MIB, X86::RDI);
13328     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13329   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13330     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13331                                       TII->get(X86::MOV32rm), X86::EAX)
13332     .addReg(0)
13333     .addImm(0).addReg(0)
13334     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13335                       MI->getOperand(3).getTargetFlags())
13336     .addReg(0);
13337     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13338     addDirectMem(MIB, X86::EAX);
13339     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13340   } else {
13341     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13342                                       TII->get(X86::MOV32rm), X86::EAX)
13343     .addReg(TII->getGlobalBaseReg(F))
13344     .addImm(0).addReg(0)
13345     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13346                       MI->getOperand(3).getTargetFlags())
13347     .addReg(0);
13348     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13349     addDirectMem(MIB, X86::EAX);
13350     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13351   }
13352
13353   MI->eraseFromParent(); // The pseudo instruction is gone now.
13354   return BB;
13355 }
13356
13357 MachineBasicBlock *
13358 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13359                                     MachineBasicBlock *MBB) const {
13360   DebugLoc DL = MI->getDebugLoc();
13361   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13362
13363   MachineFunction *MF = MBB->getParent();
13364   MachineRegisterInfo &MRI = MF->getRegInfo();
13365
13366   const BasicBlock *BB = MBB->getBasicBlock();
13367   MachineFunction::iterator I = MBB;
13368   ++I;
13369
13370   // Memory Reference
13371   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13372   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13373
13374   unsigned DstReg;
13375   unsigned MemOpndSlot = 0;
13376
13377   unsigned CurOp = 0;
13378
13379   DstReg = MI->getOperand(CurOp++).getReg();
13380   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13381   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13382   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13383   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13384
13385   MemOpndSlot = CurOp;
13386
13387   MVT PVT = getPointerTy();
13388   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13389          "Invalid Pointer Size!");
13390
13391   // For v = setjmp(buf), we generate
13392   //
13393   // thisMBB:
13394   //  buf[LabelOffset] = restoreMBB
13395   //  SjLjSetup restoreMBB
13396   //
13397   // mainMBB:
13398   //  v_main = 0
13399   //
13400   // sinkMBB:
13401   //  v = phi(main, restore)
13402   //
13403   // restoreMBB:
13404   //  v_restore = 1
13405
13406   MachineBasicBlock *thisMBB = MBB;
13407   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13408   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13409   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13410   MF->insert(I, mainMBB);
13411   MF->insert(I, sinkMBB);
13412   MF->push_back(restoreMBB);
13413
13414   MachineInstrBuilder MIB;
13415
13416   // Transfer the remainder of BB and its successor edges to sinkMBB.
13417   sinkMBB->splice(sinkMBB->begin(), MBB,
13418                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13419   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13420
13421   // thisMBB:
13422   unsigned PtrStoreOpc = 0;
13423   unsigned LabelReg = 0;
13424   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13425   Reloc::Model RM = getTargetMachine().getRelocationModel();
13426   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13427                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13428
13429   // Prepare IP either in reg or imm.
13430   if (!UseImmLabel) {
13431     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13432     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13433     LabelReg = MRI.createVirtualRegister(PtrRC);
13434     if (Subtarget->is64Bit()) {
13435       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13436               .addReg(X86::RIP)
13437               .addImm(0)
13438               .addReg(0)
13439               .addMBB(restoreMBB)
13440               .addReg(0);
13441     } else {
13442       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13443       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13444               .addReg(XII->getGlobalBaseReg(MF))
13445               .addImm(0)
13446               .addReg(0)
13447               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13448               .addReg(0);
13449     }
13450   } else
13451     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13452   // Store IP
13453   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13454   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13455     if (i == X86::AddrDisp)
13456       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13457     else
13458       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13459   }
13460   if (!UseImmLabel)
13461     MIB.addReg(LabelReg);
13462   else
13463     MIB.addMBB(restoreMBB);
13464   MIB.setMemRefs(MMOBegin, MMOEnd);
13465   // Setup
13466   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13467           .addMBB(restoreMBB);
13468   MIB.addRegMask(RegInfo->getNoPreservedMask());
13469   thisMBB->addSuccessor(mainMBB);
13470   thisMBB->addSuccessor(restoreMBB);
13471
13472   // mainMBB:
13473   //  EAX = 0
13474   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13475   mainMBB->addSuccessor(sinkMBB);
13476
13477   // sinkMBB:
13478   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13479           TII->get(X86::PHI), DstReg)
13480     .addReg(mainDstReg).addMBB(mainMBB)
13481     .addReg(restoreDstReg).addMBB(restoreMBB);
13482
13483   // restoreMBB:
13484   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13485   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13486   restoreMBB->addSuccessor(sinkMBB);
13487
13488   MI->eraseFromParent();
13489   return sinkMBB;
13490 }
13491
13492 MachineBasicBlock *
13493 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13494                                      MachineBasicBlock *MBB) const {
13495   DebugLoc DL = MI->getDebugLoc();
13496   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13497
13498   MachineFunction *MF = MBB->getParent();
13499   MachineRegisterInfo &MRI = MF->getRegInfo();
13500
13501   // Memory Reference
13502   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13503   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13504
13505   MVT PVT = getPointerTy();
13506   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13507          "Invalid Pointer Size!");
13508
13509   const TargetRegisterClass *RC =
13510     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13511   unsigned Tmp = MRI.createVirtualRegister(RC);
13512   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13513   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13514   unsigned SP = RegInfo->getStackRegister();
13515
13516   MachineInstrBuilder MIB;
13517
13518   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13519   const int64_t SPOffset = 2 * PVT.getStoreSize();
13520
13521   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13522   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13523
13524   // Reload FP
13525   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13526   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13527     MIB.addOperand(MI->getOperand(i));
13528   MIB.setMemRefs(MMOBegin, MMOEnd);
13529   // Reload IP
13530   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13531   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13532     if (i == X86::AddrDisp)
13533       MIB.addDisp(MI->getOperand(i), LabelOffset);
13534     else
13535       MIB.addOperand(MI->getOperand(i));
13536   }
13537   MIB.setMemRefs(MMOBegin, MMOEnd);
13538   // Reload SP
13539   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13540   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13541     if (i == X86::AddrDisp)
13542       MIB.addDisp(MI->getOperand(i), SPOffset);
13543     else
13544       MIB.addOperand(MI->getOperand(i));
13545   }
13546   MIB.setMemRefs(MMOBegin, MMOEnd);
13547   // Jump
13548   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13549
13550   MI->eraseFromParent();
13551   return MBB;
13552 }
13553
13554 MachineBasicBlock *
13555 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13556                                                MachineBasicBlock *BB) const {
13557   switch (MI->getOpcode()) {
13558   default: llvm_unreachable("Unexpected instr type to insert");
13559   case X86::TAILJMPd64:
13560   case X86::TAILJMPr64:
13561   case X86::TAILJMPm64:
13562     llvm_unreachable("TAILJMP64 would not be touched here.");
13563   case X86::TCRETURNdi64:
13564   case X86::TCRETURNri64:
13565   case X86::TCRETURNmi64:
13566     return BB;
13567   case X86::WIN_ALLOCA:
13568     return EmitLoweredWinAlloca(MI, BB);
13569   case X86::SEG_ALLOCA_32:
13570     return EmitLoweredSegAlloca(MI, BB, false);
13571   case X86::SEG_ALLOCA_64:
13572     return EmitLoweredSegAlloca(MI, BB, true);
13573   case X86::TLSCall_32:
13574   case X86::TLSCall_64:
13575     return EmitLoweredTLSCall(MI, BB);
13576   case X86::CMOV_GR8:
13577   case X86::CMOV_FR32:
13578   case X86::CMOV_FR64:
13579   case X86::CMOV_V4F32:
13580   case X86::CMOV_V2F64:
13581   case X86::CMOV_V2I64:
13582   case X86::CMOV_V8F32:
13583   case X86::CMOV_V4F64:
13584   case X86::CMOV_V4I64:
13585   case X86::CMOV_GR16:
13586   case X86::CMOV_GR32:
13587   case X86::CMOV_RFP32:
13588   case X86::CMOV_RFP64:
13589   case X86::CMOV_RFP80:
13590     return EmitLoweredSelect(MI, BB);
13591
13592   case X86::FP32_TO_INT16_IN_MEM:
13593   case X86::FP32_TO_INT32_IN_MEM:
13594   case X86::FP32_TO_INT64_IN_MEM:
13595   case X86::FP64_TO_INT16_IN_MEM:
13596   case X86::FP64_TO_INT32_IN_MEM:
13597   case X86::FP64_TO_INT64_IN_MEM:
13598   case X86::FP80_TO_INT16_IN_MEM:
13599   case X86::FP80_TO_INT32_IN_MEM:
13600   case X86::FP80_TO_INT64_IN_MEM: {
13601     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13602     DebugLoc DL = MI->getDebugLoc();
13603
13604     // Change the floating point control register to use "round towards zero"
13605     // mode when truncating to an integer value.
13606     MachineFunction *F = BB->getParent();
13607     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13608     addFrameReference(BuildMI(*BB, MI, DL,
13609                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13610
13611     // Load the old value of the high byte of the control word...
13612     unsigned OldCW =
13613       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13614     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13615                       CWFrameIdx);
13616
13617     // Set the high part to be round to zero...
13618     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13619       .addImm(0xC7F);
13620
13621     // Reload the modified control word now...
13622     addFrameReference(BuildMI(*BB, MI, DL,
13623                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13624
13625     // Restore the memory image of control word to original value
13626     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13627       .addReg(OldCW);
13628
13629     // Get the X86 opcode to use.
13630     unsigned Opc;
13631     switch (MI->getOpcode()) {
13632     default: llvm_unreachable("illegal opcode!");
13633     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13634     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13635     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13636     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13637     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13638     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13639     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13640     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13641     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13642     }
13643
13644     X86AddressMode AM;
13645     MachineOperand &Op = MI->getOperand(0);
13646     if (Op.isReg()) {
13647       AM.BaseType = X86AddressMode::RegBase;
13648       AM.Base.Reg = Op.getReg();
13649     } else {
13650       AM.BaseType = X86AddressMode::FrameIndexBase;
13651       AM.Base.FrameIndex = Op.getIndex();
13652     }
13653     Op = MI->getOperand(1);
13654     if (Op.isImm())
13655       AM.Scale = Op.getImm();
13656     Op = MI->getOperand(2);
13657     if (Op.isImm())
13658       AM.IndexReg = Op.getImm();
13659     Op = MI->getOperand(3);
13660     if (Op.isGlobal()) {
13661       AM.GV = Op.getGlobal();
13662     } else {
13663       AM.Disp = Op.getImm();
13664     }
13665     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13666                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13667
13668     // Reload the original control word now.
13669     addFrameReference(BuildMI(*BB, MI, DL,
13670                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13671
13672     MI->eraseFromParent();   // The pseudo instruction is gone now.
13673     return BB;
13674   }
13675     // String/text processing lowering.
13676   case X86::PCMPISTRM128REG:
13677   case X86::VPCMPISTRM128REG:
13678   case X86::PCMPISTRM128MEM:
13679   case X86::VPCMPISTRM128MEM:
13680   case X86::PCMPESTRM128REG:
13681   case X86::VPCMPESTRM128REG:
13682   case X86::PCMPESTRM128MEM:
13683   case X86::VPCMPESTRM128MEM: {
13684     unsigned NumArgs;
13685     bool MemArg;
13686     switch (MI->getOpcode()) {
13687     default: llvm_unreachable("illegal opcode!");
13688     case X86::PCMPISTRM128REG:
13689     case X86::VPCMPISTRM128REG:
13690       NumArgs = 3; MemArg = false; break;
13691     case X86::PCMPISTRM128MEM:
13692     case X86::VPCMPISTRM128MEM:
13693       NumArgs = 3; MemArg = true; break;
13694     case X86::PCMPESTRM128REG:
13695     case X86::VPCMPESTRM128REG:
13696       NumArgs = 5; MemArg = false; break;
13697     case X86::PCMPESTRM128MEM:
13698     case X86::VPCMPESTRM128MEM:
13699       NumArgs = 5; MemArg = true; break;
13700     }
13701     return EmitPCMP(MI, BB, NumArgs, MemArg);
13702   }
13703
13704     // Thread synchronization.
13705   case X86::MONITOR:
13706     return EmitMonitor(MI, BB);
13707
13708     // Atomic Lowering.
13709   case X86::ATOMAND8:
13710   case X86::ATOMAND16:
13711   case X86::ATOMAND32:
13712   case X86::ATOMAND64:
13713     // Fall through
13714   case X86::ATOMOR8:
13715   case X86::ATOMOR16:
13716   case X86::ATOMOR32:
13717   case X86::ATOMOR64:
13718     // Fall through
13719   case X86::ATOMXOR16:
13720   case X86::ATOMXOR8:
13721   case X86::ATOMXOR32:
13722   case X86::ATOMXOR64:
13723     // Fall through
13724   case X86::ATOMNAND8:
13725   case X86::ATOMNAND16:
13726   case X86::ATOMNAND32:
13727   case X86::ATOMNAND64:
13728     // Fall through
13729   case X86::ATOMMAX8:
13730   case X86::ATOMMAX16:
13731   case X86::ATOMMAX32:
13732   case X86::ATOMMAX64:
13733     // Fall through
13734   case X86::ATOMMIN8:
13735   case X86::ATOMMIN16:
13736   case X86::ATOMMIN32:
13737   case X86::ATOMMIN64:
13738     // Fall through
13739   case X86::ATOMUMAX8:
13740   case X86::ATOMUMAX16:
13741   case X86::ATOMUMAX32:
13742   case X86::ATOMUMAX64:
13743     // Fall through
13744   case X86::ATOMUMIN8:
13745   case X86::ATOMUMIN16:
13746   case X86::ATOMUMIN32:
13747   case X86::ATOMUMIN64:
13748     return EmitAtomicLoadArith(MI, BB);
13749
13750   // This group does 64-bit operations on a 32-bit host.
13751   case X86::ATOMAND6432:
13752   case X86::ATOMOR6432:
13753   case X86::ATOMXOR6432:
13754   case X86::ATOMNAND6432:
13755   case X86::ATOMADD6432:
13756   case X86::ATOMSUB6432:
13757   case X86::ATOMMAX6432:
13758   case X86::ATOMMIN6432:
13759   case X86::ATOMUMAX6432:
13760   case X86::ATOMUMIN6432:
13761   case X86::ATOMSWAP6432:
13762     return EmitAtomicLoadArith6432(MI, BB);
13763
13764   case X86::VASTART_SAVE_XMM_REGS:
13765     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13766
13767   case X86::VAARG_64:
13768     return EmitVAARG64WithCustomInserter(MI, BB);
13769
13770   case X86::EH_SjLj_SetJmp32:
13771   case X86::EH_SjLj_SetJmp64:
13772     return emitEHSjLjSetJmp(MI, BB);
13773
13774   case X86::EH_SjLj_LongJmp32:
13775   case X86::EH_SjLj_LongJmp64:
13776     return emitEHSjLjLongJmp(MI, BB);
13777   }
13778 }
13779
13780 //===----------------------------------------------------------------------===//
13781 //                           X86 Optimization Hooks
13782 //===----------------------------------------------------------------------===//
13783
13784 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13785                                                        APInt &KnownZero,
13786                                                        APInt &KnownOne,
13787                                                        const SelectionDAG &DAG,
13788                                                        unsigned Depth) const {
13789   unsigned BitWidth = KnownZero.getBitWidth();
13790   unsigned Opc = Op.getOpcode();
13791   assert((Opc >= ISD::BUILTIN_OP_END ||
13792           Opc == ISD::INTRINSIC_WO_CHAIN ||
13793           Opc == ISD::INTRINSIC_W_CHAIN ||
13794           Opc == ISD::INTRINSIC_VOID) &&
13795          "Should use MaskedValueIsZero if you don't know whether Op"
13796          " is a target node!");
13797
13798   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13799   switch (Opc) {
13800   default: break;
13801   case X86ISD::ADD:
13802   case X86ISD::SUB:
13803   case X86ISD::ADC:
13804   case X86ISD::SBB:
13805   case X86ISD::SMUL:
13806   case X86ISD::UMUL:
13807   case X86ISD::INC:
13808   case X86ISD::DEC:
13809   case X86ISD::OR:
13810   case X86ISD::XOR:
13811   case X86ISD::AND:
13812     // These nodes' second result is a boolean.
13813     if (Op.getResNo() == 0)
13814       break;
13815     // Fallthrough
13816   case X86ISD::SETCC:
13817     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13818     break;
13819   case ISD::INTRINSIC_WO_CHAIN: {
13820     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13821     unsigned NumLoBits = 0;
13822     switch (IntId) {
13823     default: break;
13824     case Intrinsic::x86_sse_movmsk_ps:
13825     case Intrinsic::x86_avx_movmsk_ps_256:
13826     case Intrinsic::x86_sse2_movmsk_pd:
13827     case Intrinsic::x86_avx_movmsk_pd_256:
13828     case Intrinsic::x86_mmx_pmovmskb:
13829     case Intrinsic::x86_sse2_pmovmskb_128:
13830     case Intrinsic::x86_avx2_pmovmskb: {
13831       // High bits of movmskp{s|d}, pmovmskb are known zero.
13832       switch (IntId) {
13833         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13834         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13835         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13836         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13837         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13838         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13839         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13840         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13841       }
13842       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13843       break;
13844     }
13845     }
13846     break;
13847   }
13848   }
13849 }
13850
13851 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13852                                                          unsigned Depth) const {
13853   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13854   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13855     return Op.getValueType().getScalarType().getSizeInBits();
13856
13857   // Fallback case.
13858   return 1;
13859 }
13860
13861 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13862 /// node is a GlobalAddress + offset.
13863 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13864                                        const GlobalValue* &GA,
13865                                        int64_t &Offset) const {
13866   if (N->getOpcode() == X86ISD::Wrapper) {
13867     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13868       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13869       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13870       return true;
13871     }
13872   }
13873   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13874 }
13875
13876 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13877 /// same as extracting the high 128-bit part of 256-bit vector and then
13878 /// inserting the result into the low part of a new 256-bit vector
13879 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13880   EVT VT = SVOp->getValueType(0);
13881   unsigned NumElems = VT.getVectorNumElements();
13882
13883   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13884   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13885     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13886         SVOp->getMaskElt(j) >= 0)
13887       return false;
13888
13889   return true;
13890 }
13891
13892 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13893 /// same as extracting the low 128-bit part of 256-bit vector and then
13894 /// inserting the result into the high part of a new 256-bit vector
13895 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13896   EVT VT = SVOp->getValueType(0);
13897   unsigned NumElems = VT.getVectorNumElements();
13898
13899   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13900   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13901     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13902         SVOp->getMaskElt(j) >= 0)
13903       return false;
13904
13905   return true;
13906 }
13907
13908 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13909 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13910                                         TargetLowering::DAGCombinerInfo &DCI,
13911                                         const X86Subtarget* Subtarget) {
13912   DebugLoc dl = N->getDebugLoc();
13913   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13914   SDValue V1 = SVOp->getOperand(0);
13915   SDValue V2 = SVOp->getOperand(1);
13916   EVT VT = SVOp->getValueType(0);
13917   unsigned NumElems = VT.getVectorNumElements();
13918
13919   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13920       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13921     //
13922     //                   0,0,0,...
13923     //                      |
13924     //    V      UNDEF    BUILD_VECTOR    UNDEF
13925     //     \      /           \           /
13926     //  CONCAT_VECTOR         CONCAT_VECTOR
13927     //         \                  /
13928     //          \                /
13929     //          RESULT: V + zero extended
13930     //
13931     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13932         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13933         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13934       return SDValue();
13935
13936     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13937       return SDValue();
13938
13939     // To match the shuffle mask, the first half of the mask should
13940     // be exactly the first vector, and all the rest a splat with the
13941     // first element of the second one.
13942     for (unsigned i = 0; i != NumElems/2; ++i)
13943       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13944           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13945         return SDValue();
13946
13947     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13948     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13949       if (Ld->hasNUsesOfValue(1, 0)) {
13950         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13951         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13952         SDValue ResNode =
13953           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13954                                   Ld->getMemoryVT(),
13955                                   Ld->getPointerInfo(),
13956                                   Ld->getAlignment(),
13957                                   false/*isVolatile*/, true/*ReadMem*/,
13958                                   false/*WriteMem*/);
13959         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13960       }
13961     }
13962
13963     // Emit a zeroed vector and insert the desired subvector on its
13964     // first half.
13965     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13966     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13967     return DCI.CombineTo(N, InsV);
13968   }
13969
13970   //===--------------------------------------------------------------------===//
13971   // Combine some shuffles into subvector extracts and inserts:
13972   //
13973
13974   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13975   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13976     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13977     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13978     return DCI.CombineTo(N, InsV);
13979   }
13980
13981   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13982   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13983     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13984     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13985     return DCI.CombineTo(N, InsV);
13986   }
13987
13988   return SDValue();
13989 }
13990
13991 /// PerformShuffleCombine - Performs several different shuffle combines.
13992 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13993                                      TargetLowering::DAGCombinerInfo &DCI,
13994                                      const X86Subtarget *Subtarget) {
13995   DebugLoc dl = N->getDebugLoc();
13996   EVT VT = N->getValueType(0);
13997
13998   // Don't create instructions with illegal types after legalize types has run.
13999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14000   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14001     return SDValue();
14002
14003   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14004   if (Subtarget->hasAVX() && VT.is256BitVector() &&
14005       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14006     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14007
14008   // Only handle 128 wide vector from here on.
14009   if (!VT.is128BitVector())
14010     return SDValue();
14011
14012   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14013   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14014   // consecutive, non-overlapping, and in the right order.
14015   SmallVector<SDValue, 16> Elts;
14016   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14017     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14018
14019   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14020 }
14021
14022
14023 /// PerformTruncateCombine - Converts truncate operation to
14024 /// a sequence of vector shuffle operations.
14025 /// It is possible when we truncate 256-bit vector to 128-bit vector
14026 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14027                                       TargetLowering::DAGCombinerInfo &DCI,
14028                                       const X86Subtarget *Subtarget)  {
14029   if (!DCI.isBeforeLegalizeOps())
14030     return SDValue();
14031
14032   if (!Subtarget->hasAVX())
14033     return SDValue();
14034
14035   EVT VT = N->getValueType(0);
14036   SDValue Op = N->getOperand(0);
14037   EVT OpVT = Op.getValueType();
14038   DebugLoc dl = N->getDebugLoc();
14039
14040   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14041
14042     if (Subtarget->hasAVX2()) {
14043       // AVX2: v4i64 -> v4i32
14044
14045       // VPERMD
14046       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14047
14048       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14049       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14050                                 ShufMask);
14051
14052       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14053                          DAG.getIntPtrConstant(0));
14054     }
14055
14056     // AVX: v4i64 -> v4i32
14057     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14058                                DAG.getIntPtrConstant(0));
14059
14060     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14061                                DAG.getIntPtrConstant(2));
14062
14063     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14064     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14065
14066     // PSHUFD
14067     static const int ShufMask1[] = {0, 2, 0, 0};
14068
14069     SDValue Undef = DAG.getUNDEF(VT);
14070     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14071     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14072
14073     // MOVLHPS
14074     static const int ShufMask2[] = {0, 1, 4, 5};
14075
14076     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14077   }
14078
14079   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14080
14081     if (Subtarget->hasAVX2()) {
14082       // AVX2: v8i32 -> v8i16
14083
14084       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14085
14086       // PSHUFB
14087       SmallVector<SDValue,32> pshufbMask;
14088       for (unsigned i = 0; i < 2; ++i) {
14089         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14090         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14091         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14092         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14093         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14094         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14095         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14096         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14097         for (unsigned j = 0; j < 8; ++j)
14098           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14099       }
14100       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14101                                &pshufbMask[0], 32);
14102       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14103
14104       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14105
14106       static const int ShufMask[] = {0,  2,  -1,  -1};
14107       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14108                                 &ShufMask[0]);
14109
14110       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14111                        DAG.getIntPtrConstant(0));
14112
14113       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14114     }
14115
14116     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14117                                DAG.getIntPtrConstant(0));
14118
14119     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14120                                DAG.getIntPtrConstant(4));
14121
14122     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14123     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14124
14125     // PSHUFB
14126     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14127                                    -1, -1, -1, -1, -1, -1, -1, -1};
14128
14129     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14130     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14131     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14132
14133     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14134     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14135
14136     // MOVLHPS
14137     static const int ShufMask2[] = {0, 1, 4, 5};
14138
14139     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14140     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14141   }
14142
14143   return SDValue();
14144 }
14145
14146 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14147 /// specific shuffle of a load can be folded into a single element load.
14148 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14149 /// shuffles have been customed lowered so we need to handle those here.
14150 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14151                                          TargetLowering::DAGCombinerInfo &DCI) {
14152   if (DCI.isBeforeLegalizeOps())
14153     return SDValue();
14154
14155   SDValue InVec = N->getOperand(0);
14156   SDValue EltNo = N->getOperand(1);
14157
14158   if (!isa<ConstantSDNode>(EltNo))
14159     return SDValue();
14160
14161   EVT VT = InVec.getValueType();
14162
14163   bool HasShuffleIntoBitcast = false;
14164   if (InVec.getOpcode() == ISD::BITCAST) {
14165     // Don't duplicate a load with other uses.
14166     if (!InVec.hasOneUse())
14167       return SDValue();
14168     EVT BCVT = InVec.getOperand(0).getValueType();
14169     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14170       return SDValue();
14171     InVec = InVec.getOperand(0);
14172     HasShuffleIntoBitcast = true;
14173   }
14174
14175   if (!isTargetShuffle(InVec.getOpcode()))
14176     return SDValue();
14177
14178   // Don't duplicate a load with other uses.
14179   if (!InVec.hasOneUse())
14180     return SDValue();
14181
14182   SmallVector<int, 16> ShuffleMask;
14183   bool UnaryShuffle;
14184   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14185                             UnaryShuffle))
14186     return SDValue();
14187
14188   // Select the input vector, guarding against out of range extract vector.
14189   unsigned NumElems = VT.getVectorNumElements();
14190   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14191   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14192   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14193                                          : InVec.getOperand(1);
14194
14195   // If inputs to shuffle are the same for both ops, then allow 2 uses
14196   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14197
14198   if (LdNode.getOpcode() == ISD::BITCAST) {
14199     // Don't duplicate a load with other uses.
14200     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14201       return SDValue();
14202
14203     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14204     LdNode = LdNode.getOperand(0);
14205   }
14206
14207   if (!ISD::isNormalLoad(LdNode.getNode()))
14208     return SDValue();
14209
14210   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14211
14212   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14213     return SDValue();
14214
14215   if (HasShuffleIntoBitcast) {
14216     // If there's a bitcast before the shuffle, check if the load type and
14217     // alignment is valid.
14218     unsigned Align = LN0->getAlignment();
14219     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14220     unsigned NewAlign = TLI.getDataLayout()->
14221       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14222
14223     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14224       return SDValue();
14225   }
14226
14227   // All checks match so transform back to vector_shuffle so that DAG combiner
14228   // can finish the job
14229   DebugLoc dl = N->getDebugLoc();
14230
14231   // Create shuffle node taking into account the case that its a unary shuffle
14232   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14233   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14234                                  InVec.getOperand(0), Shuffle,
14235                                  &ShuffleMask[0]);
14236   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14237   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14238                      EltNo);
14239 }
14240
14241 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14242 /// generation and convert it from being a bunch of shuffles and extracts
14243 /// to a simple store and scalar loads to extract the elements.
14244 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14245                                          TargetLowering::DAGCombinerInfo &DCI) {
14246   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14247   if (NewOp.getNode())
14248     return NewOp;
14249
14250   SDValue InputVector = N->getOperand(0);
14251
14252   // Only operate on vectors of 4 elements, where the alternative shuffling
14253   // gets to be more expensive.
14254   if (InputVector.getValueType() != MVT::v4i32)
14255     return SDValue();
14256
14257   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14258   // single use which is a sign-extend or zero-extend, and all elements are
14259   // used.
14260   SmallVector<SDNode *, 4> Uses;
14261   unsigned ExtractedElements = 0;
14262   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14263        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14264     if (UI.getUse().getResNo() != InputVector.getResNo())
14265       return SDValue();
14266
14267     SDNode *Extract = *UI;
14268     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14269       return SDValue();
14270
14271     if (Extract->getValueType(0) != MVT::i32)
14272       return SDValue();
14273     if (!Extract->hasOneUse())
14274       return SDValue();
14275     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14276         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14277       return SDValue();
14278     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14279       return SDValue();
14280
14281     // Record which element was extracted.
14282     ExtractedElements |=
14283       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14284
14285     Uses.push_back(Extract);
14286   }
14287
14288   // If not all the elements were used, this may not be worthwhile.
14289   if (ExtractedElements != 15)
14290     return SDValue();
14291
14292   // Ok, we've now decided to do the transformation.
14293   DebugLoc dl = InputVector.getDebugLoc();
14294
14295   // Store the value to a temporary stack slot.
14296   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14297   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14298                             MachinePointerInfo(), false, false, 0);
14299
14300   // Replace each use (extract) with a load of the appropriate element.
14301   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14302        UE = Uses.end(); UI != UE; ++UI) {
14303     SDNode *Extract = *UI;
14304
14305     // cOMpute the element's address.
14306     SDValue Idx = Extract->getOperand(1);
14307     unsigned EltSize =
14308         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14309     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14310     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14311     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14312
14313     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14314                                      StackPtr, OffsetVal);
14315
14316     // Load the scalar.
14317     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14318                                      ScalarAddr, MachinePointerInfo(),
14319                                      false, false, false, 0);
14320
14321     // Replace the exact with the load.
14322     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14323   }
14324
14325   // The replacement was made in place; don't return anything.
14326   return SDValue();
14327 }
14328
14329 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14330 /// nodes.
14331 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14332                                     TargetLowering::DAGCombinerInfo &DCI,
14333                                     const X86Subtarget *Subtarget) {
14334   DebugLoc DL = N->getDebugLoc();
14335   SDValue Cond = N->getOperand(0);
14336   // Get the LHS/RHS of the select.
14337   SDValue LHS = N->getOperand(1);
14338   SDValue RHS = N->getOperand(2);
14339   EVT VT = LHS.getValueType();
14340
14341   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14342   // instructions match the semantics of the common C idiom x<y?x:y but not
14343   // x<=y?x:y, because of how they handle negative zero (which can be
14344   // ignored in unsafe-math mode).
14345   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14346       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14347       (Subtarget->hasSSE2() ||
14348        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14349     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14350
14351     unsigned Opcode = 0;
14352     // Check for x CC y ? x : y.
14353     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14354         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14355       switch (CC) {
14356       default: break;
14357       case ISD::SETULT:
14358         // Converting this to a min would handle NaNs incorrectly, and swapping
14359         // the operands would cause it to handle comparisons between positive
14360         // and negative zero incorrectly.
14361         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14362           if (!DAG.getTarget().Options.UnsafeFPMath &&
14363               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14364             break;
14365           std::swap(LHS, RHS);
14366         }
14367         Opcode = X86ISD::FMIN;
14368         break;
14369       case ISD::SETOLE:
14370         // Converting this to a min would handle comparisons between positive
14371         // and negative zero incorrectly.
14372         if (!DAG.getTarget().Options.UnsafeFPMath &&
14373             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14374           break;
14375         Opcode = X86ISD::FMIN;
14376         break;
14377       case ISD::SETULE:
14378         // Converting this to a min would handle both negative zeros and NaNs
14379         // incorrectly, but we can swap the operands to fix both.
14380         std::swap(LHS, RHS);
14381       case ISD::SETOLT:
14382       case ISD::SETLT:
14383       case ISD::SETLE:
14384         Opcode = X86ISD::FMIN;
14385         break;
14386
14387       case ISD::SETOGE:
14388         // Converting this to a max would handle comparisons between positive
14389         // and negative zero incorrectly.
14390         if (!DAG.getTarget().Options.UnsafeFPMath &&
14391             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14392           break;
14393         Opcode = X86ISD::FMAX;
14394         break;
14395       case ISD::SETUGT:
14396         // Converting this to a max would handle NaNs incorrectly, and swapping
14397         // the operands would cause it to handle comparisons between positive
14398         // and negative zero incorrectly.
14399         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14400           if (!DAG.getTarget().Options.UnsafeFPMath &&
14401               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14402             break;
14403           std::swap(LHS, RHS);
14404         }
14405         Opcode = X86ISD::FMAX;
14406         break;
14407       case ISD::SETUGE:
14408         // Converting this to a max would handle both negative zeros and NaNs
14409         // incorrectly, but we can swap the operands to fix both.
14410         std::swap(LHS, RHS);
14411       case ISD::SETOGT:
14412       case ISD::SETGT:
14413       case ISD::SETGE:
14414         Opcode = X86ISD::FMAX;
14415         break;
14416       }
14417     // Check for x CC y ? y : x -- a min/max with reversed arms.
14418     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14419                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14420       switch (CC) {
14421       default: break;
14422       case ISD::SETOGE:
14423         // Converting this to a min would handle comparisons between positive
14424         // and negative zero incorrectly, and swapping the operands would
14425         // cause it to handle NaNs incorrectly.
14426         if (!DAG.getTarget().Options.UnsafeFPMath &&
14427             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14428           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14429             break;
14430           std::swap(LHS, RHS);
14431         }
14432         Opcode = X86ISD::FMIN;
14433         break;
14434       case ISD::SETUGT:
14435         // Converting this to a min would handle NaNs incorrectly.
14436         if (!DAG.getTarget().Options.UnsafeFPMath &&
14437             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14438           break;
14439         Opcode = X86ISD::FMIN;
14440         break;
14441       case ISD::SETUGE:
14442         // Converting this to a min would handle both negative zeros and NaNs
14443         // incorrectly, but we can swap the operands to fix both.
14444         std::swap(LHS, RHS);
14445       case ISD::SETOGT:
14446       case ISD::SETGT:
14447       case ISD::SETGE:
14448         Opcode = X86ISD::FMIN;
14449         break;
14450
14451       case ISD::SETULT:
14452         // Converting this to a max would handle NaNs incorrectly.
14453         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14454           break;
14455         Opcode = X86ISD::FMAX;
14456         break;
14457       case ISD::SETOLE:
14458         // Converting this to a max would handle comparisons between positive
14459         // and negative zero incorrectly, and swapping the operands would
14460         // cause it to handle NaNs incorrectly.
14461         if (!DAG.getTarget().Options.UnsafeFPMath &&
14462             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14463           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14464             break;
14465           std::swap(LHS, RHS);
14466         }
14467         Opcode = X86ISD::FMAX;
14468         break;
14469       case ISD::SETULE:
14470         // Converting this to a max would handle both negative zeros and NaNs
14471         // incorrectly, but we can swap the operands to fix both.
14472         std::swap(LHS, RHS);
14473       case ISD::SETOLT:
14474       case ISD::SETLT:
14475       case ISD::SETLE:
14476         Opcode = X86ISD::FMAX;
14477         break;
14478       }
14479     }
14480
14481     if (Opcode)
14482       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14483   }
14484
14485   // If this is a select between two integer constants, try to do some
14486   // optimizations.
14487   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14488     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14489       // Don't do this for crazy integer types.
14490       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14491         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14492         // so that TrueC (the true value) is larger than FalseC.
14493         bool NeedsCondInvert = false;
14494
14495         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14496             // Efficiently invertible.
14497             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14498              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14499               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14500           NeedsCondInvert = true;
14501           std::swap(TrueC, FalseC);
14502         }
14503
14504         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14505         if (FalseC->getAPIntValue() == 0 &&
14506             TrueC->getAPIntValue().isPowerOf2()) {
14507           if (NeedsCondInvert) // Invert the condition if needed.
14508             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14509                                DAG.getConstant(1, Cond.getValueType()));
14510
14511           // Zero extend the condition if needed.
14512           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14513
14514           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14515           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14516                              DAG.getConstant(ShAmt, MVT::i8));
14517         }
14518
14519         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14520         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14521           if (NeedsCondInvert) // Invert the condition if needed.
14522             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14523                                DAG.getConstant(1, Cond.getValueType()));
14524
14525           // Zero extend the condition if needed.
14526           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14527                              FalseC->getValueType(0), Cond);
14528           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14529                              SDValue(FalseC, 0));
14530         }
14531
14532         // Optimize cases that will turn into an LEA instruction.  This requires
14533         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14534         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14535           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14536           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14537
14538           bool isFastMultiplier = false;
14539           if (Diff < 10) {
14540             switch ((unsigned char)Diff) {
14541               default: break;
14542               case 1:  // result = add base, cond
14543               case 2:  // result = lea base(    , cond*2)
14544               case 3:  // result = lea base(cond, cond*2)
14545               case 4:  // result = lea base(    , cond*4)
14546               case 5:  // result = lea base(cond, cond*4)
14547               case 8:  // result = lea base(    , cond*8)
14548               case 9:  // result = lea base(cond, cond*8)
14549                 isFastMultiplier = true;
14550                 break;
14551             }
14552           }
14553
14554           if (isFastMultiplier) {
14555             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14556             if (NeedsCondInvert) // Invert the condition if needed.
14557               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14558                                  DAG.getConstant(1, Cond.getValueType()));
14559
14560             // Zero extend the condition if needed.
14561             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14562                                Cond);
14563             // Scale the condition by the difference.
14564             if (Diff != 1)
14565               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14566                                  DAG.getConstant(Diff, Cond.getValueType()));
14567
14568             // Add the base if non-zero.
14569             if (FalseC->getAPIntValue() != 0)
14570               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14571                                  SDValue(FalseC, 0));
14572             return Cond;
14573           }
14574         }
14575       }
14576   }
14577
14578   // Canonicalize max and min:
14579   // (x > y) ? x : y -> (x >= y) ? x : y
14580   // (x < y) ? x : y -> (x <= y) ? x : y
14581   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14582   // the need for an extra compare
14583   // against zero. e.g.
14584   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14585   // subl   %esi, %edi
14586   // testl  %edi, %edi
14587   // movl   $0, %eax
14588   // cmovgl %edi, %eax
14589   // =>
14590   // xorl   %eax, %eax
14591   // subl   %esi, $edi
14592   // cmovsl %eax, %edi
14593   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14594       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14595       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14596     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14597     switch (CC) {
14598     default: break;
14599     case ISD::SETLT:
14600     case ISD::SETGT: {
14601       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14602       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14603                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14604       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14605     }
14606     }
14607   }
14608
14609   // If we know that this node is legal then we know that it is going to be
14610   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14611   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14612   // to simplify previous instructions.
14613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14614   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14615       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14616     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14617
14618     // Don't optimize vector selects that map to mask-registers.
14619     if (BitWidth == 1)
14620       return SDValue();
14621
14622     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14623     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14624
14625     APInt KnownZero, KnownOne;
14626     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14627                                           DCI.isBeforeLegalizeOps());
14628     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14629         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14630       DCI.CommitTargetLoweringOpt(TLO);
14631   }
14632
14633   return SDValue();
14634 }
14635
14636 // Check whether a boolean test is testing a boolean value generated by
14637 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14638 // code.
14639 //
14640 // Simplify the following patterns:
14641 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14642 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14643 // to (Op EFLAGS Cond)
14644 //
14645 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14646 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14647 // to (Op EFLAGS !Cond)
14648 //
14649 // where Op could be BRCOND or CMOV.
14650 //
14651 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14652   // Quit if not CMP and SUB with its value result used.
14653   if (Cmp.getOpcode() != X86ISD::CMP &&
14654       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14655       return SDValue();
14656
14657   // Quit if not used as a boolean value.
14658   if (CC != X86::COND_E && CC != X86::COND_NE)
14659     return SDValue();
14660
14661   // Check CMP operands. One of them should be 0 or 1 and the other should be
14662   // an SetCC or extended from it.
14663   SDValue Op1 = Cmp.getOperand(0);
14664   SDValue Op2 = Cmp.getOperand(1);
14665
14666   SDValue SetCC;
14667   const ConstantSDNode* C = 0;
14668   bool needOppositeCond = (CC == X86::COND_E);
14669
14670   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14671     SetCC = Op2;
14672   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14673     SetCC = Op1;
14674   else // Quit if all operands are not constants.
14675     return SDValue();
14676
14677   if (C->getZExtValue() == 1)
14678     needOppositeCond = !needOppositeCond;
14679   else if (C->getZExtValue() != 0)
14680     // Quit if the constant is neither 0 or 1.
14681     return SDValue();
14682
14683   // Skip 'zext' node.
14684   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14685     SetCC = SetCC.getOperand(0);
14686
14687   switch (SetCC.getOpcode()) {
14688   case X86ISD::SETCC:
14689     // Set the condition code or opposite one if necessary.
14690     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14691     if (needOppositeCond)
14692       CC = X86::GetOppositeBranchCondition(CC);
14693     return SetCC.getOperand(1);
14694   case X86ISD::CMOV: {
14695     // Check whether false/true value has canonical one, i.e. 0 or 1.
14696     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14697     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14698     // Quit if true value is not a constant.
14699     if (!TVal)
14700       return SDValue();
14701     // Quit if false value is not a constant.
14702     if (!FVal) {
14703       // A special case for rdrand, where 0 is set if false cond is found.
14704       SDValue Op = SetCC.getOperand(0);
14705       if (Op.getOpcode() != X86ISD::RDRAND)
14706         return SDValue();
14707     }
14708     // Quit if false value is not the constant 0 or 1.
14709     bool FValIsFalse = true;
14710     if (FVal && FVal->getZExtValue() != 0) {
14711       if (FVal->getZExtValue() != 1)
14712         return SDValue();
14713       // If FVal is 1, opposite cond is needed.
14714       needOppositeCond = !needOppositeCond;
14715       FValIsFalse = false;
14716     }
14717     // Quit if TVal is not the constant opposite of FVal.
14718     if (FValIsFalse && TVal->getZExtValue() != 1)
14719       return SDValue();
14720     if (!FValIsFalse && TVal->getZExtValue() != 0)
14721       return SDValue();
14722     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14723     if (needOppositeCond)
14724       CC = X86::GetOppositeBranchCondition(CC);
14725     return SetCC.getOperand(3);
14726   }
14727   }
14728
14729   return SDValue();
14730 }
14731
14732 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14733 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14734                                   TargetLowering::DAGCombinerInfo &DCI,
14735                                   const X86Subtarget *Subtarget) {
14736   DebugLoc DL = N->getDebugLoc();
14737
14738   // If the flag operand isn't dead, don't touch this CMOV.
14739   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14740     return SDValue();
14741
14742   SDValue FalseOp = N->getOperand(0);
14743   SDValue TrueOp = N->getOperand(1);
14744   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14745   SDValue Cond = N->getOperand(3);
14746
14747   if (CC == X86::COND_E || CC == X86::COND_NE) {
14748     switch (Cond.getOpcode()) {
14749     default: break;
14750     case X86ISD::BSR:
14751     case X86ISD::BSF:
14752       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14753       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14754         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14755     }
14756   }
14757
14758   SDValue Flags;
14759
14760   Flags = checkBoolTestSetCCCombine(Cond, CC);
14761   if (Flags.getNode() &&
14762       // Extra check as FCMOV only supports a subset of X86 cond.
14763       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14764     SDValue Ops[] = { FalseOp, TrueOp,
14765                       DAG.getConstant(CC, MVT::i8), Flags };
14766     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14767                        Ops, array_lengthof(Ops));
14768   }
14769
14770   // If this is a select between two integer constants, try to do some
14771   // optimizations.  Note that the operands are ordered the opposite of SELECT
14772   // operands.
14773   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14774     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14775       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14776       // larger than FalseC (the false value).
14777       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14778         CC = X86::GetOppositeBranchCondition(CC);
14779         std::swap(TrueC, FalseC);
14780         std::swap(TrueOp, FalseOp);
14781       }
14782
14783       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14784       // This is efficient for any integer data type (including i8/i16) and
14785       // shift amount.
14786       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14787         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14788                            DAG.getConstant(CC, MVT::i8), Cond);
14789
14790         // Zero extend the condition if needed.
14791         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14792
14793         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14794         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14795                            DAG.getConstant(ShAmt, MVT::i8));
14796         if (N->getNumValues() == 2)  // Dead flag value?
14797           return DCI.CombineTo(N, Cond, SDValue());
14798         return Cond;
14799       }
14800
14801       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14802       // for any integer data type, including i8/i16.
14803       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14804         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14805                            DAG.getConstant(CC, MVT::i8), Cond);
14806
14807         // Zero extend the condition if needed.
14808         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14809                            FalseC->getValueType(0), Cond);
14810         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14811                            SDValue(FalseC, 0));
14812
14813         if (N->getNumValues() == 2)  // Dead flag value?
14814           return DCI.CombineTo(N, Cond, SDValue());
14815         return Cond;
14816       }
14817
14818       // Optimize cases that will turn into an LEA instruction.  This requires
14819       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14820       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14821         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14822         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14823
14824         bool isFastMultiplier = false;
14825         if (Diff < 10) {
14826           switch ((unsigned char)Diff) {
14827           default: break;
14828           case 1:  // result = add base, cond
14829           case 2:  // result = lea base(    , cond*2)
14830           case 3:  // result = lea base(cond, cond*2)
14831           case 4:  // result = lea base(    , cond*4)
14832           case 5:  // result = lea base(cond, cond*4)
14833           case 8:  // result = lea base(    , cond*8)
14834           case 9:  // result = lea base(cond, cond*8)
14835             isFastMultiplier = true;
14836             break;
14837           }
14838         }
14839
14840         if (isFastMultiplier) {
14841           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14842           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14843                              DAG.getConstant(CC, MVT::i8), Cond);
14844           // Zero extend the condition if needed.
14845           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14846                              Cond);
14847           // Scale the condition by the difference.
14848           if (Diff != 1)
14849             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14850                                DAG.getConstant(Diff, Cond.getValueType()));
14851
14852           // Add the base if non-zero.
14853           if (FalseC->getAPIntValue() != 0)
14854             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14855                                SDValue(FalseC, 0));
14856           if (N->getNumValues() == 2)  // Dead flag value?
14857             return DCI.CombineTo(N, Cond, SDValue());
14858           return Cond;
14859         }
14860       }
14861     }
14862   }
14863
14864   // Handle these cases:
14865   //   (select (x != c), e, c) -> select (x != c), e, x),
14866   //   (select (x == c), c, e) -> select (x == c), x, e)
14867   // where the c is an integer constant, and the "select" is the combination
14868   // of CMOV and CMP.
14869   //
14870   // The rationale for this change is that the conditional-move from a constant
14871   // needs two instructions, however, conditional-move from a register needs
14872   // only one instruction.
14873   //
14874   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14875   //  some instruction-combining opportunities. This opt needs to be
14876   //  postponed as late as possible.
14877   //
14878   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14879     // the DCI.xxxx conditions are provided to postpone the optimization as
14880     // late as possible.
14881
14882     ConstantSDNode *CmpAgainst = 0;
14883     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14884         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14885         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14886
14887       if (CC == X86::COND_NE &&
14888           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14889         CC = X86::GetOppositeBranchCondition(CC);
14890         std::swap(TrueOp, FalseOp);
14891       }
14892
14893       if (CC == X86::COND_E &&
14894           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14895         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14896                           DAG.getConstant(CC, MVT::i8), Cond };
14897         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14898                            array_lengthof(Ops));
14899       }
14900     }
14901   }
14902
14903   return SDValue();
14904 }
14905
14906
14907 /// PerformMulCombine - Optimize a single multiply with constant into two
14908 /// in order to implement it with two cheaper instructions, e.g.
14909 /// LEA + SHL, LEA + LEA.
14910 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14911                                  TargetLowering::DAGCombinerInfo &DCI) {
14912   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14913     return SDValue();
14914
14915   EVT VT = N->getValueType(0);
14916   if (VT != MVT::i64)
14917     return SDValue();
14918
14919   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14920   if (!C)
14921     return SDValue();
14922   uint64_t MulAmt = C->getZExtValue();
14923   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14924     return SDValue();
14925
14926   uint64_t MulAmt1 = 0;
14927   uint64_t MulAmt2 = 0;
14928   if ((MulAmt % 9) == 0) {
14929     MulAmt1 = 9;
14930     MulAmt2 = MulAmt / 9;
14931   } else if ((MulAmt % 5) == 0) {
14932     MulAmt1 = 5;
14933     MulAmt2 = MulAmt / 5;
14934   } else if ((MulAmt % 3) == 0) {
14935     MulAmt1 = 3;
14936     MulAmt2 = MulAmt / 3;
14937   }
14938   if (MulAmt2 &&
14939       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14940     DebugLoc DL = N->getDebugLoc();
14941
14942     if (isPowerOf2_64(MulAmt2) &&
14943         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14944       // If second multiplifer is pow2, issue it first. We want the multiply by
14945       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14946       // is an add.
14947       std::swap(MulAmt1, MulAmt2);
14948
14949     SDValue NewMul;
14950     if (isPowerOf2_64(MulAmt1))
14951       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14952                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14953     else
14954       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14955                            DAG.getConstant(MulAmt1, VT));
14956
14957     if (isPowerOf2_64(MulAmt2))
14958       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14959                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14960     else
14961       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14962                            DAG.getConstant(MulAmt2, VT));
14963
14964     // Do not add new nodes to DAG combiner worklist.
14965     DCI.CombineTo(N, NewMul, false);
14966   }
14967   return SDValue();
14968 }
14969
14970 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14971   SDValue N0 = N->getOperand(0);
14972   SDValue N1 = N->getOperand(1);
14973   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14974   EVT VT = N0.getValueType();
14975
14976   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14977   // since the result of setcc_c is all zero's or all ones.
14978   if (VT.isInteger() && !VT.isVector() &&
14979       N1C && N0.getOpcode() == ISD::AND &&
14980       N0.getOperand(1).getOpcode() == ISD::Constant) {
14981     SDValue N00 = N0.getOperand(0);
14982     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14983         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14984           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14985          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14986       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14987       APInt ShAmt = N1C->getAPIntValue();
14988       Mask = Mask.shl(ShAmt);
14989       if (Mask != 0)
14990         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14991                            N00, DAG.getConstant(Mask, VT));
14992     }
14993   }
14994
14995
14996   // Hardware support for vector shifts is sparse which makes us scalarize the
14997   // vector operations in many cases. Also, on sandybridge ADD is faster than
14998   // shl.
14999   // (shl V, 1) -> add V,V
15000   if (isSplatVector(N1.getNode())) {
15001     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15002     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15003     // We shift all of the values by one. In many cases we do not have
15004     // hardware support for this operation. This is better expressed as an ADD
15005     // of two values.
15006     if (N1C && (1 == N1C->getZExtValue())) {
15007       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15008     }
15009   }
15010
15011   return SDValue();
15012 }
15013
15014 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15015 ///                       when possible.
15016 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15017                                    TargetLowering::DAGCombinerInfo &DCI,
15018                                    const X86Subtarget *Subtarget) {
15019   EVT VT = N->getValueType(0);
15020   if (N->getOpcode() == ISD::SHL) {
15021     SDValue V = PerformSHLCombine(N, DAG);
15022     if (V.getNode()) return V;
15023   }
15024
15025   // On X86 with SSE2 support, we can transform this to a vector shift if
15026   // all elements are shifted by the same amount.  We can't do this in legalize
15027   // because the a constant vector is typically transformed to a constant pool
15028   // so we have no knowledge of the shift amount.
15029   if (!Subtarget->hasSSE2())
15030     return SDValue();
15031
15032   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15033       (!Subtarget->hasAVX2() ||
15034        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15035     return SDValue();
15036
15037   SDValue ShAmtOp = N->getOperand(1);
15038   EVT EltVT = VT.getVectorElementType();
15039   DebugLoc DL = N->getDebugLoc();
15040   SDValue BaseShAmt = SDValue();
15041   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15042     unsigned NumElts = VT.getVectorNumElements();
15043     unsigned i = 0;
15044     for (; i != NumElts; ++i) {
15045       SDValue Arg = ShAmtOp.getOperand(i);
15046       if (Arg.getOpcode() == ISD::UNDEF) continue;
15047       BaseShAmt = Arg;
15048       break;
15049     }
15050     // Handle the case where the build_vector is all undef
15051     // FIXME: Should DAG allow this?
15052     if (i == NumElts)
15053       return SDValue();
15054
15055     for (; i != NumElts; ++i) {
15056       SDValue Arg = ShAmtOp.getOperand(i);
15057       if (Arg.getOpcode() == ISD::UNDEF) continue;
15058       if (Arg != BaseShAmt) {
15059         return SDValue();
15060       }
15061     }
15062   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15063              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15064     SDValue InVec = ShAmtOp.getOperand(0);
15065     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15066       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15067       unsigned i = 0;
15068       for (; i != NumElts; ++i) {
15069         SDValue Arg = InVec.getOperand(i);
15070         if (Arg.getOpcode() == ISD::UNDEF) continue;
15071         BaseShAmt = Arg;
15072         break;
15073       }
15074     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15075        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15076          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15077          if (C->getZExtValue() == SplatIdx)
15078            BaseShAmt = InVec.getOperand(1);
15079        }
15080     }
15081     if (BaseShAmt.getNode() == 0) {
15082       // Don't create instructions with illegal types after legalize
15083       // types has run.
15084       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15085           !DCI.isBeforeLegalize())
15086         return SDValue();
15087
15088       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15089                               DAG.getIntPtrConstant(0));
15090     }
15091   } else
15092     return SDValue();
15093
15094   // The shift amount is an i32.
15095   if (EltVT.bitsGT(MVT::i32))
15096     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15097   else if (EltVT.bitsLT(MVT::i32))
15098     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15099
15100   // The shift amount is identical so we can do a vector shift.
15101   SDValue  ValOp = N->getOperand(0);
15102   switch (N->getOpcode()) {
15103   default:
15104     llvm_unreachable("Unknown shift opcode!");
15105   case ISD::SHL:
15106     switch (VT.getSimpleVT().SimpleTy) {
15107     default: return SDValue();
15108     case MVT::v2i64:
15109     case MVT::v4i32:
15110     case MVT::v8i16:
15111     case MVT::v4i64:
15112     case MVT::v8i32:
15113     case MVT::v16i16:
15114       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15115     }
15116   case ISD::SRA:
15117     switch (VT.getSimpleVT().SimpleTy) {
15118     default: return SDValue();
15119     case MVT::v4i32:
15120     case MVT::v8i16:
15121     case MVT::v8i32:
15122     case MVT::v16i16:
15123       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15124     }
15125   case ISD::SRL:
15126     switch (VT.getSimpleVT().SimpleTy) {
15127     default: return SDValue();
15128     case MVT::v2i64:
15129     case MVT::v4i32:
15130     case MVT::v8i16:
15131     case MVT::v4i64:
15132     case MVT::v8i32:
15133     case MVT::v16i16:
15134       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15135     }
15136   }
15137 }
15138
15139
15140 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15141 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15142 // and friends.  Likewise for OR -> CMPNEQSS.
15143 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15144                             TargetLowering::DAGCombinerInfo &DCI,
15145                             const X86Subtarget *Subtarget) {
15146   unsigned opcode;
15147
15148   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15149   // we're requiring SSE2 for both.
15150   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15151     SDValue N0 = N->getOperand(0);
15152     SDValue N1 = N->getOperand(1);
15153     SDValue CMP0 = N0->getOperand(1);
15154     SDValue CMP1 = N1->getOperand(1);
15155     DebugLoc DL = N->getDebugLoc();
15156
15157     // The SETCCs should both refer to the same CMP.
15158     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15159       return SDValue();
15160
15161     SDValue CMP00 = CMP0->getOperand(0);
15162     SDValue CMP01 = CMP0->getOperand(1);
15163     EVT     VT    = CMP00.getValueType();
15164
15165     if (VT == MVT::f32 || VT == MVT::f64) {
15166       bool ExpectingFlags = false;
15167       // Check for any users that want flags:
15168       for (SDNode::use_iterator UI = N->use_begin(),
15169              UE = N->use_end();
15170            !ExpectingFlags && UI != UE; ++UI)
15171         switch (UI->getOpcode()) {
15172         default:
15173         case ISD::BR_CC:
15174         case ISD::BRCOND:
15175         case ISD::SELECT:
15176           ExpectingFlags = true;
15177           break;
15178         case ISD::CopyToReg:
15179         case ISD::SIGN_EXTEND:
15180         case ISD::ZERO_EXTEND:
15181         case ISD::ANY_EXTEND:
15182           break;
15183         }
15184
15185       if (!ExpectingFlags) {
15186         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15187         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15188
15189         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15190           X86::CondCode tmp = cc0;
15191           cc0 = cc1;
15192           cc1 = tmp;
15193         }
15194
15195         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15196             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15197           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15198           X86ISD::NodeType NTOperator = is64BitFP ?
15199             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15200           // FIXME: need symbolic constants for these magic numbers.
15201           // See X86ATTInstPrinter.cpp:printSSECC().
15202           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15203           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15204                                               DAG.getConstant(x86cc, MVT::i8));
15205           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15206                                               OnesOrZeroesF);
15207           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15208                                       DAG.getConstant(1, MVT::i32));
15209           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15210           return OneBitOfTruth;
15211         }
15212       }
15213     }
15214   }
15215   return SDValue();
15216 }
15217
15218 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15219 /// so it can be folded inside ANDNP.
15220 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15221   EVT VT = N->getValueType(0);
15222
15223   // Match direct AllOnes for 128 and 256-bit vectors
15224   if (ISD::isBuildVectorAllOnes(N))
15225     return true;
15226
15227   // Look through a bit convert.
15228   if (N->getOpcode() == ISD::BITCAST)
15229     N = N->getOperand(0).getNode();
15230
15231   // Sometimes the operand may come from a insert_subvector building a 256-bit
15232   // allones vector
15233   if (VT.is256BitVector() &&
15234       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15235     SDValue V1 = N->getOperand(0);
15236     SDValue V2 = N->getOperand(1);
15237
15238     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15239         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15240         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15241         ISD::isBuildVectorAllOnes(V2.getNode()))
15242       return true;
15243   }
15244
15245   return false;
15246 }
15247
15248 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15249                                  TargetLowering::DAGCombinerInfo &DCI,
15250                                  const X86Subtarget *Subtarget) {
15251   if (DCI.isBeforeLegalizeOps())
15252     return SDValue();
15253
15254   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15255   if (R.getNode())
15256     return R;
15257
15258   EVT VT = N->getValueType(0);
15259
15260   // Create ANDN, BLSI, and BLSR instructions
15261   // BLSI is X & (-X)
15262   // BLSR is X & (X-1)
15263   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15264     SDValue N0 = N->getOperand(0);
15265     SDValue N1 = N->getOperand(1);
15266     DebugLoc DL = N->getDebugLoc();
15267
15268     // Check LHS for not
15269     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15270       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15271     // Check RHS for not
15272     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15273       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15274
15275     // Check LHS for neg
15276     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15277         isZero(N0.getOperand(0)))
15278       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15279
15280     // Check RHS for neg
15281     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15282         isZero(N1.getOperand(0)))
15283       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15284
15285     // Check LHS for X-1
15286     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15287         isAllOnes(N0.getOperand(1)))
15288       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15289
15290     // Check RHS for X-1
15291     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15292         isAllOnes(N1.getOperand(1)))
15293       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15294
15295     return SDValue();
15296   }
15297
15298   // Want to form ANDNP nodes:
15299   // 1) In the hopes of then easily combining them with OR and AND nodes
15300   //    to form PBLEND/PSIGN.
15301   // 2) To match ANDN packed intrinsics
15302   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15303     return SDValue();
15304
15305   SDValue N0 = N->getOperand(0);
15306   SDValue N1 = N->getOperand(1);
15307   DebugLoc DL = N->getDebugLoc();
15308
15309   // Check LHS for vnot
15310   if (N0.getOpcode() == ISD::XOR &&
15311       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15312       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15313     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15314
15315   // Check RHS for vnot
15316   if (N1.getOpcode() == ISD::XOR &&
15317       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15318       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15319     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15320
15321   return SDValue();
15322 }
15323
15324 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15325                                 TargetLowering::DAGCombinerInfo &DCI,
15326                                 const X86Subtarget *Subtarget) {
15327   if (DCI.isBeforeLegalizeOps())
15328     return SDValue();
15329
15330   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15331   if (R.getNode())
15332     return R;
15333
15334   EVT VT = N->getValueType(0);
15335
15336   SDValue N0 = N->getOperand(0);
15337   SDValue N1 = N->getOperand(1);
15338
15339   // look for psign/blend
15340   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15341     if (!Subtarget->hasSSSE3() ||
15342         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15343       return SDValue();
15344
15345     // Canonicalize pandn to RHS
15346     if (N0.getOpcode() == X86ISD::ANDNP)
15347       std::swap(N0, N1);
15348     // or (and (m, y), (pandn m, x))
15349     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15350       SDValue Mask = N1.getOperand(0);
15351       SDValue X    = N1.getOperand(1);
15352       SDValue Y;
15353       if (N0.getOperand(0) == Mask)
15354         Y = N0.getOperand(1);
15355       if (N0.getOperand(1) == Mask)
15356         Y = N0.getOperand(0);
15357
15358       // Check to see if the mask appeared in both the AND and ANDNP and
15359       if (!Y.getNode())
15360         return SDValue();
15361
15362       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15363       // Look through mask bitcast.
15364       if (Mask.getOpcode() == ISD::BITCAST)
15365         Mask = Mask.getOperand(0);
15366       if (X.getOpcode() == ISD::BITCAST)
15367         X = X.getOperand(0);
15368       if (Y.getOpcode() == ISD::BITCAST)
15369         Y = Y.getOperand(0);
15370
15371       EVT MaskVT = Mask.getValueType();
15372
15373       // Validate that the Mask operand is a vector sra node.
15374       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15375       // there is no psrai.b
15376       if (Mask.getOpcode() != X86ISD::VSRAI)
15377         return SDValue();
15378
15379       // Check that the SRA is all signbits.
15380       SDValue SraC = Mask.getOperand(1);
15381       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15382       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15383       if ((SraAmt + 1) != EltBits)
15384         return SDValue();
15385
15386       DebugLoc DL = N->getDebugLoc();
15387
15388       // Now we know we at least have a plendvb with the mask val.  See if
15389       // we can form a psignb/w/d.
15390       // psign = x.type == y.type == mask.type && y = sub(0, x);
15391       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15392           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15393           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15394         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15395                "Unsupported VT for PSIGN");
15396         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15397         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15398       }
15399       // PBLENDVB only available on SSE 4.1
15400       if (!Subtarget->hasSSE41())
15401         return SDValue();
15402
15403       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15404
15405       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15406       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15407       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15408       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15409       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15410     }
15411   }
15412
15413   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15414     return SDValue();
15415
15416   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15417   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15418     std::swap(N0, N1);
15419   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15420     return SDValue();
15421   if (!N0.hasOneUse() || !N1.hasOneUse())
15422     return SDValue();
15423
15424   SDValue ShAmt0 = N0.getOperand(1);
15425   if (ShAmt0.getValueType() != MVT::i8)
15426     return SDValue();
15427   SDValue ShAmt1 = N1.getOperand(1);
15428   if (ShAmt1.getValueType() != MVT::i8)
15429     return SDValue();
15430   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15431     ShAmt0 = ShAmt0.getOperand(0);
15432   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15433     ShAmt1 = ShAmt1.getOperand(0);
15434
15435   DebugLoc DL = N->getDebugLoc();
15436   unsigned Opc = X86ISD::SHLD;
15437   SDValue Op0 = N0.getOperand(0);
15438   SDValue Op1 = N1.getOperand(0);
15439   if (ShAmt0.getOpcode() == ISD::SUB) {
15440     Opc = X86ISD::SHRD;
15441     std::swap(Op0, Op1);
15442     std::swap(ShAmt0, ShAmt1);
15443   }
15444
15445   unsigned Bits = VT.getSizeInBits();
15446   if (ShAmt1.getOpcode() == ISD::SUB) {
15447     SDValue Sum = ShAmt1.getOperand(0);
15448     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15449       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15450       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15451         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15452       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15453         return DAG.getNode(Opc, DL, VT,
15454                            Op0, Op1,
15455                            DAG.getNode(ISD::TRUNCATE, DL,
15456                                        MVT::i8, ShAmt0));
15457     }
15458   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15459     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15460     if (ShAmt0C &&
15461         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15462       return DAG.getNode(Opc, DL, VT,
15463                          N0.getOperand(0), N1.getOperand(0),
15464                          DAG.getNode(ISD::TRUNCATE, DL,
15465                                        MVT::i8, ShAmt0));
15466   }
15467
15468   return SDValue();
15469 }
15470
15471 // Generate NEG and CMOV for integer abs.
15472 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15473   EVT VT = N->getValueType(0);
15474
15475   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15476   // 8-bit integer abs to NEG and CMOV.
15477   if (VT.isInteger() && VT.getSizeInBits() == 8)
15478     return SDValue();
15479
15480   SDValue N0 = N->getOperand(0);
15481   SDValue N1 = N->getOperand(1);
15482   DebugLoc DL = N->getDebugLoc();
15483
15484   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15485   // and change it to SUB and CMOV.
15486   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15487       N0.getOpcode() == ISD::ADD &&
15488       N0.getOperand(1) == N1 &&
15489       N1.getOpcode() == ISD::SRA &&
15490       N1.getOperand(0) == N0.getOperand(0))
15491     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15492       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15493         // Generate SUB & CMOV.
15494         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15495                                   DAG.getConstant(0, VT), N0.getOperand(0));
15496
15497         SDValue Ops[] = { N0.getOperand(0), Neg,
15498                           DAG.getConstant(X86::COND_GE, MVT::i8),
15499                           SDValue(Neg.getNode(), 1) };
15500         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15501                            Ops, array_lengthof(Ops));
15502       }
15503   return SDValue();
15504 }
15505
15506 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15507 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15508                                  TargetLowering::DAGCombinerInfo &DCI,
15509                                  const X86Subtarget *Subtarget) {
15510   if (DCI.isBeforeLegalizeOps())
15511     return SDValue();
15512
15513   if (Subtarget->hasCMov()) {
15514     SDValue RV = performIntegerAbsCombine(N, DAG);
15515     if (RV.getNode())
15516       return RV;
15517   }
15518
15519   // Try forming BMI if it is available.
15520   if (!Subtarget->hasBMI())
15521     return SDValue();
15522
15523   EVT VT = N->getValueType(0);
15524
15525   if (VT != MVT::i32 && VT != MVT::i64)
15526     return SDValue();
15527
15528   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15529
15530   // Create BLSMSK instructions by finding X ^ (X-1)
15531   SDValue N0 = N->getOperand(0);
15532   SDValue N1 = N->getOperand(1);
15533   DebugLoc DL = N->getDebugLoc();
15534
15535   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15536       isAllOnes(N0.getOperand(1)))
15537     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15538
15539   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15540       isAllOnes(N1.getOperand(1)))
15541     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15542
15543   return SDValue();
15544 }
15545
15546 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15547 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15548                                   TargetLowering::DAGCombinerInfo &DCI,
15549                                   const X86Subtarget *Subtarget) {
15550   LoadSDNode *Ld = cast<LoadSDNode>(N);
15551   EVT RegVT = Ld->getValueType(0);
15552   EVT MemVT = Ld->getMemoryVT();
15553   DebugLoc dl = Ld->getDebugLoc();
15554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15555
15556   ISD::LoadExtType Ext = Ld->getExtensionType();
15557
15558   // If this is a vector EXT Load then attempt to optimize it using a
15559   // shuffle. We need SSSE3 shuffles.
15560   // TODO: It is possible to support ZExt by zeroing the undef values
15561   // during the shuffle phase or after the shuffle.
15562   if (RegVT.isVector() && RegVT.isInteger() &&
15563       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15564     assert(MemVT != RegVT && "Cannot extend to the same type");
15565     assert(MemVT.isVector() && "Must load a vector from memory");
15566
15567     unsigned NumElems = RegVT.getVectorNumElements();
15568     unsigned RegSz = RegVT.getSizeInBits();
15569     unsigned MemSz = MemVT.getSizeInBits();
15570     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15571
15572     // All sizes must be a power of two.
15573     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15574       return SDValue();
15575
15576     // Attempt to load the original value using scalar loads.
15577     // Find the largest scalar type that divides the total loaded size.
15578     MVT SclrLoadTy = MVT::i8;
15579     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15580          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15581       MVT Tp = (MVT::SimpleValueType)tp;
15582       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15583         SclrLoadTy = Tp;
15584       }
15585     }
15586
15587     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15588     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15589         (64 <= MemSz))
15590       SclrLoadTy = MVT::f64;
15591
15592     // Calculate the number of scalar loads that we need to perform
15593     // in order to load our vector from memory.
15594     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15595
15596     // Represent our vector as a sequence of elements which are the
15597     // largest scalar that we can load.
15598     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15599       RegSz/SclrLoadTy.getSizeInBits());
15600
15601     // Represent the data using the same element type that is stored in
15602     // memory. In practice, we ''widen'' MemVT.
15603     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15604                                   RegSz/MemVT.getScalarType().getSizeInBits());
15605
15606     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15607       "Invalid vector type");
15608
15609     // We can't shuffle using an illegal type.
15610     if (!TLI.isTypeLegal(WideVecVT))
15611       return SDValue();
15612
15613     SmallVector<SDValue, 8> Chains;
15614     SDValue Ptr = Ld->getBasePtr();
15615     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15616                                         TLI.getPointerTy());
15617     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15618
15619     for (unsigned i = 0; i < NumLoads; ++i) {
15620       // Perform a single load.
15621       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15622                                        Ptr, Ld->getPointerInfo(),
15623                                        Ld->isVolatile(), Ld->isNonTemporal(),
15624                                        Ld->isInvariant(), Ld->getAlignment());
15625       Chains.push_back(ScalarLoad.getValue(1));
15626       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15627       // another round of DAGCombining.
15628       if (i == 0)
15629         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15630       else
15631         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15632                           ScalarLoad, DAG.getIntPtrConstant(i));
15633
15634       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15635     }
15636
15637     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15638                                Chains.size());
15639
15640     // Bitcast the loaded value to a vector of the original element type, in
15641     // the size of the target vector type.
15642     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15643     unsigned SizeRatio = RegSz/MemSz;
15644
15645     // Redistribute the loaded elements into the different locations.
15646     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15647     for (unsigned i = 0; i != NumElems; ++i)
15648       ShuffleVec[i*SizeRatio] = i;
15649
15650     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15651                                          DAG.getUNDEF(WideVecVT),
15652                                          &ShuffleVec[0]);
15653
15654     // Bitcast to the requested type.
15655     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15656     // Replace the original load with the new sequence
15657     // and return the new chain.
15658     return DCI.CombineTo(N, Shuff, TF, true);
15659   }
15660
15661   return SDValue();
15662 }
15663
15664 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15665 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15666                                    const X86Subtarget *Subtarget) {
15667   StoreSDNode *St = cast<StoreSDNode>(N);
15668   EVT VT = St->getValue().getValueType();
15669   EVT StVT = St->getMemoryVT();
15670   DebugLoc dl = St->getDebugLoc();
15671   SDValue StoredVal = St->getOperand(1);
15672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15673
15674   // If we are saving a concatenation of two XMM registers, perform two stores.
15675   // On Sandy Bridge, 256-bit memory operations are executed by two
15676   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15677   // memory  operation.
15678   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15679       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15680       StoredVal.getNumOperands() == 2) {
15681     SDValue Value0 = StoredVal.getOperand(0);
15682     SDValue Value1 = StoredVal.getOperand(1);
15683
15684     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15685     SDValue Ptr0 = St->getBasePtr();
15686     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15687
15688     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15689                                 St->getPointerInfo(), St->isVolatile(),
15690                                 St->isNonTemporal(), St->getAlignment());
15691     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15692                                 St->getPointerInfo(), St->isVolatile(),
15693                                 St->isNonTemporal(), St->getAlignment());
15694     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15695   }
15696
15697   // Optimize trunc store (of multiple scalars) to shuffle and store.
15698   // First, pack all of the elements in one place. Next, store to memory
15699   // in fewer chunks.
15700   if (St->isTruncatingStore() && VT.isVector()) {
15701     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15702     unsigned NumElems = VT.getVectorNumElements();
15703     assert(StVT != VT && "Cannot truncate to the same type");
15704     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15705     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15706
15707     // From, To sizes and ElemCount must be pow of two
15708     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15709     // We are going to use the original vector elt for storing.
15710     // Accumulated smaller vector elements must be a multiple of the store size.
15711     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15712
15713     unsigned SizeRatio  = FromSz / ToSz;
15714
15715     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15716
15717     // Create a type on which we perform the shuffle
15718     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15719             StVT.getScalarType(), NumElems*SizeRatio);
15720
15721     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15722
15723     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15724     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15725     for (unsigned i = 0; i != NumElems; ++i)
15726       ShuffleVec[i] = i * SizeRatio;
15727
15728     // Can't shuffle using an illegal type.
15729     if (!TLI.isTypeLegal(WideVecVT))
15730       return SDValue();
15731
15732     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15733                                          DAG.getUNDEF(WideVecVT),
15734                                          &ShuffleVec[0]);
15735     // At this point all of the data is stored at the bottom of the
15736     // register. We now need to save it to mem.
15737
15738     // Find the largest store unit
15739     MVT StoreType = MVT::i8;
15740     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15741          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15742       MVT Tp = (MVT::SimpleValueType)tp;
15743       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15744         StoreType = Tp;
15745     }
15746
15747     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15748     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15749         (64 <= NumElems * ToSz))
15750       StoreType = MVT::f64;
15751
15752     // Bitcast the original vector into a vector of store-size units
15753     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15754             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15755     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15756     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15757     SmallVector<SDValue, 8> Chains;
15758     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15759                                         TLI.getPointerTy());
15760     SDValue Ptr = St->getBasePtr();
15761
15762     // Perform one or more big stores into memory.
15763     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15764       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15765                                    StoreType, ShuffWide,
15766                                    DAG.getIntPtrConstant(i));
15767       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15768                                 St->getPointerInfo(), St->isVolatile(),
15769                                 St->isNonTemporal(), St->getAlignment());
15770       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15771       Chains.push_back(Ch);
15772     }
15773
15774     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15775                                Chains.size());
15776   }
15777
15778
15779   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15780   // the FP state in cases where an emms may be missing.
15781   // A preferable solution to the general problem is to figure out the right
15782   // places to insert EMMS.  This qualifies as a quick hack.
15783
15784   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15785   if (VT.getSizeInBits() != 64)
15786     return SDValue();
15787
15788   const Function *F = DAG.getMachineFunction().getFunction();
15789   bool NoImplicitFloatOps = F->getFnAttributes().
15790     hasAttribute(Attributes::NoImplicitFloat);
15791   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15792                      && Subtarget->hasSSE2();
15793   if ((VT.isVector() ||
15794        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15795       isa<LoadSDNode>(St->getValue()) &&
15796       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15797       St->getChain().hasOneUse() && !St->isVolatile()) {
15798     SDNode* LdVal = St->getValue().getNode();
15799     LoadSDNode *Ld = 0;
15800     int TokenFactorIndex = -1;
15801     SmallVector<SDValue, 8> Ops;
15802     SDNode* ChainVal = St->getChain().getNode();
15803     // Must be a store of a load.  We currently handle two cases:  the load
15804     // is a direct child, and it's under an intervening TokenFactor.  It is
15805     // possible to dig deeper under nested TokenFactors.
15806     if (ChainVal == LdVal)
15807       Ld = cast<LoadSDNode>(St->getChain());
15808     else if (St->getValue().hasOneUse() &&
15809              ChainVal->getOpcode() == ISD::TokenFactor) {
15810       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15811         if (ChainVal->getOperand(i).getNode() == LdVal) {
15812           TokenFactorIndex = i;
15813           Ld = cast<LoadSDNode>(St->getValue());
15814         } else
15815           Ops.push_back(ChainVal->getOperand(i));
15816       }
15817     }
15818
15819     if (!Ld || !ISD::isNormalLoad(Ld))
15820       return SDValue();
15821
15822     // If this is not the MMX case, i.e. we are just turning i64 load/store
15823     // into f64 load/store, avoid the transformation if there are multiple
15824     // uses of the loaded value.
15825     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15826       return SDValue();
15827
15828     DebugLoc LdDL = Ld->getDebugLoc();
15829     DebugLoc StDL = N->getDebugLoc();
15830     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15831     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15832     // pair instead.
15833     if (Subtarget->is64Bit() || F64IsLegal) {
15834       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15835       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15836                                   Ld->getPointerInfo(), Ld->isVolatile(),
15837                                   Ld->isNonTemporal(), Ld->isInvariant(),
15838                                   Ld->getAlignment());
15839       SDValue NewChain = NewLd.getValue(1);
15840       if (TokenFactorIndex != -1) {
15841         Ops.push_back(NewChain);
15842         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15843                                Ops.size());
15844       }
15845       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15846                           St->getPointerInfo(),
15847                           St->isVolatile(), St->isNonTemporal(),
15848                           St->getAlignment());
15849     }
15850
15851     // Otherwise, lower to two pairs of 32-bit loads / stores.
15852     SDValue LoAddr = Ld->getBasePtr();
15853     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15854                                  DAG.getConstant(4, MVT::i32));
15855
15856     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15857                                Ld->getPointerInfo(),
15858                                Ld->isVolatile(), Ld->isNonTemporal(),
15859                                Ld->isInvariant(), Ld->getAlignment());
15860     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15861                                Ld->getPointerInfo().getWithOffset(4),
15862                                Ld->isVolatile(), Ld->isNonTemporal(),
15863                                Ld->isInvariant(),
15864                                MinAlign(Ld->getAlignment(), 4));
15865
15866     SDValue NewChain = LoLd.getValue(1);
15867     if (TokenFactorIndex != -1) {
15868       Ops.push_back(LoLd);
15869       Ops.push_back(HiLd);
15870       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15871                              Ops.size());
15872     }
15873
15874     LoAddr = St->getBasePtr();
15875     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15876                          DAG.getConstant(4, MVT::i32));
15877
15878     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15879                                 St->getPointerInfo(),
15880                                 St->isVolatile(), St->isNonTemporal(),
15881                                 St->getAlignment());
15882     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15883                                 St->getPointerInfo().getWithOffset(4),
15884                                 St->isVolatile(),
15885                                 St->isNonTemporal(),
15886                                 MinAlign(St->getAlignment(), 4));
15887     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15888   }
15889   return SDValue();
15890 }
15891
15892 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15893 /// and return the operands for the horizontal operation in LHS and RHS.  A
15894 /// horizontal operation performs the binary operation on successive elements
15895 /// of its first operand, then on successive elements of its second operand,
15896 /// returning the resulting values in a vector.  For example, if
15897 ///   A = < float a0, float a1, float a2, float a3 >
15898 /// and
15899 ///   B = < float b0, float b1, float b2, float b3 >
15900 /// then the result of doing a horizontal operation on A and B is
15901 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15902 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15903 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15904 /// set to A, RHS to B, and the routine returns 'true'.
15905 /// Note that the binary operation should have the property that if one of the
15906 /// operands is UNDEF then the result is UNDEF.
15907 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15908   // Look for the following pattern: if
15909   //   A = < float a0, float a1, float a2, float a3 >
15910   //   B = < float b0, float b1, float b2, float b3 >
15911   // and
15912   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15913   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15914   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15915   // which is A horizontal-op B.
15916
15917   // At least one of the operands should be a vector shuffle.
15918   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15919       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15920     return false;
15921
15922   EVT VT = LHS.getValueType();
15923
15924   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15925          "Unsupported vector type for horizontal add/sub");
15926
15927   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15928   // operate independently on 128-bit lanes.
15929   unsigned NumElts = VT.getVectorNumElements();
15930   unsigned NumLanes = VT.getSizeInBits()/128;
15931   unsigned NumLaneElts = NumElts / NumLanes;
15932   assert((NumLaneElts % 2 == 0) &&
15933          "Vector type should have an even number of elements in each lane");
15934   unsigned HalfLaneElts = NumLaneElts/2;
15935
15936   // View LHS in the form
15937   //   LHS = VECTOR_SHUFFLE A, B, LMask
15938   // If LHS is not a shuffle then pretend it is the shuffle
15939   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15940   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15941   // type VT.
15942   SDValue A, B;
15943   SmallVector<int, 16> LMask(NumElts);
15944   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15945     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15946       A = LHS.getOperand(0);
15947     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15948       B = LHS.getOperand(1);
15949     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15950     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15951   } else {
15952     if (LHS.getOpcode() != ISD::UNDEF)
15953       A = LHS;
15954     for (unsigned i = 0; i != NumElts; ++i)
15955       LMask[i] = i;
15956   }
15957
15958   // Likewise, view RHS in the form
15959   //   RHS = VECTOR_SHUFFLE C, D, RMask
15960   SDValue C, D;
15961   SmallVector<int, 16> RMask(NumElts);
15962   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15963     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15964       C = RHS.getOperand(0);
15965     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15966       D = RHS.getOperand(1);
15967     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15968     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15969   } else {
15970     if (RHS.getOpcode() != ISD::UNDEF)
15971       C = RHS;
15972     for (unsigned i = 0; i != NumElts; ++i)
15973       RMask[i] = i;
15974   }
15975
15976   // Check that the shuffles are both shuffling the same vectors.
15977   if (!(A == C && B == D) && !(A == D && B == C))
15978     return false;
15979
15980   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15981   if (!A.getNode() && !B.getNode())
15982     return false;
15983
15984   // If A and B occur in reverse order in RHS, then "swap" them (which means
15985   // rewriting the mask).
15986   if (A != C)
15987     CommuteVectorShuffleMask(RMask, NumElts);
15988
15989   // At this point LHS and RHS are equivalent to
15990   //   LHS = VECTOR_SHUFFLE A, B, LMask
15991   //   RHS = VECTOR_SHUFFLE A, B, RMask
15992   // Check that the masks correspond to performing a horizontal operation.
15993   for (unsigned i = 0; i != NumElts; ++i) {
15994     int LIdx = LMask[i], RIdx = RMask[i];
15995
15996     // Ignore any UNDEF components.
15997     if (LIdx < 0 || RIdx < 0 ||
15998         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15999         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16000       continue;
16001
16002     // Check that successive elements are being operated on.  If not, this is
16003     // not a horizontal operation.
16004     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16005     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16006     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16007     if (!(LIdx == Index && RIdx == Index + 1) &&
16008         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16009       return false;
16010   }
16011
16012   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16013   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16014   return true;
16015 }
16016
16017 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16018 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16019                                   const X86Subtarget *Subtarget) {
16020   EVT VT = N->getValueType(0);
16021   SDValue LHS = N->getOperand(0);
16022   SDValue RHS = N->getOperand(1);
16023
16024   // Try to synthesize horizontal adds from adds of shuffles.
16025   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16026        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16027       isHorizontalBinOp(LHS, RHS, true))
16028     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16029   return SDValue();
16030 }
16031
16032 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16033 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16034                                   const X86Subtarget *Subtarget) {
16035   EVT VT = N->getValueType(0);
16036   SDValue LHS = N->getOperand(0);
16037   SDValue RHS = N->getOperand(1);
16038
16039   // Try to synthesize horizontal subs from subs of shuffles.
16040   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16041        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16042       isHorizontalBinOp(LHS, RHS, false))
16043     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16044   return SDValue();
16045 }
16046
16047 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16048 /// X86ISD::FXOR nodes.
16049 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16050   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16051   // F[X]OR(0.0, x) -> x
16052   // F[X]OR(x, 0.0) -> x
16053   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16054     if (C->getValueAPF().isPosZero())
16055       return N->getOperand(1);
16056   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16057     if (C->getValueAPF().isPosZero())
16058       return N->getOperand(0);
16059   return SDValue();
16060 }
16061
16062 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16063 /// X86ISD::FMAX nodes.
16064 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16065   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16066
16067   // Only perform optimizations if UnsafeMath is used.
16068   if (!DAG.getTarget().Options.UnsafeFPMath)
16069     return SDValue();
16070
16071   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16072   // into FMINC and FMAXC, which are Commutative operations.
16073   unsigned NewOp = 0;
16074   switch (N->getOpcode()) {
16075     default: llvm_unreachable("unknown opcode");
16076     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16077     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16078   }
16079
16080   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16081                      N->getOperand(0), N->getOperand(1));
16082 }
16083
16084
16085 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16086 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16087   // FAND(0.0, x) -> 0.0
16088   // FAND(x, 0.0) -> 0.0
16089   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16090     if (C->getValueAPF().isPosZero())
16091       return N->getOperand(0);
16092   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16093     if (C->getValueAPF().isPosZero())
16094       return N->getOperand(1);
16095   return SDValue();
16096 }
16097
16098 static SDValue PerformBTCombine(SDNode *N,
16099                                 SelectionDAG &DAG,
16100                                 TargetLowering::DAGCombinerInfo &DCI) {
16101   // BT ignores high bits in the bit index operand.
16102   SDValue Op1 = N->getOperand(1);
16103   if (Op1.hasOneUse()) {
16104     unsigned BitWidth = Op1.getValueSizeInBits();
16105     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16106     APInt KnownZero, KnownOne;
16107     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16108                                           !DCI.isBeforeLegalizeOps());
16109     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16110     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16111         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16112       DCI.CommitTargetLoweringOpt(TLO);
16113   }
16114   return SDValue();
16115 }
16116
16117 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16118   SDValue Op = N->getOperand(0);
16119   if (Op.getOpcode() == ISD::BITCAST)
16120     Op = Op.getOperand(0);
16121   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16122   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16123       VT.getVectorElementType().getSizeInBits() ==
16124       OpVT.getVectorElementType().getSizeInBits()) {
16125     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16126   }
16127   return SDValue();
16128 }
16129
16130 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16131                                   TargetLowering::DAGCombinerInfo &DCI,
16132                                   const X86Subtarget *Subtarget) {
16133   if (!DCI.isBeforeLegalizeOps())
16134     return SDValue();
16135
16136   if (!Subtarget->hasAVX())
16137     return SDValue();
16138
16139   EVT VT = N->getValueType(0);
16140   SDValue Op = N->getOperand(0);
16141   EVT OpVT = Op.getValueType();
16142   DebugLoc dl = N->getDebugLoc();
16143
16144   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16145       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16146
16147     if (Subtarget->hasAVX2())
16148       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16149
16150     // Optimize vectors in AVX mode
16151     // Sign extend  v8i16 to v8i32 and
16152     //              v4i32 to v4i64
16153     //
16154     // Divide input vector into two parts
16155     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16156     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16157     // concat the vectors to original VT
16158
16159     unsigned NumElems = OpVT.getVectorNumElements();
16160     SDValue Undef = DAG.getUNDEF(OpVT);
16161
16162     SmallVector<int,8> ShufMask1(NumElems, -1);
16163     for (unsigned i = 0; i != NumElems/2; ++i)
16164       ShufMask1[i] = i;
16165
16166     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16167
16168     SmallVector<int,8> ShufMask2(NumElems, -1);
16169     for (unsigned i = 0; i != NumElems/2; ++i)
16170       ShufMask2[i] = i + NumElems/2;
16171
16172     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16173
16174     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16175                                   VT.getVectorNumElements()/2);
16176
16177     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16178     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16179
16180     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16181   }
16182   return SDValue();
16183 }
16184
16185 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16186                                  const X86Subtarget* Subtarget) {
16187   DebugLoc dl = N->getDebugLoc();
16188   EVT VT = N->getValueType(0);
16189
16190   // Let legalize expand this if it isn't a legal type yet.
16191   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16192     return SDValue();
16193
16194   EVT ScalarVT = VT.getScalarType();
16195   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16196       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16197     return SDValue();
16198
16199   SDValue A = N->getOperand(0);
16200   SDValue B = N->getOperand(1);
16201   SDValue C = N->getOperand(2);
16202
16203   bool NegA = (A.getOpcode() == ISD::FNEG);
16204   bool NegB = (B.getOpcode() == ISD::FNEG);
16205   bool NegC = (C.getOpcode() == ISD::FNEG);
16206
16207   // Negative multiplication when NegA xor NegB
16208   bool NegMul = (NegA != NegB);
16209   if (NegA)
16210     A = A.getOperand(0);
16211   if (NegB)
16212     B = B.getOperand(0);
16213   if (NegC)
16214     C = C.getOperand(0);
16215
16216   unsigned Opcode;
16217   if (!NegMul)
16218     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16219   else
16220     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16221
16222   return DAG.getNode(Opcode, dl, VT, A, B, C);
16223 }
16224
16225 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16226                                   TargetLowering::DAGCombinerInfo &DCI,
16227                                   const X86Subtarget *Subtarget) {
16228   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16229   //           (and (i32 x86isd::setcc_carry), 1)
16230   // This eliminates the zext. This transformation is necessary because
16231   // ISD::SETCC is always legalized to i8.
16232   DebugLoc dl = N->getDebugLoc();
16233   SDValue N0 = N->getOperand(0);
16234   EVT VT = N->getValueType(0);
16235   EVT OpVT = N0.getValueType();
16236
16237   if (N0.getOpcode() == ISD::AND &&
16238       N0.hasOneUse() &&
16239       N0.getOperand(0).hasOneUse()) {
16240     SDValue N00 = N0.getOperand(0);
16241     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16242       return SDValue();
16243     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16244     if (!C || C->getZExtValue() != 1)
16245       return SDValue();
16246     return DAG.getNode(ISD::AND, dl, VT,
16247                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16248                                    N00.getOperand(0), N00.getOperand(1)),
16249                        DAG.getConstant(1, VT));
16250   }
16251
16252   // Optimize vectors in AVX mode:
16253   //
16254   //   v8i16 -> v8i32
16255   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16256   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16257   //   Concat upper and lower parts.
16258   //
16259   //   v4i32 -> v4i64
16260   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16261   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16262   //   Concat upper and lower parts.
16263   //
16264   if (!DCI.isBeforeLegalizeOps())
16265     return SDValue();
16266
16267   if (!Subtarget->hasAVX())
16268     return SDValue();
16269
16270   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16271       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16272
16273     if (Subtarget->hasAVX2())
16274       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16275
16276     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16277     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16278     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16279
16280     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16281                                VT.getVectorNumElements()/2);
16282
16283     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16284     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16285
16286     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16287   }
16288
16289   return SDValue();
16290 }
16291
16292 // Optimize x == -y --> x+y == 0
16293 //          x != -y --> x+y != 0
16294 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16295   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16296   SDValue LHS = N->getOperand(0);
16297   SDValue RHS = N->getOperand(1);
16298
16299   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16300     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16301       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16302         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16303                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16304         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16305                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16306       }
16307   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16308     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16309       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16310         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16311                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16312         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16313                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16314       }
16315   return SDValue();
16316 }
16317
16318 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16319 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16320                                    TargetLowering::DAGCombinerInfo &DCI,
16321                                    const X86Subtarget *Subtarget) {
16322   DebugLoc DL = N->getDebugLoc();
16323   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16324   SDValue EFLAGS = N->getOperand(1);
16325
16326   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16327   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16328   // cases.
16329   if (CC == X86::COND_B)
16330     return DAG.getNode(ISD::AND, DL, MVT::i8,
16331                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16332                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16333                        DAG.getConstant(1, MVT::i8));
16334
16335   SDValue Flags;
16336
16337   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16338   if (Flags.getNode()) {
16339     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16340     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16341   }
16342
16343   return SDValue();
16344 }
16345
16346 // Optimize branch condition evaluation.
16347 //
16348 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16349                                     TargetLowering::DAGCombinerInfo &DCI,
16350                                     const X86Subtarget *Subtarget) {
16351   DebugLoc DL = N->getDebugLoc();
16352   SDValue Chain = N->getOperand(0);
16353   SDValue Dest = N->getOperand(1);
16354   SDValue EFLAGS = N->getOperand(3);
16355   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16356
16357   SDValue Flags;
16358
16359   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16360   if (Flags.getNode()) {
16361     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16362     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16363                        Flags);
16364   }
16365
16366   return SDValue();
16367 }
16368
16369 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16370   SDValue Op0 = N->getOperand(0);
16371   EVT InVT = Op0->getValueType(0);
16372
16373   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16374   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16375     DebugLoc dl = N->getDebugLoc();
16376     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16377     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16378     // Notice that we use SINT_TO_FP because we know that the high bits
16379     // are zero and SINT_TO_FP is better supported by the hardware.
16380     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16381   }
16382
16383   return SDValue();
16384 }
16385
16386 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16387                                         const X86TargetLowering *XTLI) {
16388   SDValue Op0 = N->getOperand(0);
16389   EVT InVT = Op0->getValueType(0);
16390
16391   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16392   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16393     DebugLoc dl = N->getDebugLoc();
16394     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16395     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16396     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16397   }
16398
16399   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16400   // a 32-bit target where SSE doesn't support i64->FP operations.
16401   if (Op0.getOpcode() == ISD::LOAD) {
16402     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16403     EVT VT = Ld->getValueType(0);
16404     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16405         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16406         !XTLI->getSubtarget()->is64Bit() &&
16407         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16408       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16409                                           Ld->getChain(), Op0, DAG);
16410       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16411       return FILDChain;
16412     }
16413   }
16414   return SDValue();
16415 }
16416
16417 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16418 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16419                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16420   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16421   // the result is either zero or one (depending on the input carry bit).
16422   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16423   if (X86::isZeroNode(N->getOperand(0)) &&
16424       X86::isZeroNode(N->getOperand(1)) &&
16425       // We don't have a good way to replace an EFLAGS use, so only do this when
16426       // dead right now.
16427       SDValue(N, 1).use_empty()) {
16428     DebugLoc DL = N->getDebugLoc();
16429     EVT VT = N->getValueType(0);
16430     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16431     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16432                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16433                                            DAG.getConstant(X86::COND_B,MVT::i8),
16434                                            N->getOperand(2)),
16435                                DAG.getConstant(1, VT));
16436     return DCI.CombineTo(N, Res1, CarryOut);
16437   }
16438
16439   return SDValue();
16440 }
16441
16442 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16443 //      (add Y, (setne X, 0)) -> sbb -1, Y
16444 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16445 //      (sub (setne X, 0), Y) -> adc -1, Y
16446 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16447   DebugLoc DL = N->getDebugLoc();
16448
16449   // Look through ZExts.
16450   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16451   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16452     return SDValue();
16453
16454   SDValue SetCC = Ext.getOperand(0);
16455   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16456     return SDValue();
16457
16458   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16459   if (CC != X86::COND_E && CC != X86::COND_NE)
16460     return SDValue();
16461
16462   SDValue Cmp = SetCC.getOperand(1);
16463   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16464       !X86::isZeroNode(Cmp.getOperand(1)) ||
16465       !Cmp.getOperand(0).getValueType().isInteger())
16466     return SDValue();
16467
16468   SDValue CmpOp0 = Cmp.getOperand(0);
16469   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16470                                DAG.getConstant(1, CmpOp0.getValueType()));
16471
16472   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16473   if (CC == X86::COND_NE)
16474     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16475                        DL, OtherVal.getValueType(), OtherVal,
16476                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16477   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16478                      DL, OtherVal.getValueType(), OtherVal,
16479                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16480 }
16481
16482 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16483 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16484                                  const X86Subtarget *Subtarget) {
16485   EVT VT = N->getValueType(0);
16486   SDValue Op0 = N->getOperand(0);
16487   SDValue Op1 = N->getOperand(1);
16488
16489   // Try to synthesize horizontal adds from adds of shuffles.
16490   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16491        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16492       isHorizontalBinOp(Op0, Op1, true))
16493     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16494
16495   return OptimizeConditionalInDecrement(N, DAG);
16496 }
16497
16498 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16499                                  const X86Subtarget *Subtarget) {
16500   SDValue Op0 = N->getOperand(0);
16501   SDValue Op1 = N->getOperand(1);
16502
16503   // X86 can't encode an immediate LHS of a sub. See if we can push the
16504   // negation into a preceding instruction.
16505   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16506     // If the RHS of the sub is a XOR with one use and a constant, invert the
16507     // immediate. Then add one to the LHS of the sub so we can turn
16508     // X-Y -> X+~Y+1, saving one register.
16509     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16510         isa<ConstantSDNode>(Op1.getOperand(1))) {
16511       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16512       EVT VT = Op0.getValueType();
16513       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16514                                    Op1.getOperand(0),
16515                                    DAG.getConstant(~XorC, VT));
16516       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16517                          DAG.getConstant(C->getAPIntValue()+1, VT));
16518     }
16519   }
16520
16521   // Try to synthesize horizontal adds from adds of shuffles.
16522   EVT VT = N->getValueType(0);
16523   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16524        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16525       isHorizontalBinOp(Op0, Op1, true))
16526     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16527
16528   return OptimizeConditionalInDecrement(N, DAG);
16529 }
16530
16531 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16532                                              DAGCombinerInfo &DCI) const {
16533   SelectionDAG &DAG = DCI.DAG;
16534   switch (N->getOpcode()) {
16535   default: break;
16536   case ISD::EXTRACT_VECTOR_ELT:
16537     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16538   case ISD::VSELECT:
16539   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16540   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16541   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16542   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16543   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16544   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16545   case ISD::SHL:
16546   case ISD::SRA:
16547   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16548   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16549   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16550   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16551   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16552   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16553   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16554   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16555   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16556   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16557   case X86ISD::FXOR:
16558   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16559   case X86ISD::FMIN:
16560   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16561   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16562   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16563   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16564   case ISD::ANY_EXTEND:
16565   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16566   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16567   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16568   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16569   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16570   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16571   case X86ISD::SHUFP:       // Handle all target specific shuffles
16572   case X86ISD::PALIGN:
16573   case X86ISD::UNPCKH:
16574   case X86ISD::UNPCKL:
16575   case X86ISD::MOVHLPS:
16576   case X86ISD::MOVLHPS:
16577   case X86ISD::PSHUFD:
16578   case X86ISD::PSHUFHW:
16579   case X86ISD::PSHUFLW:
16580   case X86ISD::MOVSS:
16581   case X86ISD::MOVSD:
16582   case X86ISD::VPERMILP:
16583   case X86ISD::VPERM2X128:
16584   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16585   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16586   }
16587
16588   return SDValue();
16589 }
16590
16591 /// isTypeDesirableForOp - Return true if the target has native support for
16592 /// the specified value type and it is 'desirable' to use the type for the
16593 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16594 /// instruction encodings are longer and some i16 instructions are slow.
16595 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16596   if (!isTypeLegal(VT))
16597     return false;
16598   if (VT != MVT::i16)
16599     return true;
16600
16601   switch (Opc) {
16602   default:
16603     return true;
16604   case ISD::LOAD:
16605   case ISD::SIGN_EXTEND:
16606   case ISD::ZERO_EXTEND:
16607   case ISD::ANY_EXTEND:
16608   case ISD::SHL:
16609   case ISD::SRL:
16610   case ISD::SUB:
16611   case ISD::ADD:
16612   case ISD::MUL:
16613   case ISD::AND:
16614   case ISD::OR:
16615   case ISD::XOR:
16616     return false;
16617   }
16618 }
16619
16620 /// IsDesirableToPromoteOp - This method query the target whether it is
16621 /// beneficial for dag combiner to promote the specified node. If true, it
16622 /// should return the desired promotion type by reference.
16623 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16624   EVT VT = Op.getValueType();
16625   if (VT != MVT::i16)
16626     return false;
16627
16628   bool Promote = false;
16629   bool Commute = false;
16630   switch (Op.getOpcode()) {
16631   default: break;
16632   case ISD::LOAD: {
16633     LoadSDNode *LD = cast<LoadSDNode>(Op);
16634     // If the non-extending load has a single use and it's not live out, then it
16635     // might be folded.
16636     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16637                                                      Op.hasOneUse()*/) {
16638       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16639              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16640         // The only case where we'd want to promote LOAD (rather then it being
16641         // promoted as an operand is when it's only use is liveout.
16642         if (UI->getOpcode() != ISD::CopyToReg)
16643           return false;
16644       }
16645     }
16646     Promote = true;
16647     break;
16648   }
16649   case ISD::SIGN_EXTEND:
16650   case ISD::ZERO_EXTEND:
16651   case ISD::ANY_EXTEND:
16652     Promote = true;
16653     break;
16654   case ISD::SHL:
16655   case ISD::SRL: {
16656     SDValue N0 = Op.getOperand(0);
16657     // Look out for (store (shl (load), x)).
16658     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16659       return false;
16660     Promote = true;
16661     break;
16662   }
16663   case ISD::ADD:
16664   case ISD::MUL:
16665   case ISD::AND:
16666   case ISD::OR:
16667   case ISD::XOR:
16668     Commute = true;
16669     // fallthrough
16670   case ISD::SUB: {
16671     SDValue N0 = Op.getOperand(0);
16672     SDValue N1 = Op.getOperand(1);
16673     if (!Commute && MayFoldLoad(N1))
16674       return false;
16675     // Avoid disabling potential load folding opportunities.
16676     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16677       return false;
16678     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16679       return false;
16680     Promote = true;
16681   }
16682   }
16683
16684   PVT = MVT::i32;
16685   return Promote;
16686 }
16687
16688 //===----------------------------------------------------------------------===//
16689 //                           X86 Inline Assembly Support
16690 //===----------------------------------------------------------------------===//
16691
16692 namespace {
16693   // Helper to match a string separated by whitespace.
16694   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16695     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16696
16697     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16698       StringRef piece(*args[i]);
16699       if (!s.startswith(piece)) // Check if the piece matches.
16700         return false;
16701
16702       s = s.substr(piece.size());
16703       StringRef::size_type pos = s.find_first_not_of(" \t");
16704       if (pos == 0) // We matched a prefix.
16705         return false;
16706
16707       s = s.substr(pos);
16708     }
16709
16710     return s.empty();
16711   }
16712   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16713 }
16714
16715 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16716   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16717
16718   std::string AsmStr = IA->getAsmString();
16719
16720   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16721   if (!Ty || Ty->getBitWidth() % 16 != 0)
16722     return false;
16723
16724   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16725   SmallVector<StringRef, 4> AsmPieces;
16726   SplitString(AsmStr, AsmPieces, ";\n");
16727
16728   switch (AsmPieces.size()) {
16729   default: return false;
16730   case 1:
16731     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16732     // we will turn this bswap into something that will be lowered to logical
16733     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16734     // lower so don't worry about this.
16735     // bswap $0
16736     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16737         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16738         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16739         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16740         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16741         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16742       // No need to check constraints, nothing other than the equivalent of
16743       // "=r,0" would be valid here.
16744       return IntrinsicLowering::LowerToByteSwap(CI);
16745     }
16746
16747     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16748     if (CI->getType()->isIntegerTy(16) &&
16749         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16750         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16751          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16752       AsmPieces.clear();
16753       const std::string &ConstraintsStr = IA->getConstraintString();
16754       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16755       std::sort(AsmPieces.begin(), AsmPieces.end());
16756       if (AsmPieces.size() == 4 &&
16757           AsmPieces[0] == "~{cc}" &&
16758           AsmPieces[1] == "~{dirflag}" &&
16759           AsmPieces[2] == "~{flags}" &&
16760           AsmPieces[3] == "~{fpsr}")
16761       return IntrinsicLowering::LowerToByteSwap(CI);
16762     }
16763     break;
16764   case 3:
16765     if (CI->getType()->isIntegerTy(32) &&
16766         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16767         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16768         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16769         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16770       AsmPieces.clear();
16771       const std::string &ConstraintsStr = IA->getConstraintString();
16772       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16773       std::sort(AsmPieces.begin(), AsmPieces.end());
16774       if (AsmPieces.size() == 4 &&
16775           AsmPieces[0] == "~{cc}" &&
16776           AsmPieces[1] == "~{dirflag}" &&
16777           AsmPieces[2] == "~{flags}" &&
16778           AsmPieces[3] == "~{fpsr}")
16779         return IntrinsicLowering::LowerToByteSwap(CI);
16780     }
16781
16782     if (CI->getType()->isIntegerTy(64)) {
16783       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16784       if (Constraints.size() >= 2 &&
16785           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16786           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16787         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16788         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16789             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16790             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16791           return IntrinsicLowering::LowerToByteSwap(CI);
16792       }
16793     }
16794     break;
16795   }
16796   return false;
16797 }
16798
16799
16800
16801 /// getConstraintType - Given a constraint letter, return the type of
16802 /// constraint it is for this target.
16803 X86TargetLowering::ConstraintType
16804 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16805   if (Constraint.size() == 1) {
16806     switch (Constraint[0]) {
16807     case 'R':
16808     case 'q':
16809     case 'Q':
16810     case 'f':
16811     case 't':
16812     case 'u':
16813     case 'y':
16814     case 'x':
16815     case 'Y':
16816     case 'l':
16817       return C_RegisterClass;
16818     case 'a':
16819     case 'b':
16820     case 'c':
16821     case 'd':
16822     case 'S':
16823     case 'D':
16824     case 'A':
16825       return C_Register;
16826     case 'I':
16827     case 'J':
16828     case 'K':
16829     case 'L':
16830     case 'M':
16831     case 'N':
16832     case 'G':
16833     case 'C':
16834     case 'e':
16835     case 'Z':
16836       return C_Other;
16837     default:
16838       break;
16839     }
16840   }
16841   return TargetLowering::getConstraintType(Constraint);
16842 }
16843
16844 /// Examine constraint type and operand type and determine a weight value.
16845 /// This object must already have been set up with the operand type
16846 /// and the current alternative constraint selected.
16847 TargetLowering::ConstraintWeight
16848   X86TargetLowering::getSingleConstraintMatchWeight(
16849     AsmOperandInfo &info, const char *constraint) const {
16850   ConstraintWeight weight = CW_Invalid;
16851   Value *CallOperandVal = info.CallOperandVal;
16852     // If we don't have a value, we can't do a match,
16853     // but allow it at the lowest weight.
16854   if (CallOperandVal == NULL)
16855     return CW_Default;
16856   Type *type = CallOperandVal->getType();
16857   // Look at the constraint type.
16858   switch (*constraint) {
16859   default:
16860     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16861   case 'R':
16862   case 'q':
16863   case 'Q':
16864   case 'a':
16865   case 'b':
16866   case 'c':
16867   case 'd':
16868   case 'S':
16869   case 'D':
16870   case 'A':
16871     if (CallOperandVal->getType()->isIntegerTy())
16872       weight = CW_SpecificReg;
16873     break;
16874   case 'f':
16875   case 't':
16876   case 'u':
16877       if (type->isFloatingPointTy())
16878         weight = CW_SpecificReg;
16879       break;
16880   case 'y':
16881       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16882         weight = CW_SpecificReg;
16883       break;
16884   case 'x':
16885   case 'Y':
16886     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16887         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16888       weight = CW_Register;
16889     break;
16890   case 'I':
16891     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16892       if (C->getZExtValue() <= 31)
16893         weight = CW_Constant;
16894     }
16895     break;
16896   case 'J':
16897     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16898       if (C->getZExtValue() <= 63)
16899         weight = CW_Constant;
16900     }
16901     break;
16902   case 'K':
16903     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16904       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16905         weight = CW_Constant;
16906     }
16907     break;
16908   case 'L':
16909     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16910       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16911         weight = CW_Constant;
16912     }
16913     break;
16914   case 'M':
16915     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16916       if (C->getZExtValue() <= 3)
16917         weight = CW_Constant;
16918     }
16919     break;
16920   case 'N':
16921     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16922       if (C->getZExtValue() <= 0xff)
16923         weight = CW_Constant;
16924     }
16925     break;
16926   case 'G':
16927   case 'C':
16928     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16929       weight = CW_Constant;
16930     }
16931     break;
16932   case 'e':
16933     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16934       if ((C->getSExtValue() >= -0x80000000LL) &&
16935           (C->getSExtValue() <= 0x7fffffffLL))
16936         weight = CW_Constant;
16937     }
16938     break;
16939   case 'Z':
16940     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16941       if (C->getZExtValue() <= 0xffffffff)
16942         weight = CW_Constant;
16943     }
16944     break;
16945   }
16946   return weight;
16947 }
16948
16949 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16950 /// with another that has more specific requirements based on the type of the
16951 /// corresponding operand.
16952 const char *X86TargetLowering::
16953 LowerXConstraint(EVT ConstraintVT) const {
16954   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16955   // 'f' like normal targets.
16956   if (ConstraintVT.isFloatingPoint()) {
16957     if (Subtarget->hasSSE2())
16958       return "Y";
16959     if (Subtarget->hasSSE1())
16960       return "x";
16961   }
16962
16963   return TargetLowering::LowerXConstraint(ConstraintVT);
16964 }
16965
16966 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16967 /// vector.  If it is invalid, don't add anything to Ops.
16968 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16969                                                      std::string &Constraint,
16970                                                      std::vector<SDValue>&Ops,
16971                                                      SelectionDAG &DAG) const {
16972   SDValue Result(0, 0);
16973
16974   // Only support length 1 constraints for now.
16975   if (Constraint.length() > 1) return;
16976
16977   char ConstraintLetter = Constraint[0];
16978   switch (ConstraintLetter) {
16979   default: break;
16980   case 'I':
16981     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16982       if (C->getZExtValue() <= 31) {
16983         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16984         break;
16985       }
16986     }
16987     return;
16988   case 'J':
16989     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16990       if (C->getZExtValue() <= 63) {
16991         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16992         break;
16993       }
16994     }
16995     return;
16996   case 'K':
16997     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16998       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16999         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17000         break;
17001       }
17002     }
17003     return;
17004   case 'N':
17005     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17006       if (C->getZExtValue() <= 255) {
17007         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17008         break;
17009       }
17010     }
17011     return;
17012   case 'e': {
17013     // 32-bit signed value
17014     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17015       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17016                                            C->getSExtValue())) {
17017         // Widen to 64 bits here to get it sign extended.
17018         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17019         break;
17020       }
17021     // FIXME gcc accepts some relocatable values here too, but only in certain
17022     // memory models; it's complicated.
17023     }
17024     return;
17025   }
17026   case 'Z': {
17027     // 32-bit unsigned value
17028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17029       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17030                                            C->getZExtValue())) {
17031         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17032         break;
17033       }
17034     }
17035     // FIXME gcc accepts some relocatable values here too, but only in certain
17036     // memory models; it's complicated.
17037     return;
17038   }
17039   case 'i': {
17040     // Literal immediates are always ok.
17041     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17042       // Widen to 64 bits here to get it sign extended.
17043       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17044       break;
17045     }
17046
17047     // In any sort of PIC mode addresses need to be computed at runtime by
17048     // adding in a register or some sort of table lookup.  These can't
17049     // be used as immediates.
17050     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17051       return;
17052
17053     // If we are in non-pic codegen mode, we allow the address of a global (with
17054     // an optional displacement) to be used with 'i'.
17055     GlobalAddressSDNode *GA = 0;
17056     int64_t Offset = 0;
17057
17058     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17059     while (1) {
17060       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17061         Offset += GA->getOffset();
17062         break;
17063       } else if (Op.getOpcode() == ISD::ADD) {
17064         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17065           Offset += C->getZExtValue();
17066           Op = Op.getOperand(0);
17067           continue;
17068         }
17069       } else if (Op.getOpcode() == ISD::SUB) {
17070         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17071           Offset += -C->getZExtValue();
17072           Op = Op.getOperand(0);
17073           continue;
17074         }
17075       }
17076
17077       // Otherwise, this isn't something we can handle, reject it.
17078       return;
17079     }
17080
17081     const GlobalValue *GV = GA->getGlobal();
17082     // If we require an extra load to get this address, as in PIC mode, we
17083     // can't accept it.
17084     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17085                                                         getTargetMachine())))
17086       return;
17087
17088     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17089                                         GA->getValueType(0), Offset);
17090     break;
17091   }
17092   }
17093
17094   if (Result.getNode()) {
17095     Ops.push_back(Result);
17096     return;
17097   }
17098   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17099 }
17100
17101 std::pair<unsigned, const TargetRegisterClass*>
17102 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17103                                                 EVT VT) const {
17104   // First, see if this is a constraint that directly corresponds to an LLVM
17105   // register class.
17106   if (Constraint.size() == 1) {
17107     // GCC Constraint Letters
17108     switch (Constraint[0]) {
17109     default: break;
17110       // TODO: Slight differences here in allocation order and leaving
17111       // RIP in the class. Do they matter any more here than they do
17112       // in the normal allocation?
17113     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17114       if (Subtarget->is64Bit()) {
17115         if (VT == MVT::i32 || VT == MVT::f32)
17116           return std::make_pair(0U, &X86::GR32RegClass);
17117         if (VT == MVT::i16)
17118           return std::make_pair(0U, &X86::GR16RegClass);
17119         if (VT == MVT::i8 || VT == MVT::i1)
17120           return std::make_pair(0U, &X86::GR8RegClass);
17121         if (VT == MVT::i64 || VT == MVT::f64)
17122           return std::make_pair(0U, &X86::GR64RegClass);
17123         break;
17124       }
17125       // 32-bit fallthrough
17126     case 'Q':   // Q_REGS
17127       if (VT == MVT::i32 || VT == MVT::f32)
17128         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17129       if (VT == MVT::i16)
17130         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17131       if (VT == MVT::i8 || VT == MVT::i1)
17132         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17133       if (VT == MVT::i64)
17134         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17135       break;
17136     case 'r':   // GENERAL_REGS
17137     case 'l':   // INDEX_REGS
17138       if (VT == MVT::i8 || VT == MVT::i1)
17139         return std::make_pair(0U, &X86::GR8RegClass);
17140       if (VT == MVT::i16)
17141         return std::make_pair(0U, &X86::GR16RegClass);
17142       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17143         return std::make_pair(0U, &X86::GR32RegClass);
17144       return std::make_pair(0U, &X86::GR64RegClass);
17145     case 'R':   // LEGACY_REGS
17146       if (VT == MVT::i8 || VT == MVT::i1)
17147         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17148       if (VT == MVT::i16)
17149         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17150       if (VT == MVT::i32 || !Subtarget->is64Bit())
17151         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17152       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17153     case 'f':  // FP Stack registers.
17154       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17155       // value to the correct fpstack register class.
17156       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17157         return std::make_pair(0U, &X86::RFP32RegClass);
17158       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17159         return std::make_pair(0U, &X86::RFP64RegClass);
17160       return std::make_pair(0U, &X86::RFP80RegClass);
17161     case 'y':   // MMX_REGS if MMX allowed.
17162       if (!Subtarget->hasMMX()) break;
17163       return std::make_pair(0U, &X86::VR64RegClass);
17164     case 'Y':   // SSE_REGS if SSE2 allowed
17165       if (!Subtarget->hasSSE2()) break;
17166       // FALL THROUGH.
17167     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17168       if (!Subtarget->hasSSE1()) break;
17169
17170       switch (VT.getSimpleVT().SimpleTy) {
17171       default: break;
17172       // Scalar SSE types.
17173       case MVT::f32:
17174       case MVT::i32:
17175         return std::make_pair(0U, &X86::FR32RegClass);
17176       case MVT::f64:
17177       case MVT::i64:
17178         return std::make_pair(0U, &X86::FR64RegClass);
17179       // Vector types.
17180       case MVT::v16i8:
17181       case MVT::v8i16:
17182       case MVT::v4i32:
17183       case MVT::v2i64:
17184       case MVT::v4f32:
17185       case MVT::v2f64:
17186         return std::make_pair(0U, &X86::VR128RegClass);
17187       // AVX types.
17188       case MVT::v32i8:
17189       case MVT::v16i16:
17190       case MVT::v8i32:
17191       case MVT::v4i64:
17192       case MVT::v8f32:
17193       case MVT::v4f64:
17194         return std::make_pair(0U, &X86::VR256RegClass);
17195       }
17196       break;
17197     }
17198   }
17199
17200   // Use the default implementation in TargetLowering to convert the register
17201   // constraint into a member of a register class.
17202   std::pair<unsigned, const TargetRegisterClass*> Res;
17203   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17204
17205   // Not found as a standard register?
17206   if (Res.second == 0) {
17207     // Map st(0) -> st(7) -> ST0
17208     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17209         tolower(Constraint[1]) == 's' &&
17210         tolower(Constraint[2]) == 't' &&
17211         Constraint[3] == '(' &&
17212         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17213         Constraint[5] == ')' &&
17214         Constraint[6] == '}') {
17215
17216       Res.first = X86::ST0+Constraint[4]-'0';
17217       Res.second = &X86::RFP80RegClass;
17218       return Res;
17219     }
17220
17221     // GCC allows "st(0)" to be called just plain "st".
17222     if (StringRef("{st}").equals_lower(Constraint)) {
17223       Res.first = X86::ST0;
17224       Res.second = &X86::RFP80RegClass;
17225       return Res;
17226     }
17227
17228     // flags -> EFLAGS
17229     if (StringRef("{flags}").equals_lower(Constraint)) {
17230       Res.first = X86::EFLAGS;
17231       Res.second = &X86::CCRRegClass;
17232       return Res;
17233     }
17234
17235     // 'A' means EAX + EDX.
17236     if (Constraint == "A") {
17237       Res.first = X86::EAX;
17238       Res.second = &X86::GR32_ADRegClass;
17239       return Res;
17240     }
17241     return Res;
17242   }
17243
17244   // Otherwise, check to see if this is a register class of the wrong value
17245   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17246   // turn into {ax},{dx}.
17247   if (Res.second->hasType(VT))
17248     return Res;   // Correct type already, nothing to do.
17249
17250   // All of the single-register GCC register classes map their values onto
17251   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17252   // really want an 8-bit or 32-bit register, map to the appropriate register
17253   // class and return the appropriate register.
17254   if (Res.second == &X86::GR16RegClass) {
17255     if (VT == MVT::i8) {
17256       unsigned DestReg = 0;
17257       switch (Res.first) {
17258       default: break;
17259       case X86::AX: DestReg = X86::AL; break;
17260       case X86::DX: DestReg = X86::DL; break;
17261       case X86::CX: DestReg = X86::CL; break;
17262       case X86::BX: DestReg = X86::BL; break;
17263       }
17264       if (DestReg) {
17265         Res.first = DestReg;
17266         Res.second = &X86::GR8RegClass;
17267       }
17268     } else if (VT == MVT::i32) {
17269       unsigned DestReg = 0;
17270       switch (Res.first) {
17271       default: break;
17272       case X86::AX: DestReg = X86::EAX; break;
17273       case X86::DX: DestReg = X86::EDX; break;
17274       case X86::CX: DestReg = X86::ECX; break;
17275       case X86::BX: DestReg = X86::EBX; break;
17276       case X86::SI: DestReg = X86::ESI; break;
17277       case X86::DI: DestReg = X86::EDI; break;
17278       case X86::BP: DestReg = X86::EBP; break;
17279       case X86::SP: DestReg = X86::ESP; break;
17280       }
17281       if (DestReg) {
17282         Res.first = DestReg;
17283         Res.second = &X86::GR32RegClass;
17284       }
17285     } else if (VT == MVT::i64) {
17286       unsigned DestReg = 0;
17287       switch (Res.first) {
17288       default: break;
17289       case X86::AX: DestReg = X86::RAX; break;
17290       case X86::DX: DestReg = X86::RDX; break;
17291       case X86::CX: DestReg = X86::RCX; break;
17292       case X86::BX: DestReg = X86::RBX; break;
17293       case X86::SI: DestReg = X86::RSI; break;
17294       case X86::DI: DestReg = X86::RDI; break;
17295       case X86::BP: DestReg = X86::RBP; break;
17296       case X86::SP: DestReg = X86::RSP; break;
17297       }
17298       if (DestReg) {
17299         Res.first = DestReg;
17300         Res.second = &X86::GR64RegClass;
17301       }
17302     }
17303   } else if (Res.second == &X86::FR32RegClass ||
17304              Res.second == &X86::FR64RegClass ||
17305              Res.second == &X86::VR128RegClass) {
17306     // Handle references to XMM physical registers that got mapped into the
17307     // wrong class.  This can happen with constraints like {xmm0} where the
17308     // target independent register mapper will just pick the first match it can
17309     // find, ignoring the required type.
17310
17311     if (VT == MVT::f32 || VT == MVT::i32)
17312       Res.second = &X86::FR32RegClass;
17313     else if (VT == MVT::f64 || VT == MVT::i64)
17314       Res.second = &X86::FR64RegClass;
17315     else if (X86::VR128RegClass.hasType(VT))
17316       Res.second = &X86::VR128RegClass;
17317     else if (X86::VR256RegClass.hasType(VT))
17318       Res.second = &X86::VR256RegClass;
17319   }
17320
17321   return Res;
17322 }