This patch is to fix radar://8426430. It is about llvm support of __builtin_debugtrap()
[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   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561
562   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
564   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
565   if (Subtarget->is64Bit()) {
566     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
567     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
568   } else {
569     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
570     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
571   }
572
573   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
574   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
575
576   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578                        MVT::i64 : MVT::i32, Custom);
579   else if (TM.Options.EnableSegmentedStacks)
580     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581                        MVT::i64 : MVT::i32, Custom);
582   else
583     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584                        MVT::i64 : MVT::i32, Expand);
585
586   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587     // f32 and f64 use SSE.
588     // Set up the FP register classes.
589     addRegisterClass(MVT::f32, &X86::FR32RegClass);
590     addRegisterClass(MVT::f64, &X86::FR64RegClass);
591
592     // Use ANDPD to simulate FABS.
593     setOperationAction(ISD::FABS , MVT::f64, Custom);
594     setOperationAction(ISD::FABS , MVT::f32, Custom);
595
596     // Use XORP to simulate FNEG.
597     setOperationAction(ISD::FNEG , MVT::f64, Custom);
598     setOperationAction(ISD::FNEG , MVT::f32, Custom);
599
600     // Use ANDPD and ORPD to simulate FCOPYSIGN.
601     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603
604     // Lower this to FGETSIGNx86 plus an AND.
605     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607
608     // We don't support sin/cos/fmod
609     setOperationAction(ISD::FSIN , MVT::f64, Expand);
610     setOperationAction(ISD::FCOS , MVT::f64, Expand);
611     setOperationAction(ISD::FSIN , MVT::f32, Expand);
612     setOperationAction(ISD::FCOS , MVT::f32, Expand);
613
614     // Expand FP immediates into loads from the stack, except for the special
615     // cases we handle.
616     addLegalFPImmediate(APFloat(+0.0)); // xorpd
617     addLegalFPImmediate(APFloat(+0.0f)); // xorps
618   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619     // Use SSE for f32, x87 for f64.
620     // Set up the FP register classes.
621     addRegisterClass(MVT::f32, &X86::FR32RegClass);
622     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623
624     // Use ANDPS to simulate FABS.
625     setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627     // Use XORP to simulate FNEG.
628     setOperationAction(ISD::FNEG , MVT::f32, Custom);
629
630     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
631
632     // Use ANDPS and ORPS to simulate FCOPYSIGN.
633     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635
636     // We don't support sin/cos/fmod
637     setOperationAction(ISD::FSIN , MVT::f32, Expand);
638     setOperationAction(ISD::FCOS , MVT::f32, Expand);
639
640     // Special cases we handle for FP constants.
641     addLegalFPImmediate(APFloat(+0.0f)); // xorps
642     addLegalFPImmediate(APFloat(+0.0)); // FLD0
643     addLegalFPImmediate(APFloat(+1.0)); // FLD1
644     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646
647     if (!TM.Options.UnsafeFPMath) {
648       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
649       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
650     }
651   } else if (!TM.Options.UseSoftFloat) {
652     // f32 and f64 in x87.
653     // Set up the FP register classes.
654     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656
657     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
658     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661
662     if (!TM.Options.UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f32  , Expand);
664       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
665       setOperationAction(ISD::FCOS           , MVT::f32  , Expand);
666       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
667     }
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
676   }
677
678   // We don't support FMA.
679   setOperationAction(ISD::FMA, MVT::f64, Expand);
680   setOperationAction(ISD::FMA, MVT::f32, Expand);
681
682   // Long double always uses X87.
683   if (!TM.Options.UseSoftFloat) {
684     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687     {
688       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689       addLegalFPImmediate(TmpFlt);  // FLD0
690       TmpFlt.changeSign();
691       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
692
693       bool ignored;
694       APFloat TmpFlt2(+1.0);
695       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696                       &ignored);
697       addLegalFPImmediate(TmpFlt2);  // FLD1
698       TmpFlt2.changeSign();
699       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
700     }
701
702     if (!TM.Options.UnsafeFPMath) {
703       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
704       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
705     }
706
707     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
709     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
711     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712     setOperationAction(ISD::FMA, MVT::f80, Expand);
713   }
714
715   // Always use a library call for pow.
716   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
717   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
718   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
719
720   setOperationAction(ISD::FLOG, MVT::f80, Expand);
721   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723   setOperationAction(ISD::FEXP, MVT::f80, Expand);
724   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725
726   // First set operation action for all vector types to either promote
727   // (for widening) or expand (for scalarization). Then we will selectively
728   // turn on ones that can be effectively codegen'd.
729   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
786     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
787     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
788     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
789     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
790     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792       setTruncStoreAction((MVT::SimpleValueType)VT,
793                           (MVT::SimpleValueType)InnerVT, Expand);
794     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
797   }
798
799   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800   // with -msoft-float, disable use of MMX as well.
801   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803     // No operations on x86mmx supported, everything uses intrinsics.
804   }
805
806   // MMX-sized vectors (other than x86mmx) are expected to be expanded
807   // into smaller operations.
808   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
809   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
810   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
811   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
812   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
813   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
814   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
815   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
816   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
817   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
818   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
819   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
820   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
821   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
822   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
823   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
824   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
825   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
826   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
827   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
828   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
829   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
830   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
831   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
832   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
833   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
834   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
835   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
836   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
837
838   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
840
841     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
842     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
843     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
844     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
845     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
846     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
847     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
848     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
849     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
850     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
851     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
853   }
854
855   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
857
858     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859     // registers cannot be used even for integer operations.
860     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
864
865     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
866     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
867     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
868     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
869     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
870     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
871     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
872     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
873     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
874     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
875     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
876     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
877     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
878     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
879     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
880     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
881     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
882
883     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
884     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
885     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
886     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
887
888     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
889     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
891     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
892     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
893
894     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897       // Do not attempt to custom lower non-power-of-2 vectors
898       if (!isPowerOf2_32(VT.getVectorNumElements()))
899         continue;
900       // Do not attempt to custom lower non-128-bit vectors
901       if (!VT.is128BitVector())
902         continue;
903       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
904       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
906     }
907
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
909     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
911     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
913     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
914
915     if (Subtarget->is64Bit()) {
916       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
917       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
918     }
919
920     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922       MVT VT = (MVT::SimpleValueType)i;
923
924       // Do not attempt to promote non-128-bit vectors
925       if (!VT.is128BitVector())
926         continue;
927
928       setOperationAction(ISD::AND,    VT, Promote);
929       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
930       setOperationAction(ISD::OR,     VT, Promote);
931       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
932       setOperationAction(ISD::XOR,    VT, Promote);
933       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
934       setOperationAction(ISD::LOAD,   VT, Promote);
935       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
936       setOperationAction(ISD::SELECT, VT, Promote);
937       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
938     }
939
940     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
941
942     // Custom lower v2i64 and v2f64 selects.
943     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
944     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
945     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
946     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
947
948     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
949     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
950
951     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
952     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
953
954     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
955   }
956
957   if (Subtarget->hasSSE41()) {
958     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
959     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
960     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
961     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
962     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
963     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
964     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
965     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
966     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
967     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
968
969     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
970     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
971
972     // FIXME: Do we need to handle scalar-to-vector here?
973     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
974
975     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
976     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
977     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
978     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
979     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
980
981     // i8 and i16 vectors are custom , because the source register and source
982     // source memory operand types are not the same width.  f32 vectors are
983     // custom since the immediate controlling the insert encodes additional
984     // information.
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
986     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
987     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
989
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
992     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
993     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
994
995     // FIXME: these should be Legal but thats only for the case where
996     // the index is constant.  For now custom expand to deal with that.
997     if (Subtarget->is64Bit()) {
998       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
999       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1000     }
1001   }
1002
1003   if (Subtarget->hasSSE2()) {
1004     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1005     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1006
1007     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1008     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1009
1010     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1011     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1012
1013     if (Subtarget->hasAVX2()) {
1014       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1015       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1016
1017       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1018       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1019
1020       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1021     } else {
1022       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1023       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1024
1025       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1026       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1027
1028       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1029     }
1030   }
1031
1032   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1033     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1034     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1035     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1036     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1038     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1039
1040     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1041     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1042     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1043
1044     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1045     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1046     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1049     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1050     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1051     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1052
1053     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1054     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1055     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1056     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1057     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1059     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1060     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1061
1062     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1063
1064     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1065
1066     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1067     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1068     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1069
1070     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1071
1072     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1073     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1074
1075     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1076     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1077
1078     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1079     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1080
1081     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1082     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1083     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1084     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1085
1086     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1087     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1088     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1089
1090     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1091     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1092     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1093     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1094
1095     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1096       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1097       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1098       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1099       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1100       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1101       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1102     }
1103
1104     if (Subtarget->hasAVX2()) {
1105       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1106       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1107       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1108       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1109
1110       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1111       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1112       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1113       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1114
1115       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1116       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1117       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1118       // Don't lower v32i8 because there is no 128-bit byte mul
1119
1120       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1121
1122       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1123       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1124
1125       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1126       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1127
1128       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1129     } else {
1130       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1131       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1132       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1133       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1134
1135       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1136       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1137       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1138       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1139
1140       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1141       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1142       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1143       // Don't lower v32i8 because there is no 128-bit byte mul
1144
1145       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1146       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1147
1148       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1149       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1150
1151       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1152     }
1153
1154     // Custom lower several nodes for 256-bit types.
1155     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1156              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1157       MVT VT = (MVT::SimpleValueType)i;
1158
1159       // Extract subvector is special because the value type
1160       // (result) is 128-bit but the source is 256-bit wide.
1161       if (VT.is128BitVector())
1162         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1163
1164       // Do not attempt to custom lower other non-256-bit vectors
1165       if (!VT.is256BitVector())
1166         continue;
1167
1168       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1169       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1170       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1171       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1172       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1173       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1174       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1175     }
1176
1177     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1178     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1179       MVT VT = (MVT::SimpleValueType)i;
1180
1181       // Do not attempt to promote non-256-bit vectors
1182       if (!VT.is256BitVector())
1183         continue;
1184
1185       setOperationAction(ISD::AND,    VT, Promote);
1186       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1187       setOperationAction(ISD::OR,     VT, Promote);
1188       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1189       setOperationAction(ISD::XOR,    VT, Promote);
1190       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1191       setOperationAction(ISD::LOAD,   VT, Promote);
1192       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1193       setOperationAction(ISD::SELECT, VT, Promote);
1194       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1195     }
1196   }
1197
1198   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1199   // of this type with custom code.
1200   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1201            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1202     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1203                        Custom);
1204   }
1205
1206   // We want to custom lower some of our intrinsics.
1207   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1208   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1209
1210
1211   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1212   // handle type legalization for these operations here.
1213   //
1214   // FIXME: We really should do custom legalization for addition and
1215   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1216   // than generic legalization for 64-bit multiplication-with-overflow, though.
1217   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1218     // Add/Sub/Mul with overflow operations are custom lowered.
1219     MVT VT = IntVTs[i];
1220     setOperationAction(ISD::SADDO, VT, Custom);
1221     setOperationAction(ISD::UADDO, VT, Custom);
1222     setOperationAction(ISD::SSUBO, VT, Custom);
1223     setOperationAction(ISD::USUBO, VT, Custom);
1224     setOperationAction(ISD::SMULO, VT, Custom);
1225     setOperationAction(ISD::UMULO, VT, Custom);
1226   }
1227
1228   // There are no 8-bit 3-address imul/mul instructions
1229   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1230   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1231
1232   if (!Subtarget->is64Bit()) {
1233     // These libcalls are not available in 32-bit.
1234     setLibcallName(RTLIB::SHL_I128, 0);
1235     setLibcallName(RTLIB::SRL_I128, 0);
1236     setLibcallName(RTLIB::SRA_I128, 0);
1237   }
1238
1239   // We have target-specific dag combine patterns for the following nodes:
1240   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1241   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1242   setTargetDAGCombine(ISD::VSELECT);
1243   setTargetDAGCombine(ISD::SELECT);
1244   setTargetDAGCombine(ISD::SHL);
1245   setTargetDAGCombine(ISD::SRA);
1246   setTargetDAGCombine(ISD::SRL);
1247   setTargetDAGCombine(ISD::OR);
1248   setTargetDAGCombine(ISD::AND);
1249   setTargetDAGCombine(ISD::ADD);
1250   setTargetDAGCombine(ISD::FADD);
1251   setTargetDAGCombine(ISD::FSUB);
1252   setTargetDAGCombine(ISD::FMA);
1253   setTargetDAGCombine(ISD::SUB);
1254   setTargetDAGCombine(ISD::LOAD);
1255   setTargetDAGCombine(ISD::STORE);
1256   setTargetDAGCombine(ISD::ZERO_EXTEND);
1257   setTargetDAGCombine(ISD::ANY_EXTEND);
1258   setTargetDAGCombine(ISD::SIGN_EXTEND);
1259   setTargetDAGCombine(ISD::TRUNCATE);
1260   setTargetDAGCombine(ISD::UINT_TO_FP);
1261   setTargetDAGCombine(ISD::SINT_TO_FP);
1262   setTargetDAGCombine(ISD::SETCC);
1263   if (Subtarget->is64Bit())
1264     setTargetDAGCombine(ISD::MUL);
1265   setTargetDAGCombine(ISD::XOR);
1266
1267   computeRegisterProperties();
1268
1269   // On Darwin, -Os means optimize for size without hurting performance,
1270   // do not reduce the limit.
1271   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1272   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1273   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1274   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1275   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1276   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1277   setPrefLoopAlignment(4); // 2^4 bytes.
1278   benefitFromCodePlacementOpt = true;
1279
1280   // Predictable cmov don't hurt on atom because it's in-order.
1281   predictableSelectIsExpensive = !Subtarget->isAtom();
1282
1283   setPrefFunctionAlignment(4); // 2^4 bytes.
1284 }
1285
1286
1287 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1288   if (!VT.isVector()) return MVT::i8;
1289   return VT.changeVectorElementTypeToInteger();
1290 }
1291
1292
1293 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1294 /// the desired ByVal argument alignment.
1295 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1296   if (MaxAlign == 16)
1297     return;
1298   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1299     if (VTy->getBitWidth() == 128)
1300       MaxAlign = 16;
1301   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1302     unsigned EltAlign = 0;
1303     getMaxByValAlign(ATy->getElementType(), EltAlign);
1304     if (EltAlign > MaxAlign)
1305       MaxAlign = EltAlign;
1306   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1307     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1308       unsigned EltAlign = 0;
1309       getMaxByValAlign(STy->getElementType(i), EltAlign);
1310       if (EltAlign > MaxAlign)
1311         MaxAlign = EltAlign;
1312       if (MaxAlign == 16)
1313         break;
1314     }
1315   }
1316 }
1317
1318 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1319 /// function arguments in the caller parameter area. For X86, aggregates
1320 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1321 /// are at 4-byte boundaries.
1322 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1323   if (Subtarget->is64Bit()) {
1324     // Max of 8 and alignment of type.
1325     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1326     if (TyAlign > 8)
1327       return TyAlign;
1328     return 8;
1329   }
1330
1331   unsigned Align = 4;
1332   if (Subtarget->hasSSE1())
1333     getMaxByValAlign(Ty, Align);
1334   return Align;
1335 }
1336
1337 /// getOptimalMemOpType - Returns the target specific optimal type for load
1338 /// and store operations as a result of memset, memcpy, and memmove
1339 /// lowering. If DstAlign is zero that means it's safe to destination
1340 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1341 /// means there isn't a need to check it against alignment requirement,
1342 /// probably because the source does not need to be loaded. If
1343 /// 'IsZeroVal' is true, that means it's safe to return a
1344 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1345 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1346 /// constant so it does not need to be loaded.
1347 /// It returns EVT::Other if the type should be determined using generic
1348 /// target-independent logic.
1349 EVT
1350 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1351                                        unsigned DstAlign, unsigned SrcAlign,
1352                                        bool IsZeroVal,
1353                                        bool MemcpyStrSrc,
1354                                        MachineFunction &MF) const {
1355   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1356   // linux.  This is because the stack realignment code can't handle certain
1357   // cases like PR2962.  This should be removed when PR2962 is fixed.
1358   const Function *F = MF.getFunction();
1359   if (IsZeroVal &&
1360       !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1361     if (Size >= 16 &&
1362         (Subtarget->isUnalignedMemAccessFast() ||
1363          ((DstAlign == 0 || DstAlign >= 16) &&
1364           (SrcAlign == 0 || SrcAlign >= 16))) &&
1365         Subtarget->getStackAlignment() >= 16) {
1366       if (Subtarget->getStackAlignment() >= 32) {
1367         if (Subtarget->hasAVX2())
1368           return MVT::v8i32;
1369         if (Subtarget->hasAVX())
1370           return MVT::v8f32;
1371       }
1372       if (Subtarget->hasSSE2())
1373         return MVT::v4i32;
1374       if (Subtarget->hasSSE1())
1375         return MVT::v4f32;
1376     } else if (!MemcpyStrSrc && Size >= 8 &&
1377                !Subtarget->is64Bit() &&
1378                Subtarget->getStackAlignment() >= 8 &&
1379                Subtarget->hasSSE2()) {
1380       // Do not use f64 to lower memcpy if source is string constant. It's
1381       // better to use i32 to avoid the loads.
1382       return MVT::f64;
1383     }
1384   }
1385   if (Subtarget->is64Bit() && Size >= 8)
1386     return MVT::i64;
1387   return MVT::i32;
1388 }
1389
1390 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1391 /// current function.  The returned value is a member of the
1392 /// MachineJumpTableInfo::JTEntryKind enum.
1393 unsigned X86TargetLowering::getJumpTableEncoding() const {
1394   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1395   // symbol.
1396   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1397       Subtarget->isPICStyleGOT())
1398     return MachineJumpTableInfo::EK_Custom32;
1399
1400   // Otherwise, use the normal jump table encoding heuristics.
1401   return TargetLowering::getJumpTableEncoding();
1402 }
1403
1404 const MCExpr *
1405 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1406                                              const MachineBasicBlock *MBB,
1407                                              unsigned uid,MCContext &Ctx) const{
1408   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1409          Subtarget->isPICStyleGOT());
1410   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1411   // entries.
1412   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1413                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1414 }
1415
1416 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1417 /// jumptable.
1418 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1419                                                     SelectionDAG &DAG) const {
1420   if (!Subtarget->is64Bit())
1421     // This doesn't have DebugLoc associated with it, but is not really the
1422     // same as a Register.
1423     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1424   return Table;
1425 }
1426
1427 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1428 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1429 /// MCExpr.
1430 const MCExpr *X86TargetLowering::
1431 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1432                              MCContext &Ctx) const {
1433   // X86-64 uses RIP relative addressing based on the jump table label.
1434   if (Subtarget->isPICStyleRIPRel())
1435     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1436
1437   // Otherwise, the reference is relative to the PIC base.
1438   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1439 }
1440
1441 // FIXME: Why this routine is here? Move to RegInfo!
1442 std::pair<const TargetRegisterClass*, uint8_t>
1443 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1444   const TargetRegisterClass *RRC = 0;
1445   uint8_t Cost = 1;
1446   switch (VT.getSimpleVT().SimpleTy) {
1447   default:
1448     return TargetLowering::findRepresentativeClass(VT);
1449   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1450     RRC = Subtarget->is64Bit() ?
1451       (const TargetRegisterClass*)&X86::GR64RegClass :
1452       (const TargetRegisterClass*)&X86::GR32RegClass;
1453     break;
1454   case MVT::x86mmx:
1455     RRC = &X86::VR64RegClass;
1456     break;
1457   case MVT::f32: case MVT::f64:
1458   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1459   case MVT::v4f32: case MVT::v2f64:
1460   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1461   case MVT::v4f64:
1462     RRC = &X86::VR128RegClass;
1463     break;
1464   }
1465   return std::make_pair(RRC, Cost);
1466 }
1467
1468 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1469                                                unsigned &Offset) const {
1470   if (!Subtarget->isTargetLinux())
1471     return false;
1472
1473   if (Subtarget->is64Bit()) {
1474     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1475     Offset = 0x28;
1476     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1477       AddressSpace = 256;
1478     else
1479       AddressSpace = 257;
1480   } else {
1481     // %gs:0x14 on i386
1482     Offset = 0x14;
1483     AddressSpace = 256;
1484   }
1485   return true;
1486 }
1487
1488
1489 //===----------------------------------------------------------------------===//
1490 //               Return Value Calling Convention Implementation
1491 //===----------------------------------------------------------------------===//
1492
1493 #include "X86GenCallingConv.inc"
1494
1495 bool
1496 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1497                                   MachineFunction &MF, bool isVarArg,
1498                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1499                         LLVMContext &Context) const {
1500   SmallVector<CCValAssign, 16> RVLocs;
1501   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1502                  RVLocs, Context);
1503   return CCInfo.CheckReturn(Outs, RetCC_X86);
1504 }
1505
1506 SDValue
1507 X86TargetLowering::LowerReturn(SDValue Chain,
1508                                CallingConv::ID CallConv, bool isVarArg,
1509                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1510                                const SmallVectorImpl<SDValue> &OutVals,
1511                                DebugLoc dl, SelectionDAG &DAG) const {
1512   MachineFunction &MF = DAG.getMachineFunction();
1513   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1514
1515   SmallVector<CCValAssign, 16> RVLocs;
1516   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1517                  RVLocs, *DAG.getContext());
1518   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1519
1520   // Add the regs to the liveout set for the function.
1521   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1522   for (unsigned i = 0; i != RVLocs.size(); ++i)
1523     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1524       MRI.addLiveOut(RVLocs[i].getLocReg());
1525
1526   SDValue Flag;
1527
1528   SmallVector<SDValue, 6> RetOps;
1529   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1530   // Operand #1 = Bytes To Pop
1531   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1532                    MVT::i16));
1533
1534   // Copy the result values into the output registers.
1535   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1536     CCValAssign &VA = RVLocs[i];
1537     assert(VA.isRegLoc() && "Can only return in registers!");
1538     SDValue ValToCopy = OutVals[i];
1539     EVT ValVT = ValToCopy.getValueType();
1540
1541     // Promote values to the appropriate types
1542     if (VA.getLocInfo() == CCValAssign::SExt)
1543       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1544     else if (VA.getLocInfo() == CCValAssign::ZExt)
1545       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1546     else if (VA.getLocInfo() == CCValAssign::AExt)
1547       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1548     else if (VA.getLocInfo() == CCValAssign::BCvt)
1549       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1550
1551     // If this is x86-64, and we disabled SSE, we can't return FP values,
1552     // or SSE or MMX vectors.
1553     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1554          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1555           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1556       report_fatal_error("SSE register return with SSE disabled");
1557     }
1558     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1559     // llvm-gcc has never done it right and no one has noticed, so this
1560     // should be OK for now.
1561     if (ValVT == MVT::f64 &&
1562         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1563       report_fatal_error("SSE2 register return with SSE2 disabled");
1564
1565     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1566     // the RET instruction and handled by the FP Stackifier.
1567     if (VA.getLocReg() == X86::ST0 ||
1568         VA.getLocReg() == X86::ST1) {
1569       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1570       // change the value to the FP stack register class.
1571       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1572         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1573       RetOps.push_back(ValToCopy);
1574       // Don't emit a copytoreg.
1575       continue;
1576     }
1577
1578     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1579     // which is returned in RAX / RDX.
1580     if (Subtarget->is64Bit()) {
1581       if (ValVT == MVT::x86mmx) {
1582         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1583           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1584           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1585                                   ValToCopy);
1586           // If we don't have SSE2 available, convert to v4f32 so the generated
1587           // register is legal.
1588           if (!Subtarget->hasSSE2())
1589             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1590         }
1591       }
1592     }
1593
1594     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1595     Flag = Chain.getValue(1);
1596   }
1597
1598   // The x86-64 ABI for returning structs by value requires that we copy
1599   // the sret argument into %rax for the return. We saved the argument into
1600   // a virtual register in the entry block, so now we copy the value out
1601   // and into %rax.
1602   if (Subtarget->is64Bit() &&
1603       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1604     MachineFunction &MF = DAG.getMachineFunction();
1605     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1606     unsigned Reg = FuncInfo->getSRetReturnReg();
1607     assert(Reg &&
1608            "SRetReturnReg should have been set in LowerFormalArguments().");
1609     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1610
1611     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1612     Flag = Chain.getValue(1);
1613
1614     // RAX now acts like a return value.
1615     MRI.addLiveOut(X86::RAX);
1616   }
1617
1618   RetOps[0] = Chain;  // Update chain.
1619
1620   // Add the flag if we have it.
1621   if (Flag.getNode())
1622     RetOps.push_back(Flag);
1623
1624   return DAG.getNode(X86ISD::RET_FLAG, dl,
1625                      MVT::Other, &RetOps[0], RetOps.size());
1626 }
1627
1628 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1629   if (N->getNumValues() != 1)
1630     return false;
1631   if (!N->hasNUsesOfValue(1, 0))
1632     return false;
1633
1634   SDValue TCChain = Chain;
1635   SDNode *Copy = *N->use_begin();
1636   if (Copy->getOpcode() == ISD::CopyToReg) {
1637     // If the copy has a glue operand, we conservatively assume it isn't safe to
1638     // perform a tail call.
1639     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1640       return false;
1641     TCChain = Copy->getOperand(0);
1642   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1643     return false;
1644
1645   bool HasRet = false;
1646   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1647        UI != UE; ++UI) {
1648     if (UI->getOpcode() != X86ISD::RET_FLAG)
1649       return false;
1650     HasRet = true;
1651   }
1652
1653   if (!HasRet)
1654     return false;
1655
1656   Chain = TCChain;
1657   return true;
1658 }
1659
1660 EVT
1661 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1662                                             ISD::NodeType ExtendKind) const {
1663   MVT ReturnMVT;
1664   // TODO: Is this also valid on 32-bit?
1665   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1666     ReturnMVT = MVT::i8;
1667   else
1668     ReturnMVT = MVT::i32;
1669
1670   EVT MinVT = getRegisterType(Context, ReturnMVT);
1671   return VT.bitsLT(MinVT) ? MinVT : VT;
1672 }
1673
1674 /// LowerCallResult - Lower the result values of a call into the
1675 /// appropriate copies out of appropriate physical registers.
1676 ///
1677 SDValue
1678 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1679                                    CallingConv::ID CallConv, bool isVarArg,
1680                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1681                                    DebugLoc dl, SelectionDAG &DAG,
1682                                    SmallVectorImpl<SDValue> &InVals) const {
1683
1684   // Assign locations to each value returned by this call.
1685   SmallVector<CCValAssign, 16> RVLocs;
1686   bool Is64Bit = Subtarget->is64Bit();
1687   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1688                  getTargetMachine(), RVLocs, *DAG.getContext());
1689   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1690
1691   // Copy all of the result registers out of their specified physreg.
1692   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1693     CCValAssign &VA = RVLocs[i];
1694     EVT CopyVT = VA.getValVT();
1695
1696     // If this is x86-64, and we disabled SSE, we can't return FP values
1697     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1698         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1699       report_fatal_error("SSE register return with SSE disabled");
1700     }
1701
1702     SDValue Val;
1703
1704     // If this is a call to a function that returns an fp value on the floating
1705     // point stack, we must guarantee the value is popped from the stack, so
1706     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1707     // if the return value is not used. We use the FpPOP_RETVAL instruction
1708     // instead.
1709     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1710       // If we prefer to use the value in xmm registers, copy it out as f80 and
1711       // use a truncate to move it from fp stack reg to xmm reg.
1712       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1713       SDValue Ops[] = { Chain, InFlag };
1714       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1715                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1716       Val = Chain.getValue(0);
1717
1718       // Round the f80 to the right size, which also moves it to the appropriate
1719       // xmm register.
1720       if (CopyVT != VA.getValVT())
1721         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1722                           // This truncation won't change the value.
1723                           DAG.getIntPtrConstant(1));
1724     } else {
1725       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1726                                  CopyVT, InFlag).getValue(1);
1727       Val = Chain.getValue(0);
1728     }
1729     InFlag = Chain.getValue(2);
1730     InVals.push_back(Val);
1731   }
1732
1733   return Chain;
1734 }
1735
1736
1737 //===----------------------------------------------------------------------===//
1738 //                C & StdCall & Fast Calling Convention implementation
1739 //===----------------------------------------------------------------------===//
1740 //  StdCall calling convention seems to be standard for many Windows' API
1741 //  routines and around. It differs from C calling convention just a little:
1742 //  callee should clean up the stack, not caller. Symbols should be also
1743 //  decorated in some fancy way :) It doesn't support any vector arguments.
1744 //  For info on fast calling convention see Fast Calling Convention (tail call)
1745 //  implementation LowerX86_32FastCCCallTo.
1746
1747 /// CallIsStructReturn - Determines whether a call uses struct return
1748 /// semantics.
1749 enum StructReturnType {
1750   NotStructReturn,
1751   RegStructReturn,
1752   StackStructReturn
1753 };
1754 static StructReturnType
1755 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1756   if (Outs.empty())
1757     return NotStructReturn;
1758
1759   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1760   if (!Flags.isSRet())
1761     return NotStructReturn;
1762   if (Flags.isInReg())
1763     return RegStructReturn;
1764   return StackStructReturn;
1765 }
1766
1767 /// ArgsAreStructReturn - Determines whether a function uses struct
1768 /// return semantics.
1769 static StructReturnType
1770 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1771   if (Ins.empty())
1772     return NotStructReturn;
1773
1774   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1775   if (!Flags.isSRet())
1776     return NotStructReturn;
1777   if (Flags.isInReg())
1778     return RegStructReturn;
1779   return StackStructReturn;
1780 }
1781
1782 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1783 /// by "Src" to address "Dst" with size and alignment information specified by
1784 /// the specific parameter attribute. The copy will be passed as a byval
1785 /// function parameter.
1786 static SDValue
1787 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1788                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1789                           DebugLoc dl) {
1790   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1791
1792   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1793                        /*isVolatile*/false, /*AlwaysInline=*/true,
1794                        MachinePointerInfo(), MachinePointerInfo());
1795 }
1796
1797 /// IsTailCallConvention - Return true if the calling convention is one that
1798 /// supports tail call optimization.
1799 static bool IsTailCallConvention(CallingConv::ID CC) {
1800   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1801 }
1802
1803 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1804   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1805     return false;
1806
1807   CallSite CS(CI);
1808   CallingConv::ID CalleeCC = CS.getCallingConv();
1809   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1810     return false;
1811
1812   return true;
1813 }
1814
1815 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1816 /// a tailcall target by changing its ABI.
1817 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1818                                    bool GuaranteedTailCallOpt) {
1819   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1820 }
1821
1822 SDValue
1823 X86TargetLowering::LowerMemArgument(SDValue Chain,
1824                                     CallingConv::ID CallConv,
1825                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1826                                     DebugLoc dl, SelectionDAG &DAG,
1827                                     const CCValAssign &VA,
1828                                     MachineFrameInfo *MFI,
1829                                     unsigned i) const {
1830   // Create the nodes corresponding to a load from this parameter slot.
1831   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1832   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1833                               getTargetMachine().Options.GuaranteedTailCallOpt);
1834   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1835   EVT ValVT;
1836
1837   // If value is passed by pointer we have address passed instead of the value
1838   // itself.
1839   if (VA.getLocInfo() == CCValAssign::Indirect)
1840     ValVT = VA.getLocVT();
1841   else
1842     ValVT = VA.getValVT();
1843
1844   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1845   // changed with more analysis.
1846   // In case of tail call optimization mark all arguments mutable. Since they
1847   // could be overwritten by lowering of arguments in case of a tail call.
1848   if (Flags.isByVal()) {
1849     unsigned Bytes = Flags.getByValSize();
1850     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1851     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1852     return DAG.getFrameIndex(FI, getPointerTy());
1853   } else {
1854     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1855                                     VA.getLocMemOffset(), isImmutable);
1856     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1857     return DAG.getLoad(ValVT, dl, Chain, FIN,
1858                        MachinePointerInfo::getFixedStack(FI),
1859                        false, false, false, 0);
1860   }
1861 }
1862
1863 SDValue
1864 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1865                                         CallingConv::ID CallConv,
1866                                         bool isVarArg,
1867                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1868                                         DebugLoc dl,
1869                                         SelectionDAG &DAG,
1870                                         SmallVectorImpl<SDValue> &InVals)
1871                                           const {
1872   MachineFunction &MF = DAG.getMachineFunction();
1873   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1874
1875   const Function* Fn = MF.getFunction();
1876   if (Fn->hasExternalLinkage() &&
1877       Subtarget->isTargetCygMing() &&
1878       Fn->getName() == "main")
1879     FuncInfo->setForceFramePointer(true);
1880
1881   MachineFrameInfo *MFI = MF.getFrameInfo();
1882   bool Is64Bit = Subtarget->is64Bit();
1883   bool IsWindows = Subtarget->isTargetWindows();
1884   bool IsWin64 = Subtarget->isTargetWin64();
1885
1886   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1887          "Var args not supported with calling convention fastcc or ghc");
1888
1889   // Assign locations to all of the incoming arguments.
1890   SmallVector<CCValAssign, 16> ArgLocs;
1891   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1892                  ArgLocs, *DAG.getContext());
1893
1894   // Allocate shadow area for Win64
1895   if (IsWin64) {
1896     CCInfo.AllocateStack(32, 8);
1897   }
1898
1899   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1900
1901   unsigned LastVal = ~0U;
1902   SDValue ArgValue;
1903   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1904     CCValAssign &VA = ArgLocs[i];
1905     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1906     // places.
1907     assert(VA.getValNo() != LastVal &&
1908            "Don't support value assigned to multiple locs yet");
1909     (void)LastVal;
1910     LastVal = VA.getValNo();
1911
1912     if (VA.isRegLoc()) {
1913       EVT RegVT = VA.getLocVT();
1914       const TargetRegisterClass *RC;
1915       if (RegVT == MVT::i32)
1916         RC = &X86::GR32RegClass;
1917       else if (Is64Bit && RegVT == MVT::i64)
1918         RC = &X86::GR64RegClass;
1919       else if (RegVT == MVT::f32)
1920         RC = &X86::FR32RegClass;
1921       else if (RegVT == MVT::f64)
1922         RC = &X86::FR64RegClass;
1923       else if (RegVT.is256BitVector())
1924         RC = &X86::VR256RegClass;
1925       else if (RegVT.is128BitVector())
1926         RC = &X86::VR128RegClass;
1927       else if (RegVT == MVT::x86mmx)
1928         RC = &X86::VR64RegClass;
1929       else
1930         llvm_unreachable("Unknown argument type!");
1931
1932       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1933       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1934
1935       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1936       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1937       // right size.
1938       if (VA.getLocInfo() == CCValAssign::SExt)
1939         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1940                                DAG.getValueType(VA.getValVT()));
1941       else if (VA.getLocInfo() == CCValAssign::ZExt)
1942         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1943                                DAG.getValueType(VA.getValVT()));
1944       else if (VA.getLocInfo() == CCValAssign::BCvt)
1945         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1946
1947       if (VA.isExtInLoc()) {
1948         // Handle MMX values passed in XMM regs.
1949         if (RegVT.isVector()) {
1950           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1951                                  ArgValue);
1952         } else
1953           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1954       }
1955     } else {
1956       assert(VA.isMemLoc());
1957       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1958     }
1959
1960     // If value is passed via pointer - do a load.
1961     if (VA.getLocInfo() == CCValAssign::Indirect)
1962       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1963                              MachinePointerInfo(), false, false, false, 0);
1964
1965     InVals.push_back(ArgValue);
1966   }
1967
1968   // The x86-64 ABI for returning structs by value requires that we copy
1969   // the sret argument into %rax for the return. Save the argument into
1970   // a virtual register so that we can access it from the return points.
1971   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1972     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1973     unsigned Reg = FuncInfo->getSRetReturnReg();
1974     if (!Reg) {
1975       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1976       FuncInfo->setSRetReturnReg(Reg);
1977     }
1978     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1979     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1980   }
1981
1982   unsigned StackSize = CCInfo.getNextStackOffset();
1983   // Align stack specially for tail calls.
1984   if (FuncIsMadeTailCallSafe(CallConv,
1985                              MF.getTarget().Options.GuaranteedTailCallOpt))
1986     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1987
1988   // If the function takes variable number of arguments, make a frame index for
1989   // the start of the first vararg value... for expansion of llvm.va_start.
1990   if (isVarArg) {
1991     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1992                     CallConv != CallingConv::X86_ThisCall)) {
1993       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1994     }
1995     if (Is64Bit) {
1996       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1997
1998       // FIXME: We should really autogenerate these arrays
1999       static const uint16_t GPR64ArgRegsWin64[] = {
2000         X86::RCX, X86::RDX, X86::R8,  X86::R9
2001       };
2002       static const uint16_t GPR64ArgRegs64Bit[] = {
2003         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2004       };
2005       static const uint16_t XMMArgRegs64Bit[] = {
2006         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2007         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2008       };
2009       const uint16_t *GPR64ArgRegs;
2010       unsigned NumXMMRegs = 0;
2011
2012       if (IsWin64) {
2013         // The XMM registers which might contain var arg parameters are shadowed
2014         // in their paired GPR.  So we only need to save the GPR to their home
2015         // slots.
2016         TotalNumIntRegs = 4;
2017         GPR64ArgRegs = GPR64ArgRegsWin64;
2018       } else {
2019         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2020         GPR64ArgRegs = GPR64ArgRegs64Bit;
2021
2022         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2023                                                 TotalNumXMMRegs);
2024       }
2025       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2026                                                        TotalNumIntRegs);
2027
2028       bool NoImplicitFloatOps = Fn->getFnAttributes().
2029         hasAttribute(Attributes::NoImplicitFloat);
2030       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2031              "SSE register cannot be used when SSE is disabled!");
2032       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2033                NoImplicitFloatOps) &&
2034              "SSE register cannot be used when SSE is disabled!");
2035       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2036           !Subtarget->hasSSE1())
2037         // Kernel mode asks for SSE to be disabled, so don't push them
2038         // on the stack.
2039         TotalNumXMMRegs = 0;
2040
2041       if (IsWin64) {
2042         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2043         // Get to the caller-allocated home save location.  Add 8 to account
2044         // for the return address.
2045         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2046         FuncInfo->setRegSaveFrameIndex(
2047           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2048         // Fixup to set vararg frame on shadow area (4 x i64).
2049         if (NumIntRegs < 4)
2050           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2051       } else {
2052         // For X86-64, if there are vararg parameters that are passed via
2053         // registers, then we must store them to their spots on the stack so
2054         // they may be loaded by deferencing the result of va_next.
2055         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2056         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2057         FuncInfo->setRegSaveFrameIndex(
2058           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2059                                false));
2060       }
2061
2062       // Store the integer parameter registers.
2063       SmallVector<SDValue, 8> MemOps;
2064       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2065                                         getPointerTy());
2066       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2067       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2068         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2069                                   DAG.getIntPtrConstant(Offset));
2070         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2071                                      &X86::GR64RegClass);
2072         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2073         SDValue Store =
2074           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2075                        MachinePointerInfo::getFixedStack(
2076                          FuncInfo->getRegSaveFrameIndex(), Offset),
2077                        false, false, 0);
2078         MemOps.push_back(Store);
2079         Offset += 8;
2080       }
2081
2082       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2083         // Now store the XMM (fp + vector) parameter registers.
2084         SmallVector<SDValue, 11> SaveXMMOps;
2085         SaveXMMOps.push_back(Chain);
2086
2087         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2088         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2089         SaveXMMOps.push_back(ALVal);
2090
2091         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2092                                FuncInfo->getRegSaveFrameIndex()));
2093         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2094                                FuncInfo->getVarArgsFPOffset()));
2095
2096         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2097           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2098                                        &X86::VR128RegClass);
2099           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2100           SaveXMMOps.push_back(Val);
2101         }
2102         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2103                                      MVT::Other,
2104                                      &SaveXMMOps[0], SaveXMMOps.size()));
2105       }
2106
2107       if (!MemOps.empty())
2108         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2109                             &MemOps[0], MemOps.size());
2110     }
2111   }
2112
2113   // Some CCs need callee pop.
2114   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2115                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2116     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2117   } else {
2118     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2119     // If this is an sret function, the return should pop the hidden pointer.
2120     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2121         argsAreStructReturn(Ins) == StackStructReturn)
2122       FuncInfo->setBytesToPopOnReturn(4);
2123   }
2124
2125   if (!Is64Bit) {
2126     // RegSaveFrameIndex is X86-64 only.
2127     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2128     if (CallConv == CallingConv::X86_FastCall ||
2129         CallConv == CallingConv::X86_ThisCall)
2130       // fastcc functions can't have varargs.
2131       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2132   }
2133
2134   FuncInfo->setArgumentStackSize(StackSize);
2135
2136   return Chain;
2137 }
2138
2139 SDValue
2140 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2141                                     SDValue StackPtr, SDValue Arg,
2142                                     DebugLoc dl, SelectionDAG &DAG,
2143                                     const CCValAssign &VA,
2144                                     ISD::ArgFlagsTy Flags) const {
2145   unsigned LocMemOffset = VA.getLocMemOffset();
2146   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2147   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2148   if (Flags.isByVal())
2149     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2150
2151   return DAG.getStore(Chain, dl, Arg, PtrOff,
2152                       MachinePointerInfo::getStack(LocMemOffset),
2153                       false, false, 0);
2154 }
2155
2156 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2157 /// optimization is performed and it is required.
2158 SDValue
2159 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2160                                            SDValue &OutRetAddr, SDValue Chain,
2161                                            bool IsTailCall, bool Is64Bit,
2162                                            int FPDiff, DebugLoc dl) const {
2163   // Adjust the Return address stack slot.
2164   EVT VT = getPointerTy();
2165   OutRetAddr = getReturnAddressFrameIndex(DAG);
2166
2167   // Load the "old" Return address.
2168   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2169                            false, false, false, 0);
2170   return SDValue(OutRetAddr.getNode(), 1);
2171 }
2172
2173 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2174 /// optimization is performed and it is required (FPDiff!=0).
2175 static SDValue
2176 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2177                          SDValue Chain, SDValue RetAddrFrIdx,
2178                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2179   // Store the return address to the appropriate stack slot.
2180   if (!FPDiff) return Chain;
2181   // Calculate the new stack slot for the return address.
2182   int SlotSize = Is64Bit ? 8 : 4;
2183   int NewReturnAddrFI =
2184     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2185   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2186   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2187   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2188                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2189                        false, false, 0);
2190   return Chain;
2191 }
2192
2193 SDValue
2194 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2195                              SmallVectorImpl<SDValue> &InVals) const {
2196   SelectionDAG &DAG                     = CLI.DAG;
2197   DebugLoc &dl                          = CLI.DL;
2198   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2199   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2200   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2201   SDValue Chain                         = CLI.Chain;
2202   SDValue Callee                        = CLI.Callee;
2203   CallingConv::ID CallConv              = CLI.CallConv;
2204   bool &isTailCall                      = CLI.IsTailCall;
2205   bool isVarArg                         = CLI.IsVarArg;
2206
2207   MachineFunction &MF = DAG.getMachineFunction();
2208   bool Is64Bit        = Subtarget->is64Bit();
2209   bool IsWin64        = Subtarget->isTargetWin64();
2210   bool IsWindows      = Subtarget->isTargetWindows();
2211   StructReturnType SR = callIsStructReturn(Outs);
2212   bool IsSibcall      = false;
2213
2214   if (MF.getTarget().Options.DisableTailCalls)
2215     isTailCall = false;
2216
2217   if (isTailCall) {
2218     // Check if it's really possible to do a tail call.
2219     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2220                     isVarArg, SR != NotStructReturn,
2221                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2222                     Outs, OutVals, Ins, DAG);
2223
2224     // Sibcalls are automatically detected tailcalls which do not require
2225     // ABI changes.
2226     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2227       IsSibcall = true;
2228
2229     if (isTailCall)
2230       ++NumTailCalls;
2231   }
2232
2233   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2234          "Var args not supported with calling convention fastcc or ghc");
2235
2236   // Analyze operands of the call, assigning locations to each operand.
2237   SmallVector<CCValAssign, 16> ArgLocs;
2238   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2239                  ArgLocs, *DAG.getContext());
2240
2241   // Allocate shadow area for Win64
2242   if (IsWin64) {
2243     CCInfo.AllocateStack(32, 8);
2244   }
2245
2246   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2247
2248   // Get a count of how many bytes are to be pushed on the stack.
2249   unsigned NumBytes = CCInfo.getNextStackOffset();
2250   if (IsSibcall)
2251     // This is a sibcall. The memory operands are available in caller's
2252     // own caller's stack.
2253     NumBytes = 0;
2254   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2255            IsTailCallConvention(CallConv))
2256     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2257
2258   int FPDiff = 0;
2259   if (isTailCall && !IsSibcall) {
2260     // Lower arguments at fp - stackoffset + fpdiff.
2261     unsigned NumBytesCallerPushed =
2262       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2263     FPDiff = NumBytesCallerPushed - NumBytes;
2264
2265     // Set the delta of movement of the returnaddr stackslot.
2266     // But only set if delta is greater than previous delta.
2267     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2268       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2269   }
2270
2271   if (!IsSibcall)
2272     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2273
2274   SDValue RetAddrFrIdx;
2275   // Load return address for tail calls.
2276   if (isTailCall && FPDiff)
2277     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2278                                     Is64Bit, FPDiff, dl);
2279
2280   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2281   SmallVector<SDValue, 8> MemOpChains;
2282   SDValue StackPtr;
2283
2284   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2285   // of tail call optimization arguments are handle later.
2286   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2287     CCValAssign &VA = ArgLocs[i];
2288     EVT RegVT = VA.getLocVT();
2289     SDValue Arg = OutVals[i];
2290     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2291     bool isByVal = Flags.isByVal();
2292
2293     // Promote the value if needed.
2294     switch (VA.getLocInfo()) {
2295     default: llvm_unreachable("Unknown loc info!");
2296     case CCValAssign::Full: break;
2297     case CCValAssign::SExt:
2298       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2299       break;
2300     case CCValAssign::ZExt:
2301       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2302       break;
2303     case CCValAssign::AExt:
2304       if (RegVT.is128BitVector()) {
2305         // Special case: passing MMX values in XMM registers.
2306         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2307         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2308         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2309       } else
2310         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2311       break;
2312     case CCValAssign::BCvt:
2313       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2314       break;
2315     case CCValAssign::Indirect: {
2316       // Store the argument.
2317       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2318       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2319       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2320                            MachinePointerInfo::getFixedStack(FI),
2321                            false, false, 0);
2322       Arg = SpillSlot;
2323       break;
2324     }
2325     }
2326
2327     if (VA.isRegLoc()) {
2328       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2329       if (isVarArg && IsWin64) {
2330         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2331         // shadow reg if callee is a varargs function.
2332         unsigned ShadowReg = 0;
2333         switch (VA.getLocReg()) {
2334         case X86::XMM0: ShadowReg = X86::RCX; break;
2335         case X86::XMM1: ShadowReg = X86::RDX; break;
2336         case X86::XMM2: ShadowReg = X86::R8; break;
2337         case X86::XMM3: ShadowReg = X86::R9; break;
2338         }
2339         if (ShadowReg)
2340           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2341       }
2342     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2343       assert(VA.isMemLoc());
2344       if (StackPtr.getNode() == 0)
2345         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2346       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2347                                              dl, DAG, VA, Flags));
2348     }
2349   }
2350
2351   if (!MemOpChains.empty())
2352     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2353                         &MemOpChains[0], MemOpChains.size());
2354
2355   if (Subtarget->isPICStyleGOT()) {
2356     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2357     // GOT pointer.
2358     if (!isTailCall) {
2359       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2360                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2361     } else {
2362       // If we are tail calling and generating PIC/GOT style code load the
2363       // address of the callee into ECX. The value in ecx is used as target of
2364       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2365       // for tail calls on PIC/GOT architectures. Normally we would just put the
2366       // address of GOT into ebx and then call target@PLT. But for tail calls
2367       // ebx would be restored (since ebx is callee saved) before jumping to the
2368       // target@PLT.
2369
2370       // Note: The actual moving to ECX is done further down.
2371       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2372       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2373           !G->getGlobal()->hasProtectedVisibility())
2374         Callee = LowerGlobalAddress(Callee, DAG);
2375       else if (isa<ExternalSymbolSDNode>(Callee))
2376         Callee = LowerExternalSymbol(Callee, DAG);
2377     }
2378   }
2379
2380   if (Is64Bit && isVarArg && !IsWin64) {
2381     // From AMD64 ABI document:
2382     // For calls that may call functions that use varargs or stdargs
2383     // (prototype-less calls or calls to functions containing ellipsis (...) in
2384     // the declaration) %al is used as hidden argument to specify the number
2385     // of SSE registers used. The contents of %al do not need to match exactly
2386     // the number of registers, but must be an ubound on the number of SSE
2387     // registers used and is in the range 0 - 8 inclusive.
2388
2389     // Count the number of XMM registers allocated.
2390     static const uint16_t XMMArgRegs[] = {
2391       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2392       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2393     };
2394     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2395     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2396            && "SSE registers cannot be used when SSE is disabled");
2397
2398     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2399                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2400   }
2401
2402   // For tail calls lower the arguments to the 'real' stack slot.
2403   if (isTailCall) {
2404     // Force all the incoming stack arguments to be loaded from the stack
2405     // before any new outgoing arguments are stored to the stack, because the
2406     // outgoing stack slots may alias the incoming argument stack slots, and
2407     // the alias isn't otherwise explicit. This is slightly more conservative
2408     // than necessary, because it means that each store effectively depends
2409     // on every argument instead of just those arguments it would clobber.
2410     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2411
2412     SmallVector<SDValue, 8> MemOpChains2;
2413     SDValue FIN;
2414     int FI = 0;
2415     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2416       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2417         CCValAssign &VA = ArgLocs[i];
2418         if (VA.isRegLoc())
2419           continue;
2420         assert(VA.isMemLoc());
2421         SDValue Arg = OutVals[i];
2422         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2423         // Create frame index.
2424         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2425         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2426         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2427         FIN = DAG.getFrameIndex(FI, getPointerTy());
2428
2429         if (Flags.isByVal()) {
2430           // Copy relative to framepointer.
2431           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2432           if (StackPtr.getNode() == 0)
2433             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2434                                           getPointerTy());
2435           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2436
2437           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2438                                                            ArgChain,
2439                                                            Flags, DAG, dl));
2440         } else {
2441           // Store relative to framepointer.
2442           MemOpChains2.push_back(
2443             DAG.getStore(ArgChain, dl, Arg, FIN,
2444                          MachinePointerInfo::getFixedStack(FI),
2445                          false, false, 0));
2446         }
2447       }
2448     }
2449
2450     if (!MemOpChains2.empty())
2451       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2452                           &MemOpChains2[0], MemOpChains2.size());
2453
2454     // Store the return address to the appropriate stack slot.
2455     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2456                                      FPDiff, dl);
2457   }
2458
2459   // Build a sequence of copy-to-reg nodes chained together with token chain
2460   // and flag operands which copy the outgoing args into registers.
2461   SDValue InFlag;
2462   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2463     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2464                              RegsToPass[i].second, InFlag);
2465     InFlag = Chain.getValue(1);
2466   }
2467
2468   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2469     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2470     // In the 64-bit large code model, we have to make all calls
2471     // through a register, since the call instruction's 32-bit
2472     // pc-relative offset may not be large enough to hold the whole
2473     // address.
2474   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2475     // If the callee is a GlobalAddress node (quite common, every direct call
2476     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2477     // it.
2478
2479     // We should use extra load for direct calls to dllimported functions in
2480     // non-JIT mode.
2481     const GlobalValue *GV = G->getGlobal();
2482     if (!GV->hasDLLImportLinkage()) {
2483       unsigned char OpFlags = 0;
2484       bool ExtraLoad = false;
2485       unsigned WrapperKind = ISD::DELETED_NODE;
2486
2487       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2488       // external symbols most go through the PLT in PIC mode.  If the symbol
2489       // has hidden or protected visibility, or if it is static or local, then
2490       // we don't need to use the PLT - we can directly call it.
2491       if (Subtarget->isTargetELF() &&
2492           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2493           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2494         OpFlags = X86II::MO_PLT;
2495       } else if (Subtarget->isPICStyleStubAny() &&
2496                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2497                  (!Subtarget->getTargetTriple().isMacOSX() ||
2498                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2499         // PC-relative references to external symbols should go through $stub,
2500         // unless we're building with the leopard linker or later, which
2501         // automatically synthesizes these stubs.
2502         OpFlags = X86II::MO_DARWIN_STUB;
2503       } else if (Subtarget->isPICStyleRIPRel() &&
2504                  isa<Function>(GV) &&
2505                  cast<Function>(GV)->getFnAttributes().
2506                    hasAttribute(Attributes::NonLazyBind)) {
2507         // If the function is marked as non-lazy, generate an indirect call
2508         // which loads from the GOT directly. This avoids runtime overhead
2509         // at the cost of eager binding (and one extra byte of encoding).
2510         OpFlags = X86II::MO_GOTPCREL;
2511         WrapperKind = X86ISD::WrapperRIP;
2512         ExtraLoad = true;
2513       }
2514
2515       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2516                                           G->getOffset(), OpFlags);
2517
2518       // Add a wrapper if needed.
2519       if (WrapperKind != ISD::DELETED_NODE)
2520         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2521       // Add extra indirection if needed.
2522       if (ExtraLoad)
2523         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2524                              MachinePointerInfo::getGOT(),
2525                              false, false, false, 0);
2526     }
2527   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2528     unsigned char OpFlags = 0;
2529
2530     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2531     // external symbols should go through the PLT.
2532     if (Subtarget->isTargetELF() &&
2533         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2534       OpFlags = X86II::MO_PLT;
2535     } else if (Subtarget->isPICStyleStubAny() &&
2536                (!Subtarget->getTargetTriple().isMacOSX() ||
2537                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2538       // PC-relative references to external symbols should go through $stub,
2539       // unless we're building with the leopard linker or later, which
2540       // automatically synthesizes these stubs.
2541       OpFlags = X86II::MO_DARWIN_STUB;
2542     }
2543
2544     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2545                                          OpFlags);
2546   }
2547
2548   // Returns a chain & a flag for retval copy to use.
2549   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2550   SmallVector<SDValue, 8> Ops;
2551
2552   if (!IsSibcall && isTailCall) {
2553     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2554                            DAG.getIntPtrConstant(0, true), InFlag);
2555     InFlag = Chain.getValue(1);
2556   }
2557
2558   Ops.push_back(Chain);
2559   Ops.push_back(Callee);
2560
2561   if (isTailCall)
2562     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2563
2564   // Add argument registers to the end of the list so that they are known live
2565   // into the call.
2566   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2567     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2568                                   RegsToPass[i].second.getValueType()));
2569
2570   // Add a register mask operand representing the call-preserved registers.
2571   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2572   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2573   assert(Mask && "Missing call preserved mask for calling convention");
2574   Ops.push_back(DAG.getRegisterMask(Mask));
2575
2576   if (InFlag.getNode())
2577     Ops.push_back(InFlag);
2578
2579   if (isTailCall) {
2580     // We used to do:
2581     //// If this is the first return lowered for this function, add the regs
2582     //// to the liveout set for the function.
2583     // This isn't right, although it's probably harmless on x86; liveouts
2584     // should be computed from returns not tail calls.  Consider a void
2585     // function making a tail call to a function returning int.
2586     return DAG.getNode(X86ISD::TC_RETURN, dl,
2587                        NodeTys, &Ops[0], Ops.size());
2588   }
2589
2590   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2591   InFlag = Chain.getValue(1);
2592
2593   // Create the CALLSEQ_END node.
2594   unsigned NumBytesForCalleeToPush;
2595   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2596                        getTargetMachine().Options.GuaranteedTailCallOpt))
2597     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2598   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2599            SR == StackStructReturn)
2600     // If this is a call to a struct-return function, the callee
2601     // pops the hidden struct pointer, so we have to push it back.
2602     // This is common for Darwin/X86, Linux & Mingw32 targets.
2603     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2604     NumBytesForCalleeToPush = 4;
2605   else
2606     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2607
2608   // Returns a flag for retval copy to use.
2609   if (!IsSibcall) {
2610     Chain = DAG.getCALLSEQ_END(Chain,
2611                                DAG.getIntPtrConstant(NumBytes, true),
2612                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2613                                                      true),
2614                                InFlag);
2615     InFlag = Chain.getValue(1);
2616   }
2617
2618   // Handle result values, copying them out of physregs into vregs that we
2619   // return.
2620   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2621                          Ins, dl, DAG, InVals);
2622 }
2623
2624
2625 //===----------------------------------------------------------------------===//
2626 //                Fast Calling Convention (tail call) implementation
2627 //===----------------------------------------------------------------------===//
2628
2629 //  Like std call, callee cleans arguments, convention except that ECX is
2630 //  reserved for storing the tail called function address. Only 2 registers are
2631 //  free for argument passing (inreg). Tail call optimization is performed
2632 //  provided:
2633 //                * tailcallopt is enabled
2634 //                * caller/callee are fastcc
2635 //  On X86_64 architecture with GOT-style position independent code only local
2636 //  (within module) calls are supported at the moment.
2637 //  To keep the stack aligned according to platform abi the function
2638 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2639 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2640 //  If a tail called function callee has more arguments than the caller the
2641 //  caller needs to make sure that there is room to move the RETADDR to. This is
2642 //  achieved by reserving an area the size of the argument delta right after the
2643 //  original REtADDR, but before the saved framepointer or the spilled registers
2644 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2645 //  stack layout:
2646 //    arg1
2647 //    arg2
2648 //    RETADDR
2649 //    [ new RETADDR
2650 //      move area ]
2651 //    (possible EBP)
2652 //    ESI
2653 //    EDI
2654 //    local1 ..
2655
2656 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2657 /// for a 16 byte align requirement.
2658 unsigned
2659 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2660                                                SelectionDAG& DAG) const {
2661   MachineFunction &MF = DAG.getMachineFunction();
2662   const TargetMachine &TM = MF.getTarget();
2663   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2664   unsigned StackAlignment = TFI.getStackAlignment();
2665   uint64_t AlignMask = StackAlignment - 1;
2666   int64_t Offset = StackSize;
2667   uint64_t SlotSize = TD->getPointerSize(0);
2668   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2669     // Number smaller than 12 so just add the difference.
2670     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2671   } else {
2672     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2673     Offset = ((~AlignMask) & Offset) + StackAlignment +
2674       (StackAlignment-SlotSize);
2675   }
2676   return Offset;
2677 }
2678
2679 /// MatchingStackOffset - Return true if the given stack call argument is
2680 /// already available in the same position (relatively) of the caller's
2681 /// incoming argument stack.
2682 static
2683 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2684                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2685                          const X86InstrInfo *TII) {
2686   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2687   int FI = INT_MAX;
2688   if (Arg.getOpcode() == ISD::CopyFromReg) {
2689     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2690     if (!TargetRegisterInfo::isVirtualRegister(VR))
2691       return false;
2692     MachineInstr *Def = MRI->getVRegDef(VR);
2693     if (!Def)
2694       return false;
2695     if (!Flags.isByVal()) {
2696       if (!TII->isLoadFromStackSlot(Def, FI))
2697         return false;
2698     } else {
2699       unsigned Opcode = Def->getOpcode();
2700       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2701           Def->getOperand(1).isFI()) {
2702         FI = Def->getOperand(1).getIndex();
2703         Bytes = Flags.getByValSize();
2704       } else
2705         return false;
2706     }
2707   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2708     if (Flags.isByVal())
2709       // ByVal argument is passed in as a pointer but it's now being
2710       // dereferenced. e.g.
2711       // define @foo(%struct.X* %A) {
2712       //   tail call @bar(%struct.X* byval %A)
2713       // }
2714       return false;
2715     SDValue Ptr = Ld->getBasePtr();
2716     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2717     if (!FINode)
2718       return false;
2719     FI = FINode->getIndex();
2720   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2721     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2722     FI = FINode->getIndex();
2723     Bytes = Flags.getByValSize();
2724   } else
2725     return false;
2726
2727   assert(FI != INT_MAX);
2728   if (!MFI->isFixedObjectIndex(FI))
2729     return false;
2730   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2731 }
2732
2733 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2734 /// for tail call optimization. Targets which want to do tail call
2735 /// optimization should implement this function.
2736 bool
2737 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2738                                                      CallingConv::ID CalleeCC,
2739                                                      bool isVarArg,
2740                                                      bool isCalleeStructRet,
2741                                                      bool isCallerStructRet,
2742                                                      Type *RetTy,
2743                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2744                                     const SmallVectorImpl<SDValue> &OutVals,
2745                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2746                                                      SelectionDAG& DAG) const {
2747   if (!IsTailCallConvention(CalleeCC) &&
2748       CalleeCC != CallingConv::C)
2749     return false;
2750
2751   // If -tailcallopt is specified, make fastcc functions tail-callable.
2752   const MachineFunction &MF = DAG.getMachineFunction();
2753   const Function *CallerF = DAG.getMachineFunction().getFunction();
2754
2755   // If the function return type is x86_fp80 and the callee return type is not,
2756   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2757   // perform a tailcall optimization here.
2758   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2759     return false;
2760
2761   CallingConv::ID CallerCC = CallerF->getCallingConv();
2762   bool CCMatch = CallerCC == CalleeCC;
2763
2764   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2765     if (IsTailCallConvention(CalleeCC) && CCMatch)
2766       return true;
2767     return false;
2768   }
2769
2770   // Look for obvious safe cases to perform tail call optimization that do not
2771   // require ABI changes. This is what gcc calls sibcall.
2772
2773   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2774   // emit a special epilogue.
2775   if (RegInfo->needsStackRealignment(MF))
2776     return false;
2777
2778   // Also avoid sibcall optimization if either caller or callee uses struct
2779   // return semantics.
2780   if (isCalleeStructRet || isCallerStructRet)
2781     return false;
2782
2783   // An stdcall caller is expected to clean up its arguments; the callee
2784   // isn't going to do that.
2785   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2786     return false;
2787
2788   // Do not sibcall optimize vararg calls unless all arguments are passed via
2789   // registers.
2790   if (isVarArg && !Outs.empty()) {
2791
2792     // Optimizing for varargs on Win64 is unlikely to be safe without
2793     // additional testing.
2794     if (Subtarget->isTargetWin64())
2795       return false;
2796
2797     SmallVector<CCValAssign, 16> ArgLocs;
2798     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2799                    getTargetMachine(), ArgLocs, *DAG.getContext());
2800
2801     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2802     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2803       if (!ArgLocs[i].isRegLoc())
2804         return false;
2805   }
2806
2807   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2808   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2809   // this into a sibcall.
2810   bool Unused = false;
2811   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2812     if (!Ins[i].Used) {
2813       Unused = true;
2814       break;
2815     }
2816   }
2817   if (Unused) {
2818     SmallVector<CCValAssign, 16> RVLocs;
2819     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2820                    getTargetMachine(), RVLocs, *DAG.getContext());
2821     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2822     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2823       CCValAssign &VA = RVLocs[i];
2824       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2825         return false;
2826     }
2827   }
2828
2829   // If the calling conventions do not match, then we'd better make sure the
2830   // results are returned in the same way as what the caller expects.
2831   if (!CCMatch) {
2832     SmallVector<CCValAssign, 16> RVLocs1;
2833     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2834                     getTargetMachine(), RVLocs1, *DAG.getContext());
2835     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2836
2837     SmallVector<CCValAssign, 16> RVLocs2;
2838     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2839                     getTargetMachine(), RVLocs2, *DAG.getContext());
2840     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2841
2842     if (RVLocs1.size() != RVLocs2.size())
2843       return false;
2844     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2845       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2846         return false;
2847       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2848         return false;
2849       if (RVLocs1[i].isRegLoc()) {
2850         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2851           return false;
2852       } else {
2853         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2854           return false;
2855       }
2856     }
2857   }
2858
2859   // If the callee takes no arguments then go on to check the results of the
2860   // call.
2861   if (!Outs.empty()) {
2862     // Check if stack adjustment is needed. For now, do not do this if any
2863     // argument is passed on the stack.
2864     SmallVector<CCValAssign, 16> ArgLocs;
2865     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2866                    getTargetMachine(), ArgLocs, *DAG.getContext());
2867
2868     // Allocate shadow area for Win64
2869     if (Subtarget->isTargetWin64()) {
2870       CCInfo.AllocateStack(32, 8);
2871     }
2872
2873     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2874     if (CCInfo.getNextStackOffset()) {
2875       MachineFunction &MF = DAG.getMachineFunction();
2876       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2877         return false;
2878
2879       // Check if the arguments are already laid out in the right way as
2880       // the caller's fixed stack objects.
2881       MachineFrameInfo *MFI = MF.getFrameInfo();
2882       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2883       const X86InstrInfo *TII =
2884         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2885       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886         CCValAssign &VA = ArgLocs[i];
2887         SDValue Arg = OutVals[i];
2888         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2889         if (VA.getLocInfo() == CCValAssign::Indirect)
2890           return false;
2891         if (!VA.isRegLoc()) {
2892           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2893                                    MFI, MRI, TII))
2894             return false;
2895         }
2896       }
2897     }
2898
2899     // If the tailcall address may be in a register, then make sure it's
2900     // possible to register allocate for it. In 32-bit, the call address can
2901     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2902     // callee-saved registers are restored. These happen to be the same
2903     // registers used to pass 'inreg' arguments so watch out for those.
2904     if (!Subtarget->is64Bit() &&
2905         !isa<GlobalAddressSDNode>(Callee) &&
2906         !isa<ExternalSymbolSDNode>(Callee)) {
2907       unsigned NumInRegs = 0;
2908       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2909         CCValAssign &VA = ArgLocs[i];
2910         if (!VA.isRegLoc())
2911           continue;
2912         unsigned Reg = VA.getLocReg();
2913         switch (Reg) {
2914         default: break;
2915         case X86::EAX: case X86::EDX: case X86::ECX:
2916           if (++NumInRegs == 3)
2917             return false;
2918           break;
2919         }
2920       }
2921     }
2922   }
2923
2924   return true;
2925 }
2926
2927 FastISel *
2928 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2929                                   const TargetLibraryInfo *libInfo) const {
2930   return X86::createFastISel(funcInfo, libInfo);
2931 }
2932
2933
2934 //===----------------------------------------------------------------------===//
2935 //                           Other Lowering Hooks
2936 //===----------------------------------------------------------------------===//
2937
2938 static bool MayFoldLoad(SDValue Op) {
2939   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2940 }
2941
2942 static bool MayFoldIntoStore(SDValue Op) {
2943   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2944 }
2945
2946 static bool isTargetShuffle(unsigned Opcode) {
2947   switch(Opcode) {
2948   default: return false;
2949   case X86ISD::PSHUFD:
2950   case X86ISD::PSHUFHW:
2951   case X86ISD::PSHUFLW:
2952   case X86ISD::SHUFP:
2953   case X86ISD::PALIGN:
2954   case X86ISD::MOVLHPS:
2955   case X86ISD::MOVLHPD:
2956   case X86ISD::MOVHLPS:
2957   case X86ISD::MOVLPS:
2958   case X86ISD::MOVLPD:
2959   case X86ISD::MOVSHDUP:
2960   case X86ISD::MOVSLDUP:
2961   case X86ISD::MOVDDUP:
2962   case X86ISD::MOVSS:
2963   case X86ISD::MOVSD:
2964   case X86ISD::UNPCKL:
2965   case X86ISD::UNPCKH:
2966   case X86ISD::VPERMILP:
2967   case X86ISD::VPERM2X128:
2968   case X86ISD::VPERMI:
2969     return true;
2970   }
2971 }
2972
2973 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2974                                     SDValue V1, SelectionDAG &DAG) {
2975   switch(Opc) {
2976   default: llvm_unreachable("Unknown x86 shuffle node");
2977   case X86ISD::MOVSHDUP:
2978   case X86ISD::MOVSLDUP:
2979   case X86ISD::MOVDDUP:
2980     return DAG.getNode(Opc, dl, VT, V1);
2981   }
2982 }
2983
2984 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2985                                     SDValue V1, unsigned TargetMask,
2986                                     SelectionDAG &DAG) {
2987   switch(Opc) {
2988   default: llvm_unreachable("Unknown x86 shuffle node");
2989   case X86ISD::PSHUFD:
2990   case X86ISD::PSHUFHW:
2991   case X86ISD::PSHUFLW:
2992   case X86ISD::VPERMILP:
2993   case X86ISD::VPERMI:
2994     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2995   }
2996 }
2997
2998 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2999                                     SDValue V1, SDValue V2, unsigned TargetMask,
3000                                     SelectionDAG &DAG) {
3001   switch(Opc) {
3002   default: llvm_unreachable("Unknown x86 shuffle node");
3003   case X86ISD::PALIGN:
3004   case X86ISD::SHUFP:
3005   case X86ISD::VPERM2X128:
3006     return DAG.getNode(Opc, dl, VT, V1, V2,
3007                        DAG.getConstant(TargetMask, MVT::i8));
3008   }
3009 }
3010
3011 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3012                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3013   switch(Opc) {
3014   default: llvm_unreachable("Unknown x86 shuffle node");
3015   case X86ISD::MOVLHPS:
3016   case X86ISD::MOVLHPD:
3017   case X86ISD::MOVHLPS:
3018   case X86ISD::MOVLPS:
3019   case X86ISD::MOVLPD:
3020   case X86ISD::MOVSS:
3021   case X86ISD::MOVSD:
3022   case X86ISD::UNPCKL:
3023   case X86ISD::UNPCKH:
3024     return DAG.getNode(Opc, dl, VT, V1, V2);
3025   }
3026 }
3027
3028 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3029   MachineFunction &MF = DAG.getMachineFunction();
3030   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3031   int ReturnAddrIndex = FuncInfo->getRAIndex();
3032
3033   if (ReturnAddrIndex == 0) {
3034     // Set up a frame object for the return address.
3035     uint64_t SlotSize = TD->getPointerSize(0);
3036     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3037                                                            false);
3038     FuncInfo->setRAIndex(ReturnAddrIndex);
3039   }
3040
3041   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3042 }
3043
3044
3045 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3046                                        bool hasSymbolicDisplacement) {
3047   // Offset should fit into 32 bit immediate field.
3048   if (!isInt<32>(Offset))
3049     return false;
3050
3051   // If we don't have a symbolic displacement - we don't have any extra
3052   // restrictions.
3053   if (!hasSymbolicDisplacement)
3054     return true;
3055
3056   // FIXME: Some tweaks might be needed for medium code model.
3057   if (M != CodeModel::Small && M != CodeModel::Kernel)
3058     return false;
3059
3060   // For small code model we assume that latest object is 16MB before end of 31
3061   // bits boundary. We may also accept pretty large negative constants knowing
3062   // that all objects are in the positive half of address space.
3063   if (M == CodeModel::Small && Offset < 16*1024*1024)
3064     return true;
3065
3066   // For kernel code model we know that all object resist in the negative half
3067   // of 32bits address space. We may not accept negative offsets, since they may
3068   // be just off and we may accept pretty large positive ones.
3069   if (M == CodeModel::Kernel && Offset > 0)
3070     return true;
3071
3072   return false;
3073 }
3074
3075 /// isCalleePop - Determines whether the callee is required to pop its
3076 /// own arguments. Callee pop is necessary to support tail calls.
3077 bool X86::isCalleePop(CallingConv::ID CallingConv,
3078                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3079   if (IsVarArg)
3080     return false;
3081
3082   switch (CallingConv) {
3083   default:
3084     return false;
3085   case CallingConv::X86_StdCall:
3086     return !is64Bit;
3087   case CallingConv::X86_FastCall:
3088     return !is64Bit;
3089   case CallingConv::X86_ThisCall:
3090     return !is64Bit;
3091   case CallingConv::Fast:
3092     return TailCallOpt;
3093   case CallingConv::GHC:
3094     return TailCallOpt;
3095   }
3096 }
3097
3098 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3099 /// specific condition code, returning the condition code and the LHS/RHS of the
3100 /// comparison to make.
3101 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3102                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3103   if (!isFP) {
3104     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3105       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3106         // X > -1   -> X == 0, jump !sign.
3107         RHS = DAG.getConstant(0, RHS.getValueType());
3108         return X86::COND_NS;
3109       }
3110       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3111         // X < 0   -> X == 0, jump on sign.
3112         return X86::COND_S;
3113       }
3114       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3115         // X < 1   -> X <= 0
3116         RHS = DAG.getConstant(0, RHS.getValueType());
3117         return X86::COND_LE;
3118       }
3119     }
3120
3121     switch (SetCCOpcode) {
3122     default: llvm_unreachable("Invalid integer condition!");
3123     case ISD::SETEQ:  return X86::COND_E;
3124     case ISD::SETGT:  return X86::COND_G;
3125     case ISD::SETGE:  return X86::COND_GE;
3126     case ISD::SETLT:  return X86::COND_L;
3127     case ISD::SETLE:  return X86::COND_LE;
3128     case ISD::SETNE:  return X86::COND_NE;
3129     case ISD::SETULT: return X86::COND_B;
3130     case ISD::SETUGT: return X86::COND_A;
3131     case ISD::SETULE: return X86::COND_BE;
3132     case ISD::SETUGE: return X86::COND_AE;
3133     }
3134   }
3135
3136   // First determine if it is required or is profitable to flip the operands.
3137
3138   // If LHS is a foldable load, but RHS is not, flip the condition.
3139   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3140       !ISD::isNON_EXTLoad(RHS.getNode())) {
3141     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3142     std::swap(LHS, RHS);
3143   }
3144
3145   switch (SetCCOpcode) {
3146   default: break;
3147   case ISD::SETOLT:
3148   case ISD::SETOLE:
3149   case ISD::SETUGT:
3150   case ISD::SETUGE:
3151     std::swap(LHS, RHS);
3152     break;
3153   }
3154
3155   // On a floating point condition, the flags are set as follows:
3156   // ZF  PF  CF   op
3157   //  0 | 0 | 0 | X > Y
3158   //  0 | 0 | 1 | X < Y
3159   //  1 | 0 | 0 | X == Y
3160   //  1 | 1 | 1 | unordered
3161   switch (SetCCOpcode) {
3162   default: llvm_unreachable("Condcode should be pre-legalized away");
3163   case ISD::SETUEQ:
3164   case ISD::SETEQ:   return X86::COND_E;
3165   case ISD::SETOLT:              // flipped
3166   case ISD::SETOGT:
3167   case ISD::SETGT:   return X86::COND_A;
3168   case ISD::SETOLE:              // flipped
3169   case ISD::SETOGE:
3170   case ISD::SETGE:   return X86::COND_AE;
3171   case ISD::SETUGT:              // flipped
3172   case ISD::SETULT:
3173   case ISD::SETLT:   return X86::COND_B;
3174   case ISD::SETUGE:              // flipped
3175   case ISD::SETULE:
3176   case ISD::SETLE:   return X86::COND_BE;
3177   case ISD::SETONE:
3178   case ISD::SETNE:   return X86::COND_NE;
3179   case ISD::SETUO:   return X86::COND_P;
3180   case ISD::SETO:    return X86::COND_NP;
3181   case ISD::SETOEQ:
3182   case ISD::SETUNE:  return X86::COND_INVALID;
3183   }
3184 }
3185
3186 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3187 /// code. Current x86 isa includes the following FP cmov instructions:
3188 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3189 static bool hasFPCMov(unsigned X86CC) {
3190   switch (X86CC) {
3191   default:
3192     return false;
3193   case X86::COND_B:
3194   case X86::COND_BE:
3195   case X86::COND_E:
3196   case X86::COND_P:
3197   case X86::COND_A:
3198   case X86::COND_AE:
3199   case X86::COND_NE:
3200   case X86::COND_NP:
3201     return true;
3202   }
3203 }
3204
3205 /// isFPImmLegal - Returns true if the target can instruction select the
3206 /// specified FP immediate natively. If false, the legalizer will
3207 /// materialize the FP immediate as a load from a constant pool.
3208 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3209   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3210     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3211       return true;
3212   }
3213   return false;
3214 }
3215
3216 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3217 /// the specified range (L, H].
3218 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3219   return (Val < 0) || (Val >= Low && Val < Hi);
3220 }
3221
3222 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3223 /// specified value.
3224 static bool isUndefOrEqual(int Val, int CmpVal) {
3225   if (Val < 0 || Val == CmpVal)
3226     return true;
3227   return false;
3228 }
3229
3230 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3231 /// from position Pos and ending in Pos+Size, falls within the specified
3232 /// sequential range (L, L+Pos]. or is undef.
3233 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3234                                        unsigned Pos, unsigned Size, int Low) {
3235   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3236     if (!isUndefOrEqual(Mask[i], Low))
3237       return false;
3238   return true;
3239 }
3240
3241 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3242 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3243 /// the second operand.
3244 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3245   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3246     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3247   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3248     return (Mask[0] < 2 && Mask[1] < 2);
3249   return false;
3250 }
3251
3252 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PSHUFHW.
3254 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3255   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3256     return false;
3257
3258   // Lower quadword copied in order or undef.
3259   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3260     return false;
3261
3262   // Upper quadword shuffled.
3263   for (unsigned i = 4; i != 8; ++i)
3264     if (!isUndefOrInRange(Mask[i], 4, 8))
3265       return false;
3266
3267   if (VT == MVT::v16i16) {
3268     // Lower quadword copied in order or undef.
3269     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3270       return false;
3271
3272     // Upper quadword shuffled.
3273     for (unsigned i = 12; i != 16; ++i)
3274       if (!isUndefOrInRange(Mask[i], 12, 16))
3275         return false;
3276   }
3277
3278   return true;
3279 }
3280
3281 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3282 /// is suitable for input to PSHUFLW.
3283 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3284   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3285     return false;
3286
3287   // Upper quadword copied in order.
3288   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3289     return false;
3290
3291   // Lower quadword shuffled.
3292   for (unsigned i = 0; i != 4; ++i)
3293     if (!isUndefOrInRange(Mask[i], 0, 4))
3294       return false;
3295
3296   if (VT == MVT::v16i16) {
3297     // Upper quadword copied in order.
3298     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3299       return false;
3300
3301     // Lower quadword shuffled.
3302     for (unsigned i = 8; i != 12; ++i)
3303       if (!isUndefOrInRange(Mask[i], 8, 12))
3304         return false;
3305   }
3306
3307   return true;
3308 }
3309
3310 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3311 /// is suitable for input to PALIGNR.
3312 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3313                           const X86Subtarget *Subtarget) {
3314   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3315       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3316     return false;
3317
3318   unsigned NumElts = VT.getVectorNumElements();
3319   unsigned NumLanes = VT.getSizeInBits()/128;
3320   unsigned NumLaneElts = NumElts/NumLanes;
3321
3322   // Do not handle 64-bit element shuffles with palignr.
3323   if (NumLaneElts == 2)
3324     return false;
3325
3326   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3327     unsigned i;
3328     for (i = 0; i != NumLaneElts; ++i) {
3329       if (Mask[i+l] >= 0)
3330         break;
3331     }
3332
3333     // Lane is all undef, go to next lane
3334     if (i == NumLaneElts)
3335       continue;
3336
3337     int Start = Mask[i+l];
3338
3339     // Make sure its in this lane in one of the sources
3340     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3341         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3342       return false;
3343
3344     // If not lane 0, then we must match lane 0
3345     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3346       return false;
3347
3348     // Correct second source to be contiguous with first source
3349     if (Start >= (int)NumElts)
3350       Start -= NumElts - NumLaneElts;
3351
3352     // Make sure we're shifting in the right direction.
3353     if (Start <= (int)(i+l))
3354       return false;
3355
3356     Start -= i;
3357
3358     // Check the rest of the elements to see if they are consecutive.
3359     for (++i; i != NumLaneElts; ++i) {
3360       int Idx = Mask[i+l];
3361
3362       // Make sure its in this lane
3363       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3364           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3365         return false;
3366
3367       // If not lane 0, then we must match lane 0
3368       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3369         return false;
3370
3371       if (Idx >= (int)NumElts)
3372         Idx -= NumElts - NumLaneElts;
3373
3374       if (!isUndefOrEqual(Idx, Start+i))
3375         return false;
3376
3377     }
3378   }
3379
3380   return true;
3381 }
3382
3383 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3384 /// the two vector operands have swapped position.
3385 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3386                                      unsigned NumElems) {
3387   for (unsigned i = 0; i != NumElems; ++i) {
3388     int idx = Mask[i];
3389     if (idx < 0)
3390       continue;
3391     else if (idx < (int)NumElems)
3392       Mask[i] = idx + NumElems;
3393     else
3394       Mask[i] = idx - NumElems;
3395   }
3396 }
3397
3398 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3399 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3400 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3401 /// reverse of what x86 shuffles want.
3402 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3403                         bool Commuted = false) {
3404   if (!HasAVX && VT.getSizeInBits() == 256)
3405     return false;
3406
3407   unsigned NumElems = VT.getVectorNumElements();
3408   unsigned NumLanes = VT.getSizeInBits()/128;
3409   unsigned NumLaneElems = NumElems/NumLanes;
3410
3411   if (NumLaneElems != 2 && NumLaneElems != 4)
3412     return false;
3413
3414   // VSHUFPSY divides the resulting vector into 4 chunks.
3415   // The sources are also splitted into 4 chunks, and each destination
3416   // chunk must come from a different source chunk.
3417   //
3418   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3419   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3420   //
3421   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3422   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3423   //
3424   // VSHUFPDY divides the resulting vector into 4 chunks.
3425   // The sources are also splitted into 4 chunks, and each destination
3426   // chunk must come from a different source chunk.
3427   //
3428   //  SRC1 =>      X3       X2       X1       X0
3429   //  SRC2 =>      Y3       Y2       Y1       Y0
3430   //
3431   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3432   //
3433   unsigned HalfLaneElems = NumLaneElems/2;
3434   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3435     for (unsigned i = 0; i != NumLaneElems; ++i) {
3436       int Idx = Mask[i+l];
3437       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3438       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3439         return false;
3440       // For VSHUFPSY, the mask of the second half must be the same as the
3441       // first but with the appropriate offsets. This works in the same way as
3442       // VPERMILPS works with masks.
3443       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3444         continue;
3445       if (!isUndefOrEqual(Idx, Mask[i]+l))
3446         return false;
3447     }
3448   }
3449
3450   return true;
3451 }
3452
3453 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3455 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3456   if (!VT.is128BitVector())
3457     return false;
3458
3459   unsigned NumElems = VT.getVectorNumElements();
3460
3461   if (NumElems != 4)
3462     return false;
3463
3464   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3465   return isUndefOrEqual(Mask[0], 6) &&
3466          isUndefOrEqual(Mask[1], 7) &&
3467          isUndefOrEqual(Mask[2], 2) &&
3468          isUndefOrEqual(Mask[3], 3);
3469 }
3470
3471 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3472 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3473 /// <2, 3, 2, 3>
3474 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3475   if (!VT.is128BitVector())
3476     return false;
3477
3478   unsigned NumElems = VT.getVectorNumElements();
3479
3480   if (NumElems != 4)
3481     return false;
3482
3483   return isUndefOrEqual(Mask[0], 2) &&
3484          isUndefOrEqual(Mask[1], 3) &&
3485          isUndefOrEqual(Mask[2], 2) &&
3486          isUndefOrEqual(Mask[3], 3);
3487 }
3488
3489 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3491 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3492   if (!VT.is128BitVector())
3493     return false;
3494
3495   unsigned NumElems = VT.getVectorNumElements();
3496
3497   if (NumElems != 2 && NumElems != 4)
3498     return false;
3499
3500   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3501     if (!isUndefOrEqual(Mask[i], i + NumElems))
3502       return false;
3503
3504   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3505     if (!isUndefOrEqual(Mask[i], i))
3506       return false;
3507
3508   return true;
3509 }
3510
3511 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3513 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3514   if (!VT.is128BitVector())
3515     return false;
3516
3517   unsigned NumElems = VT.getVectorNumElements();
3518
3519   if (NumElems != 2 && NumElems != 4)
3520     return false;
3521
3522   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3523     if (!isUndefOrEqual(Mask[i], i))
3524       return false;
3525
3526   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3527     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3528       return false;
3529
3530   return true;
3531 }
3532
3533 //
3534 // Some special combinations that can be optimized.
3535 //
3536 static
3537 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3538                                SelectionDAG &DAG) {
3539   EVT VT = SVOp->getValueType(0);
3540   DebugLoc dl = SVOp->getDebugLoc();
3541
3542   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3543     return SDValue();
3544
3545   ArrayRef<int> Mask = SVOp->getMask();
3546
3547   // These are the special masks that may be optimized.
3548   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3549   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3550   bool MatchEvenMask = true;
3551   bool MatchOddMask  = true;
3552   for (int i=0; i<8; ++i) {
3553     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3554       MatchEvenMask = false;
3555     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3556       MatchOddMask = false;
3557   }
3558
3559   if (!MatchEvenMask && !MatchOddMask)
3560     return SDValue();
3561
3562   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3563
3564   SDValue Op0 = SVOp->getOperand(0);
3565   SDValue Op1 = SVOp->getOperand(1);
3566
3567   if (MatchEvenMask) {
3568     // Shift the second operand right to 32 bits.
3569     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3570     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3571   } else {
3572     // Shift the first operand left to 32 bits.
3573     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3574     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3575   }
3576   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3577   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3578 }
3579
3580 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3581 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3582 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3583                          bool HasAVX2, bool V2IsSplat = false) {
3584   unsigned NumElts = VT.getVectorNumElements();
3585
3586   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3587          "Unsupported vector type for unpckh");
3588
3589   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3590       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3591     return false;
3592
3593   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3594   // independently on 128-bit lanes.
3595   unsigned NumLanes = VT.getSizeInBits()/128;
3596   unsigned NumLaneElts = NumElts/NumLanes;
3597
3598   for (unsigned l = 0; l != NumLanes; ++l) {
3599     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3600          i != (l+1)*NumLaneElts;
3601          i += 2, ++j) {
3602       int BitI  = Mask[i];
3603       int BitI1 = Mask[i+1];
3604       if (!isUndefOrEqual(BitI, j))
3605         return false;
3606       if (V2IsSplat) {
3607         if (!isUndefOrEqual(BitI1, NumElts))
3608           return false;
3609       } else {
3610         if (!isUndefOrEqual(BitI1, j + NumElts))
3611           return false;
3612       }
3613     }
3614   }
3615
3616   return true;
3617 }
3618
3619 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3620 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3621 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3622                          bool HasAVX2, bool V2IsSplat = false) {
3623   unsigned NumElts = VT.getVectorNumElements();
3624
3625   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3626          "Unsupported vector type for unpckh");
3627
3628   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3629       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3630     return false;
3631
3632   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3633   // independently on 128-bit lanes.
3634   unsigned NumLanes = VT.getSizeInBits()/128;
3635   unsigned NumLaneElts = NumElts/NumLanes;
3636
3637   for (unsigned l = 0; l != NumLanes; ++l) {
3638     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3639          i != (l+1)*NumLaneElts; i += 2, ++j) {
3640       int BitI  = Mask[i];
3641       int BitI1 = Mask[i+1];
3642       if (!isUndefOrEqual(BitI, j))
3643         return false;
3644       if (V2IsSplat) {
3645         if (isUndefOrEqual(BitI1, NumElts))
3646           return false;
3647       } else {
3648         if (!isUndefOrEqual(BitI1, j+NumElts))
3649           return false;
3650       }
3651     }
3652   }
3653   return true;
3654 }
3655
3656 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3657 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3658 /// <0, 0, 1, 1>
3659 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3660                                   bool HasAVX2) {
3661   unsigned NumElts = VT.getVectorNumElements();
3662
3663   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3664          "Unsupported vector type for unpckh");
3665
3666   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3667       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3668     return false;
3669
3670   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3671   // FIXME: Need a better way to get rid of this, there's no latency difference
3672   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3673   // the former later. We should also remove the "_undef" special mask.
3674   if (NumElts == 4 && VT.getSizeInBits() == 256)
3675     return false;
3676
3677   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3678   // independently on 128-bit lanes.
3679   unsigned NumLanes = VT.getSizeInBits()/128;
3680   unsigned NumLaneElts = NumElts/NumLanes;
3681
3682   for (unsigned l = 0; l != NumLanes; ++l) {
3683     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3684          i != (l+1)*NumLaneElts;
3685          i += 2, ++j) {
3686       int BitI  = Mask[i];
3687       int BitI1 = Mask[i+1];
3688
3689       if (!isUndefOrEqual(BitI, j))
3690         return false;
3691       if (!isUndefOrEqual(BitI1, j))
3692         return false;
3693     }
3694   }
3695
3696   return true;
3697 }
3698
3699 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3700 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3701 /// <2, 2, 3, 3>
3702 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3703   unsigned NumElts = VT.getVectorNumElements();
3704
3705   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3706          "Unsupported vector type for unpckh");
3707
3708   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3709       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3710     return false;
3711
3712   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3713   // independently on 128-bit lanes.
3714   unsigned NumLanes = VT.getSizeInBits()/128;
3715   unsigned NumLaneElts = NumElts/NumLanes;
3716
3717   for (unsigned l = 0; l != NumLanes; ++l) {
3718     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3719          i != (l+1)*NumLaneElts; i += 2, ++j) {
3720       int BitI  = Mask[i];
3721       int BitI1 = Mask[i+1];
3722       if (!isUndefOrEqual(BitI, j))
3723         return false;
3724       if (!isUndefOrEqual(BitI1, j))
3725         return false;
3726     }
3727   }
3728   return true;
3729 }
3730
3731 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3732 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3733 /// MOVSD, and MOVD, i.e. setting the lowest element.
3734 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3735   if (VT.getVectorElementType().getSizeInBits() < 32)
3736     return false;
3737   if (!VT.is128BitVector())
3738     return false;
3739
3740   unsigned NumElts = VT.getVectorNumElements();
3741
3742   if (!isUndefOrEqual(Mask[0], NumElts))
3743     return false;
3744
3745   for (unsigned i = 1; i != NumElts; ++i)
3746     if (!isUndefOrEqual(Mask[i], i))
3747       return false;
3748
3749   return true;
3750 }
3751
3752 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3753 /// as permutations between 128-bit chunks or halves. As an example: this
3754 /// shuffle bellow:
3755 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3756 /// The first half comes from the second half of V1 and the second half from the
3757 /// the second half of V2.
3758 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3759   if (!HasAVX || !VT.is256BitVector())
3760     return false;
3761
3762   // The shuffle result is divided into half A and half B. In total the two
3763   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3764   // B must come from C, D, E or F.
3765   unsigned HalfSize = VT.getVectorNumElements()/2;
3766   bool MatchA = false, MatchB = false;
3767
3768   // Check if A comes from one of C, D, E, F.
3769   for (unsigned Half = 0; Half != 4; ++Half) {
3770     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3771       MatchA = true;
3772       break;
3773     }
3774   }
3775
3776   // Check if B comes from one of C, D, E, F.
3777   for (unsigned Half = 0; Half != 4; ++Half) {
3778     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3779       MatchB = true;
3780       break;
3781     }
3782   }
3783
3784   return MatchA && MatchB;
3785 }
3786
3787 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3788 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3789 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3790   EVT VT = SVOp->getValueType(0);
3791
3792   unsigned HalfSize = VT.getVectorNumElements()/2;
3793
3794   unsigned FstHalf = 0, SndHalf = 0;
3795   for (unsigned i = 0; i < HalfSize; ++i) {
3796     if (SVOp->getMaskElt(i) > 0) {
3797       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3798       break;
3799     }
3800   }
3801   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3802     if (SVOp->getMaskElt(i) > 0) {
3803       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3804       break;
3805     }
3806   }
3807
3808   return (FstHalf | (SndHalf << 4));
3809 }
3810
3811 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3812 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3813 /// Note that VPERMIL mask matching is different depending whether theunderlying
3814 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3815 /// to the same elements of the low, but to the higher half of the source.
3816 /// In VPERMILPD the two lanes could be shuffled independently of each other
3817 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3818 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3819   if (!HasAVX)
3820     return false;
3821
3822   unsigned NumElts = VT.getVectorNumElements();
3823   // Only match 256-bit with 32/64-bit types
3824   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3825     return false;
3826
3827   unsigned NumLanes = VT.getSizeInBits()/128;
3828   unsigned LaneSize = NumElts/NumLanes;
3829   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3830     for (unsigned i = 0; i != LaneSize; ++i) {
3831       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3832         return false;
3833       if (NumElts != 8 || l == 0)
3834         continue;
3835       // VPERMILPS handling
3836       if (Mask[i] < 0)
3837         continue;
3838       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3839         return false;
3840     }
3841   }
3842
3843   return true;
3844 }
3845
3846 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3847 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3848 /// element of vector 2 and the other elements to come from vector 1 in order.
3849 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3850                                bool V2IsSplat = false, bool V2IsUndef = false) {
3851   if (!VT.is128BitVector())
3852     return false;
3853
3854   unsigned NumOps = VT.getVectorNumElements();
3855   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3856     return false;
3857
3858   if (!isUndefOrEqual(Mask[0], 0))
3859     return false;
3860
3861   for (unsigned i = 1; i != NumOps; ++i)
3862     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3863           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3864           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3865       return false;
3866
3867   return true;
3868 }
3869
3870 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3871 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3872 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3873 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3874                            const X86Subtarget *Subtarget) {
3875   if (!Subtarget->hasSSE3())
3876     return false;
3877
3878   unsigned NumElems = VT.getVectorNumElements();
3879
3880   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3881       (VT.getSizeInBits() == 256 && NumElems != 8))
3882     return false;
3883
3884   // "i+1" is the value the indexed mask element must have
3885   for (unsigned i = 0; i != NumElems; i += 2)
3886     if (!isUndefOrEqual(Mask[i], i+1) ||
3887         !isUndefOrEqual(Mask[i+1], i+1))
3888       return false;
3889
3890   return true;
3891 }
3892
3893 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3895 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3896 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3897                            const X86Subtarget *Subtarget) {
3898   if (!Subtarget->hasSSE3())
3899     return false;
3900
3901   unsigned NumElems = VT.getVectorNumElements();
3902
3903   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3904       (VT.getSizeInBits() == 256 && NumElems != 8))
3905     return false;
3906
3907   // "i" is the value the indexed mask element must have
3908   for (unsigned i = 0; i != NumElems; i += 2)
3909     if (!isUndefOrEqual(Mask[i], i) ||
3910         !isUndefOrEqual(Mask[i+1], i))
3911       return false;
3912
3913   return true;
3914 }
3915
3916 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to 256-bit
3918 /// version of MOVDDUP.
3919 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3920   if (!HasAVX || !VT.is256BitVector())
3921     return false;
3922
3923   unsigned NumElts = VT.getVectorNumElements();
3924   if (NumElts != 4)
3925     return false;
3926
3927   for (unsigned i = 0; i != NumElts/2; ++i)
3928     if (!isUndefOrEqual(Mask[i], 0))
3929       return false;
3930   for (unsigned i = NumElts/2; i != NumElts; ++i)
3931     if (!isUndefOrEqual(Mask[i], NumElts/2))
3932       return false;
3933   return true;
3934 }
3935
3936 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to 128-bit
3938 /// version of MOVDDUP.
3939 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3940   if (!VT.is128BitVector())
3941     return false;
3942
3943   unsigned e = VT.getVectorNumElements() / 2;
3944   for (unsigned i = 0; i != e; ++i)
3945     if (!isUndefOrEqual(Mask[i], i))
3946       return false;
3947   for (unsigned i = 0; i != e; ++i)
3948     if (!isUndefOrEqual(Mask[e+i], i))
3949       return false;
3950   return true;
3951 }
3952
3953 /// isVEXTRACTF128Index - Return true if the specified
3954 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3955 /// suitable for input to VEXTRACTF128.
3956 bool X86::isVEXTRACTF128Index(SDNode *N) {
3957   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3958     return false;
3959
3960   // The index should be aligned on a 128-bit boundary.
3961   uint64_t Index =
3962     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3963
3964   unsigned VL = N->getValueType(0).getVectorNumElements();
3965   unsigned VBits = N->getValueType(0).getSizeInBits();
3966   unsigned ElSize = VBits / VL;
3967   bool Result = (Index * ElSize) % 128 == 0;
3968
3969   return Result;
3970 }
3971
3972 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3973 /// operand specifies a subvector insert that is suitable for input to
3974 /// VINSERTF128.
3975 bool X86::isVINSERTF128Index(SDNode *N) {
3976   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3977     return false;
3978
3979   // The index should be aligned on a 128-bit boundary.
3980   uint64_t Index =
3981     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3982
3983   unsigned VL = N->getValueType(0).getVectorNumElements();
3984   unsigned VBits = N->getValueType(0).getSizeInBits();
3985   unsigned ElSize = VBits / VL;
3986   bool Result = (Index * ElSize) % 128 == 0;
3987
3988   return Result;
3989 }
3990
3991 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3992 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3993 /// Handles 128-bit and 256-bit.
3994 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3995   EVT VT = N->getValueType(0);
3996
3997   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3998          "Unsupported vector type for PSHUF/SHUFP");
3999
4000   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4001   // independently on 128-bit lanes.
4002   unsigned NumElts = VT.getVectorNumElements();
4003   unsigned NumLanes = VT.getSizeInBits()/128;
4004   unsigned NumLaneElts = NumElts/NumLanes;
4005
4006   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4007          "Only supports 2 or 4 elements per lane");
4008
4009   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4010   unsigned Mask = 0;
4011   for (unsigned i = 0; i != NumElts; ++i) {
4012     int Elt = N->getMaskElt(i);
4013     if (Elt < 0) continue;
4014     Elt &= NumLaneElts - 1;
4015     unsigned ShAmt = (i << Shift) % 8;
4016     Mask |= Elt << ShAmt;
4017   }
4018
4019   return Mask;
4020 }
4021
4022 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4023 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4024 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4025   EVT VT = N->getValueType(0);
4026
4027   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4028          "Unsupported vector type for PSHUFHW");
4029
4030   unsigned NumElts = VT.getVectorNumElements();
4031
4032   unsigned Mask = 0;
4033   for (unsigned l = 0; l != NumElts; l += 8) {
4034     // 8 nodes per lane, but we only care about the last 4.
4035     for (unsigned i = 0; i < 4; ++i) {
4036       int Elt = N->getMaskElt(l+i+4);
4037       if (Elt < 0) continue;
4038       Elt &= 0x3; // only 2-bits.
4039       Mask |= Elt << (i * 2);
4040     }
4041   }
4042
4043   return Mask;
4044 }
4045
4046 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4047 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4048 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4049   EVT VT = N->getValueType(0);
4050
4051   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4052          "Unsupported vector type for PSHUFHW");
4053
4054   unsigned NumElts = VT.getVectorNumElements();
4055
4056   unsigned Mask = 0;
4057   for (unsigned l = 0; l != NumElts; l += 8) {
4058     // 8 nodes per lane, but we only care about the first 4.
4059     for (unsigned i = 0; i < 4; ++i) {
4060       int Elt = N->getMaskElt(l+i);
4061       if (Elt < 0) continue;
4062       Elt &= 0x3; // only 2-bits
4063       Mask |= Elt << (i * 2);
4064     }
4065   }
4066
4067   return Mask;
4068 }
4069
4070 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4071 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4072 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4073   EVT VT = SVOp->getValueType(0);
4074   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4075
4076   unsigned NumElts = VT.getVectorNumElements();
4077   unsigned NumLanes = VT.getSizeInBits()/128;
4078   unsigned NumLaneElts = NumElts/NumLanes;
4079
4080   int Val = 0;
4081   unsigned i;
4082   for (i = 0; i != NumElts; ++i) {
4083     Val = SVOp->getMaskElt(i);
4084     if (Val >= 0)
4085       break;
4086   }
4087   if (Val >= (int)NumElts)
4088     Val -= NumElts - NumLaneElts;
4089
4090   assert(Val - i > 0 && "PALIGNR imm should be positive");
4091   return (Val - i) * EltSize;
4092 }
4093
4094 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4095 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4096 /// instructions.
4097 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4098   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4099     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4100
4101   uint64_t Index =
4102     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4103
4104   EVT VecVT = N->getOperand(0).getValueType();
4105   EVT ElVT = VecVT.getVectorElementType();
4106
4107   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4108   return Index / NumElemsPerChunk;
4109 }
4110
4111 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4112 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4113 /// instructions.
4114 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4115   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4116     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4117
4118   uint64_t Index =
4119     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4120
4121   EVT VecVT = N->getValueType(0);
4122   EVT ElVT = VecVT.getVectorElementType();
4123
4124   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4125   return Index / NumElemsPerChunk;
4126 }
4127
4128 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4129 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4130 /// Handles 256-bit.
4131 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4132   EVT VT = N->getValueType(0);
4133
4134   unsigned NumElts = VT.getVectorNumElements();
4135
4136   assert((VT.is256BitVector() && NumElts == 4) &&
4137          "Unsupported vector type for VPERMQ/VPERMPD");
4138
4139   unsigned Mask = 0;
4140   for (unsigned i = 0; i != NumElts; ++i) {
4141     int Elt = N->getMaskElt(i);
4142     if (Elt < 0)
4143       continue;
4144     Mask |= Elt << (i*2);
4145   }
4146
4147   return Mask;
4148 }
4149 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4150 /// constant +0.0.
4151 bool X86::isZeroNode(SDValue Elt) {
4152   return ((isa<ConstantSDNode>(Elt) &&
4153            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4154           (isa<ConstantFPSDNode>(Elt) &&
4155            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4156 }
4157
4158 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4159 /// their permute mask.
4160 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4161                                     SelectionDAG &DAG) {
4162   EVT VT = SVOp->getValueType(0);
4163   unsigned NumElems = VT.getVectorNumElements();
4164   SmallVector<int, 8> MaskVec;
4165
4166   for (unsigned i = 0; i != NumElems; ++i) {
4167     int Idx = SVOp->getMaskElt(i);
4168     if (Idx >= 0) {
4169       if (Idx < (int)NumElems)
4170         Idx += NumElems;
4171       else
4172         Idx -= NumElems;
4173     }
4174     MaskVec.push_back(Idx);
4175   }
4176   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4177                               SVOp->getOperand(0), &MaskVec[0]);
4178 }
4179
4180 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4181 /// match movhlps. The lower half elements should come from upper half of
4182 /// V1 (and in order), and the upper half elements should come from the upper
4183 /// half of V2 (and in order).
4184 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4185   if (!VT.is128BitVector())
4186     return false;
4187   if (VT.getVectorNumElements() != 4)
4188     return false;
4189   for (unsigned i = 0, e = 2; i != e; ++i)
4190     if (!isUndefOrEqual(Mask[i], i+2))
4191       return false;
4192   for (unsigned i = 2; i != 4; ++i)
4193     if (!isUndefOrEqual(Mask[i], i+4))
4194       return false;
4195   return true;
4196 }
4197
4198 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4199 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4200 /// required.
4201 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4202   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4203     return false;
4204   N = N->getOperand(0).getNode();
4205   if (!ISD::isNON_EXTLoad(N))
4206     return false;
4207   if (LD)
4208     *LD = cast<LoadSDNode>(N);
4209   return true;
4210 }
4211
4212 // Test whether the given value is a vector value which will be legalized
4213 // into a load.
4214 static bool WillBeConstantPoolLoad(SDNode *N) {
4215   if (N->getOpcode() != ISD::BUILD_VECTOR)
4216     return false;
4217
4218   // Check for any non-constant elements.
4219   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4220     switch (N->getOperand(i).getNode()->getOpcode()) {
4221     case ISD::UNDEF:
4222     case ISD::ConstantFP:
4223     case ISD::Constant:
4224       break;
4225     default:
4226       return false;
4227     }
4228
4229   // Vectors of all-zeros and all-ones are materialized with special
4230   // instructions rather than being loaded.
4231   return !ISD::isBuildVectorAllZeros(N) &&
4232          !ISD::isBuildVectorAllOnes(N);
4233 }
4234
4235 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4236 /// match movlp{s|d}. The lower half elements should come from lower half of
4237 /// V1 (and in order), and the upper half elements should come from the upper
4238 /// half of V2 (and in order). And since V1 will become the source of the
4239 /// MOVLP, it must be either a vector load or a scalar load to vector.
4240 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4241                                ArrayRef<int> Mask, EVT VT) {
4242   if (!VT.is128BitVector())
4243     return false;
4244
4245   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4246     return false;
4247   // Is V2 is a vector load, don't do this transformation. We will try to use
4248   // load folding shufps op.
4249   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4250     return false;
4251
4252   unsigned NumElems = VT.getVectorNumElements();
4253
4254   if (NumElems != 2 && NumElems != 4)
4255     return false;
4256   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4257     if (!isUndefOrEqual(Mask[i], i))
4258       return false;
4259   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4260     if (!isUndefOrEqual(Mask[i], i+NumElems))
4261       return false;
4262   return true;
4263 }
4264
4265 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4266 /// all the same.
4267 static bool isSplatVector(SDNode *N) {
4268   if (N->getOpcode() != ISD::BUILD_VECTOR)
4269     return false;
4270
4271   SDValue SplatValue = N->getOperand(0);
4272   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4273     if (N->getOperand(i) != SplatValue)
4274       return false;
4275   return true;
4276 }
4277
4278 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4279 /// to an zero vector.
4280 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4281 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4282   SDValue V1 = N->getOperand(0);
4283   SDValue V2 = N->getOperand(1);
4284   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4285   for (unsigned i = 0; i != NumElems; ++i) {
4286     int Idx = N->getMaskElt(i);
4287     if (Idx >= (int)NumElems) {
4288       unsigned Opc = V2.getOpcode();
4289       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4290         continue;
4291       if (Opc != ISD::BUILD_VECTOR ||
4292           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4293         return false;
4294     } else if (Idx >= 0) {
4295       unsigned Opc = V1.getOpcode();
4296       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4297         continue;
4298       if (Opc != ISD::BUILD_VECTOR ||
4299           !X86::isZeroNode(V1.getOperand(Idx)))
4300         return false;
4301     }
4302   }
4303   return true;
4304 }
4305
4306 /// getZeroVector - Returns a vector of specified type with all zero elements.
4307 ///
4308 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4309                              SelectionDAG &DAG, DebugLoc dl) {
4310   assert(VT.isVector() && "Expected a vector type");
4311   unsigned Size = VT.getSizeInBits();
4312
4313   // Always build SSE zero vectors as <4 x i32> bitcasted
4314   // to their dest type. This ensures they get CSE'd.
4315   SDValue Vec;
4316   if (Size == 128) {  // SSE
4317     if (Subtarget->hasSSE2()) {  // SSE2
4318       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4319       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4320     } else { // SSE1
4321       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4322       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4323     }
4324   } else if (Size == 256) { // AVX
4325     if (Subtarget->hasAVX2()) { // AVX2
4326       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4327       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4328       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4329     } else {
4330       // 256-bit logic and arithmetic instructions in AVX are all
4331       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4332       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4333       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4335     }
4336   } else
4337     llvm_unreachable("Unexpected vector type");
4338
4339   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4340 }
4341
4342 /// getOnesVector - Returns a vector of specified type with all bits set.
4343 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4344 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4345 /// Then bitcast to their original type, ensuring they get CSE'd.
4346 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4347                              DebugLoc dl) {
4348   assert(VT.isVector() && "Expected a vector type");
4349   unsigned Size = VT.getSizeInBits();
4350
4351   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4352   SDValue Vec;
4353   if (Size == 256) {
4354     if (HasAVX2) { // AVX2
4355       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4356       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4357     } else { // AVX
4358       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4359       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4360     }
4361   } else if (Size == 128) {
4362     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4363   } else
4364     llvm_unreachable("Unexpected vector type");
4365
4366   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4367 }
4368
4369 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4370 /// that point to V2 points to its first element.
4371 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4372   for (unsigned i = 0; i != NumElems; ++i) {
4373     if (Mask[i] > (int)NumElems) {
4374       Mask[i] = NumElems;
4375     }
4376   }
4377 }
4378
4379 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4380 /// operation of specified width.
4381 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4382                        SDValue V2) {
4383   unsigned NumElems = VT.getVectorNumElements();
4384   SmallVector<int, 8> Mask;
4385   Mask.push_back(NumElems);
4386   for (unsigned i = 1; i != NumElems; ++i)
4387     Mask.push_back(i);
4388   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4389 }
4390
4391 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4392 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4393                           SDValue V2) {
4394   unsigned NumElems = VT.getVectorNumElements();
4395   SmallVector<int, 8> Mask;
4396   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4397     Mask.push_back(i);
4398     Mask.push_back(i + NumElems);
4399   }
4400   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4401 }
4402
4403 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4404 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4405                           SDValue V2) {
4406   unsigned NumElems = VT.getVectorNumElements();
4407   SmallVector<int, 8> Mask;
4408   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4409     Mask.push_back(i + Half);
4410     Mask.push_back(i + NumElems + Half);
4411   }
4412   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4413 }
4414
4415 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4416 // a generic shuffle instruction because the target has no such instructions.
4417 // Generate shuffles which repeat i16 and i8 several times until they can be
4418 // represented by v4f32 and then be manipulated by target suported shuffles.
4419 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4420   EVT VT = V.getValueType();
4421   int NumElems = VT.getVectorNumElements();
4422   DebugLoc dl = V.getDebugLoc();
4423
4424   while (NumElems > 4) {
4425     if (EltNo < NumElems/2) {
4426       V = getUnpackl(DAG, dl, VT, V, V);
4427     } else {
4428       V = getUnpackh(DAG, dl, VT, V, V);
4429       EltNo -= NumElems/2;
4430     }
4431     NumElems >>= 1;
4432   }
4433   return V;
4434 }
4435
4436 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4437 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4438   EVT VT = V.getValueType();
4439   DebugLoc dl = V.getDebugLoc();
4440   unsigned Size = VT.getSizeInBits();
4441
4442   if (Size == 128) {
4443     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4444     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4445     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4446                              &SplatMask[0]);
4447   } else if (Size == 256) {
4448     // To use VPERMILPS to splat scalars, the second half of indicies must
4449     // refer to the higher part, which is a duplication of the lower one,
4450     // because VPERMILPS can only handle in-lane permutations.
4451     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4452                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4453
4454     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4455     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4456                              &SplatMask[0]);
4457   } else
4458     llvm_unreachable("Vector size not supported");
4459
4460   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4461 }
4462
4463 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4464 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4465   EVT SrcVT = SV->getValueType(0);
4466   SDValue V1 = SV->getOperand(0);
4467   DebugLoc dl = SV->getDebugLoc();
4468
4469   int EltNo = SV->getSplatIndex();
4470   int NumElems = SrcVT.getVectorNumElements();
4471   unsigned Size = SrcVT.getSizeInBits();
4472
4473   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4474           "Unknown how to promote splat for type");
4475
4476   // Extract the 128-bit part containing the splat element and update
4477   // the splat element index when it refers to the higher register.
4478   if (Size == 256) {
4479     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4480     if (EltNo >= NumElems/2)
4481       EltNo -= NumElems/2;
4482   }
4483
4484   // All i16 and i8 vector types can't be used directly by a generic shuffle
4485   // instruction because the target has no such instruction. Generate shuffles
4486   // which repeat i16 and i8 several times until they fit in i32, and then can
4487   // be manipulated by target suported shuffles.
4488   EVT EltVT = SrcVT.getVectorElementType();
4489   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4490     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4491
4492   // Recreate the 256-bit vector and place the same 128-bit vector
4493   // into the low and high part. This is necessary because we want
4494   // to use VPERM* to shuffle the vectors
4495   if (Size == 256) {
4496     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4497   }
4498
4499   return getLegalSplat(DAG, V1, EltNo);
4500 }
4501
4502 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4503 /// vector of zero or undef vector.  This produces a shuffle where the low
4504 /// element of V2 is swizzled into the zero/undef vector, landing at element
4505 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4506 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4507                                            bool IsZero,
4508                                            const X86Subtarget *Subtarget,
4509                                            SelectionDAG &DAG) {
4510   EVT VT = V2.getValueType();
4511   SDValue V1 = IsZero
4512     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4513   unsigned NumElems = VT.getVectorNumElements();
4514   SmallVector<int, 16> MaskVec;
4515   for (unsigned i = 0; i != NumElems; ++i)
4516     // If this is the insertion idx, put the low elt of V2 here.
4517     MaskVec.push_back(i == Idx ? NumElems : i);
4518   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4519 }
4520
4521 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4522 /// target specific opcode. Returns true if the Mask could be calculated.
4523 /// Sets IsUnary to true if only uses one source.
4524 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4525                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4526   unsigned NumElems = VT.getVectorNumElements();
4527   SDValue ImmN;
4528
4529   IsUnary = false;
4530   switch(N->getOpcode()) {
4531   case X86ISD::SHUFP:
4532     ImmN = N->getOperand(N->getNumOperands()-1);
4533     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534     break;
4535   case X86ISD::UNPCKH:
4536     DecodeUNPCKHMask(VT, Mask);
4537     break;
4538   case X86ISD::UNPCKL:
4539     DecodeUNPCKLMask(VT, Mask);
4540     break;
4541   case X86ISD::MOVHLPS:
4542     DecodeMOVHLPSMask(NumElems, Mask);
4543     break;
4544   case X86ISD::MOVLHPS:
4545     DecodeMOVLHPSMask(NumElems, Mask);
4546     break;
4547   case X86ISD::PSHUFD:
4548   case X86ISD::VPERMILP:
4549     ImmN = N->getOperand(N->getNumOperands()-1);
4550     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551     IsUnary = true;
4552     break;
4553   case X86ISD::PSHUFHW:
4554     ImmN = N->getOperand(N->getNumOperands()-1);
4555     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4556     IsUnary = true;
4557     break;
4558   case X86ISD::PSHUFLW:
4559     ImmN = N->getOperand(N->getNumOperands()-1);
4560     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4561     IsUnary = true;
4562     break;
4563   case X86ISD::VPERMI:
4564     ImmN = N->getOperand(N->getNumOperands()-1);
4565     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4566     IsUnary = true;
4567     break;
4568   case X86ISD::MOVSS:
4569   case X86ISD::MOVSD: {
4570     // The index 0 always comes from the first element of the second source,
4571     // this is why MOVSS and MOVSD are used in the first place. The other
4572     // elements come from the other positions of the first source vector
4573     Mask.push_back(NumElems);
4574     for (unsigned i = 1; i != NumElems; ++i) {
4575       Mask.push_back(i);
4576     }
4577     break;
4578   }
4579   case X86ISD::VPERM2X128:
4580     ImmN = N->getOperand(N->getNumOperands()-1);
4581     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4582     if (Mask.empty()) return false;
4583     break;
4584   case X86ISD::MOVDDUP:
4585   case X86ISD::MOVLHPD:
4586   case X86ISD::MOVLPD:
4587   case X86ISD::MOVLPS:
4588   case X86ISD::MOVSHDUP:
4589   case X86ISD::MOVSLDUP:
4590   case X86ISD::PALIGN:
4591     // Not yet implemented
4592     return false;
4593   default: llvm_unreachable("unknown target shuffle node");
4594   }
4595
4596   return true;
4597 }
4598
4599 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4600 /// element of the result of the vector shuffle.
4601 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4602                                    unsigned Depth) {
4603   if (Depth == 6)
4604     return SDValue();  // Limit search depth.
4605
4606   SDValue V = SDValue(N, 0);
4607   EVT VT = V.getValueType();
4608   unsigned Opcode = V.getOpcode();
4609
4610   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4611   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4612     int Elt = SV->getMaskElt(Index);
4613
4614     if (Elt < 0)
4615       return DAG.getUNDEF(VT.getVectorElementType());
4616
4617     unsigned NumElems = VT.getVectorNumElements();
4618     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4619                                          : SV->getOperand(1);
4620     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4621   }
4622
4623   // Recurse into target specific vector shuffles to find scalars.
4624   if (isTargetShuffle(Opcode)) {
4625     MVT ShufVT = V.getValueType().getSimpleVT();
4626     unsigned NumElems = ShufVT.getVectorNumElements();
4627     SmallVector<int, 16> ShuffleMask;
4628     SDValue ImmN;
4629     bool IsUnary;
4630
4631     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4632       return SDValue();
4633
4634     int Elt = ShuffleMask[Index];
4635     if (Elt < 0)
4636       return DAG.getUNDEF(ShufVT.getVectorElementType());
4637
4638     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4639                                          : N->getOperand(1);
4640     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4641                                Depth+1);
4642   }
4643
4644   // Actual nodes that may contain scalar elements
4645   if (Opcode == ISD::BITCAST) {
4646     V = V.getOperand(0);
4647     EVT SrcVT = V.getValueType();
4648     unsigned NumElems = VT.getVectorNumElements();
4649
4650     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4651       return SDValue();
4652   }
4653
4654   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4655     return (Index == 0) ? V.getOperand(0)
4656                         : DAG.getUNDEF(VT.getVectorElementType());
4657
4658   if (V.getOpcode() == ISD::BUILD_VECTOR)
4659     return V.getOperand(Index);
4660
4661   return SDValue();
4662 }
4663
4664 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4665 /// shuffle operation which come from a consecutively from a zero. The
4666 /// search can start in two different directions, from left or right.
4667 static
4668 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4669                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4670   unsigned i;
4671   for (i = 0; i != NumElems; ++i) {
4672     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4673     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4674     if (!(Elt.getNode() &&
4675          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4676       break;
4677   }
4678
4679   return i;
4680 }
4681
4682 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4683 /// correspond consecutively to elements from one of the vector operands,
4684 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4685 static
4686 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4687                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4688                               unsigned NumElems, unsigned &OpNum) {
4689   bool SeenV1 = false;
4690   bool SeenV2 = false;
4691
4692   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4693     int Idx = SVOp->getMaskElt(i);
4694     // Ignore undef indicies
4695     if (Idx < 0)
4696       continue;
4697
4698     if (Idx < (int)NumElems)
4699       SeenV1 = true;
4700     else
4701       SeenV2 = true;
4702
4703     // Only accept consecutive elements from the same vector
4704     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4705       return false;
4706   }
4707
4708   OpNum = SeenV1 ? 0 : 1;
4709   return true;
4710 }
4711
4712 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4713 /// logical left shift of a vector.
4714 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4715                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4716   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4717   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4718               false /* check zeros from right */, DAG);
4719   unsigned OpSrc;
4720
4721   if (!NumZeros)
4722     return false;
4723
4724   // Considering the elements in the mask that are not consecutive zeros,
4725   // check if they consecutively come from only one of the source vectors.
4726   //
4727   //               V1 = {X, A, B, C}     0
4728   //                         \  \  \    /
4729   //   vector_shuffle V1, V2 <1, 2, 3, X>
4730   //
4731   if (!isShuffleMaskConsecutive(SVOp,
4732             0,                   // Mask Start Index
4733             NumElems-NumZeros,   // Mask End Index(exclusive)
4734             NumZeros,            // Where to start looking in the src vector
4735             NumElems,            // Number of elements in vector
4736             OpSrc))              // Which source operand ?
4737     return false;
4738
4739   isLeft = false;
4740   ShAmt = NumZeros;
4741   ShVal = SVOp->getOperand(OpSrc);
4742   return true;
4743 }
4744
4745 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4746 /// logical left shift of a vector.
4747 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4748                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4749   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4750   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4751               true /* check zeros from left */, DAG);
4752   unsigned OpSrc;
4753
4754   if (!NumZeros)
4755     return false;
4756
4757   // Considering the elements in the mask that are not consecutive zeros,
4758   // check if they consecutively come from only one of the source vectors.
4759   //
4760   //                           0    { A, B, X, X } = V2
4761   //                          / \    /  /
4762   //   vector_shuffle V1, V2 <X, X, 4, 5>
4763   //
4764   if (!isShuffleMaskConsecutive(SVOp,
4765             NumZeros,     // Mask Start Index
4766             NumElems,     // Mask End Index(exclusive)
4767             0,            // Where to start looking in the src vector
4768             NumElems,     // Number of elements in vector
4769             OpSrc))       // Which source operand ?
4770     return false;
4771
4772   isLeft = true;
4773   ShAmt = NumZeros;
4774   ShVal = SVOp->getOperand(OpSrc);
4775   return true;
4776 }
4777
4778 /// isVectorShift - Returns true if the shuffle can be implemented as a
4779 /// logical left or right shift of a vector.
4780 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4781                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4782   // Although the logic below support any bitwidth size, there are no
4783   // shift instructions which handle more than 128-bit vectors.
4784   if (!SVOp->getValueType(0).is128BitVector())
4785     return false;
4786
4787   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4788       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4789     return true;
4790
4791   return false;
4792 }
4793
4794 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4795 ///
4796 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4797                                        unsigned NumNonZero, unsigned NumZero,
4798                                        SelectionDAG &DAG,
4799                                        const X86Subtarget* Subtarget,
4800                                        const TargetLowering &TLI) {
4801   if (NumNonZero > 8)
4802     return SDValue();
4803
4804   DebugLoc dl = Op.getDebugLoc();
4805   SDValue V(0, 0);
4806   bool First = true;
4807   for (unsigned i = 0; i < 16; ++i) {
4808     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4809     if (ThisIsNonZero && First) {
4810       if (NumZero)
4811         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4812       else
4813         V = DAG.getUNDEF(MVT::v8i16);
4814       First = false;
4815     }
4816
4817     if ((i & 1) != 0) {
4818       SDValue ThisElt(0, 0), LastElt(0, 0);
4819       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4820       if (LastIsNonZero) {
4821         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4822                               MVT::i16, Op.getOperand(i-1));
4823       }
4824       if (ThisIsNonZero) {
4825         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4826         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4827                               ThisElt, DAG.getConstant(8, MVT::i8));
4828         if (LastIsNonZero)
4829           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4830       } else
4831         ThisElt = LastElt;
4832
4833       if (ThisElt.getNode())
4834         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4835                         DAG.getIntPtrConstant(i/2));
4836     }
4837   }
4838
4839   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4840 }
4841
4842 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4843 ///
4844 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4845                                      unsigned NumNonZero, unsigned NumZero,
4846                                      SelectionDAG &DAG,
4847                                      const X86Subtarget* Subtarget,
4848                                      const TargetLowering &TLI) {
4849   if (NumNonZero > 4)
4850     return SDValue();
4851
4852   DebugLoc dl = Op.getDebugLoc();
4853   SDValue V(0, 0);
4854   bool First = true;
4855   for (unsigned i = 0; i < 8; ++i) {
4856     bool isNonZero = (NonZeros & (1 << i)) != 0;
4857     if (isNonZero) {
4858       if (First) {
4859         if (NumZero)
4860           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4861         else
4862           V = DAG.getUNDEF(MVT::v8i16);
4863         First = false;
4864       }
4865       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4866                       MVT::v8i16, V, Op.getOperand(i),
4867                       DAG.getIntPtrConstant(i));
4868     }
4869   }
4870
4871   return V;
4872 }
4873
4874 /// getVShift - Return a vector logical shift node.
4875 ///
4876 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4877                          unsigned NumBits, SelectionDAG &DAG,
4878                          const TargetLowering &TLI, DebugLoc dl) {
4879   assert(VT.is128BitVector() && "Unknown type for VShift");
4880   EVT ShVT = MVT::v2i64;
4881   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4882   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4883   return DAG.getNode(ISD::BITCAST, dl, VT,
4884                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4885                              DAG.getConstant(NumBits,
4886                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4887 }
4888
4889 SDValue
4890 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4891                                           SelectionDAG &DAG) const {
4892
4893   // Check if the scalar load can be widened into a vector load. And if
4894   // the address is "base + cst" see if the cst can be "absorbed" into
4895   // the shuffle mask.
4896   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4897     SDValue Ptr = LD->getBasePtr();
4898     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4899       return SDValue();
4900     EVT PVT = LD->getValueType(0);
4901     if (PVT != MVT::i32 && PVT != MVT::f32)
4902       return SDValue();
4903
4904     int FI = -1;
4905     int64_t Offset = 0;
4906     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4907       FI = FINode->getIndex();
4908       Offset = 0;
4909     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4910                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4911       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4912       Offset = Ptr.getConstantOperandVal(1);
4913       Ptr = Ptr.getOperand(0);
4914     } else {
4915       return SDValue();
4916     }
4917
4918     // FIXME: 256-bit vector instructions don't require a strict alignment,
4919     // improve this code to support it better.
4920     unsigned RequiredAlign = VT.getSizeInBits()/8;
4921     SDValue Chain = LD->getChain();
4922     // Make sure the stack object alignment is at least 16 or 32.
4923     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4924     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4925       if (MFI->isFixedObjectIndex(FI)) {
4926         // Can't change the alignment. FIXME: It's possible to compute
4927         // the exact stack offset and reference FI + adjust offset instead.
4928         // If someone *really* cares about this. That's the way to implement it.
4929         return SDValue();
4930       } else {
4931         MFI->setObjectAlignment(FI, RequiredAlign);
4932       }
4933     }
4934
4935     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4936     // Ptr + (Offset & ~15).
4937     if (Offset < 0)
4938       return SDValue();
4939     if ((Offset % RequiredAlign) & 3)
4940       return SDValue();
4941     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4942     if (StartOffset)
4943       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4944                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4945
4946     int EltNo = (Offset - StartOffset) >> 2;
4947     unsigned NumElems = VT.getVectorNumElements();
4948
4949     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4950     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4951                              LD->getPointerInfo().getWithOffset(StartOffset),
4952                              false, false, false, 0);
4953
4954     SmallVector<int, 8> Mask;
4955     for (unsigned i = 0; i != NumElems; ++i)
4956       Mask.push_back(EltNo);
4957
4958     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4959   }
4960
4961   return SDValue();
4962 }
4963
4964 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4965 /// vector of type 'VT', see if the elements can be replaced by a single large
4966 /// load which has the same value as a build_vector whose operands are 'elts'.
4967 ///
4968 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4969 ///
4970 /// FIXME: we'd also like to handle the case where the last elements are zero
4971 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4972 /// There's even a handy isZeroNode for that purpose.
4973 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4974                                         DebugLoc &DL, SelectionDAG &DAG) {
4975   EVT EltVT = VT.getVectorElementType();
4976   unsigned NumElems = Elts.size();
4977
4978   LoadSDNode *LDBase = NULL;
4979   unsigned LastLoadedElt = -1U;
4980
4981   // For each element in the initializer, see if we've found a load or an undef.
4982   // If we don't find an initial load element, or later load elements are
4983   // non-consecutive, bail out.
4984   for (unsigned i = 0; i < NumElems; ++i) {
4985     SDValue Elt = Elts[i];
4986
4987     if (!Elt.getNode() ||
4988         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4989       return SDValue();
4990     if (!LDBase) {
4991       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4992         return SDValue();
4993       LDBase = cast<LoadSDNode>(Elt.getNode());
4994       LastLoadedElt = i;
4995       continue;
4996     }
4997     if (Elt.getOpcode() == ISD::UNDEF)
4998       continue;
4999
5000     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5001     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5002       return SDValue();
5003     LastLoadedElt = i;
5004   }
5005
5006   // If we have found an entire vector of loads and undefs, then return a large
5007   // load of the entire vector width starting at the base pointer.  If we found
5008   // consecutive loads for the low half, generate a vzext_load node.
5009   if (LastLoadedElt == NumElems - 1) {
5010     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5011       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5012                          LDBase->getPointerInfo(),
5013                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5014                          LDBase->isInvariant(), 0);
5015     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5016                        LDBase->getPointerInfo(),
5017                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5018                        LDBase->isInvariant(), LDBase->getAlignment());
5019   }
5020   if (NumElems == 4 && LastLoadedElt == 1 &&
5021       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5022     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5023     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5024     SDValue ResNode =
5025         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5026                                 LDBase->getPointerInfo(),
5027                                 LDBase->getAlignment(),
5028                                 false/*isVolatile*/, true/*ReadMem*/,
5029                                 false/*WriteMem*/);
5030
5031     // Make sure the newly-created LOAD is in the same position as LDBase in
5032     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5033     // update uses of LDBase's output chain to use the TokenFactor.
5034     if (LDBase->hasAnyUseOfValue(1)) {
5035       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5036                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5037       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5038       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5039                              SDValue(ResNode.getNode(), 1));
5040     }
5041
5042     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5043   }
5044   return SDValue();
5045 }
5046
5047 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5048 /// to generate a splat value for the following cases:
5049 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5050 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5051 /// a scalar load, or a constant.
5052 /// The VBROADCAST node is returned when a pattern is found,
5053 /// or SDValue() otherwise.
5054 SDValue
5055 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5056   if (!Subtarget->hasAVX())
5057     return SDValue();
5058
5059   EVT VT = Op.getValueType();
5060   DebugLoc dl = Op.getDebugLoc();
5061
5062   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5063          "Unsupported vector type for broadcast.");
5064
5065   SDValue Ld;
5066   bool ConstSplatVal;
5067
5068   switch (Op.getOpcode()) {
5069     default:
5070       // Unknown pattern found.
5071       return SDValue();
5072
5073     case ISD::BUILD_VECTOR: {
5074       // The BUILD_VECTOR node must be a splat.
5075       if (!isSplatVector(Op.getNode()))
5076         return SDValue();
5077
5078       Ld = Op.getOperand(0);
5079       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5080                      Ld.getOpcode() == ISD::ConstantFP);
5081
5082       // The suspected load node has several users. Make sure that all
5083       // of its users are from the BUILD_VECTOR node.
5084       // Constants may have multiple users.
5085       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5086         return SDValue();
5087       break;
5088     }
5089
5090     case ISD::VECTOR_SHUFFLE: {
5091       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5092
5093       // Shuffles must have a splat mask where the first element is
5094       // broadcasted.
5095       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5096         return SDValue();
5097
5098       SDValue Sc = Op.getOperand(0);
5099       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5100           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5101
5102         if (!Subtarget->hasAVX2())
5103           return SDValue();
5104
5105         // Use the register form of the broadcast instruction available on AVX2.
5106         if (VT.is256BitVector())
5107           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5108         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5109       }
5110
5111       Ld = Sc.getOperand(0);
5112       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5113                        Ld.getOpcode() == ISD::ConstantFP);
5114
5115       // The scalar_to_vector node and the suspected
5116       // load node must have exactly one user.
5117       // Constants may have multiple users.
5118       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5119         return SDValue();
5120       break;
5121     }
5122   }
5123
5124   bool Is256 = VT.is256BitVector();
5125
5126   // Handle the broadcasting a single constant scalar from the constant pool
5127   // into a vector. On Sandybridge it is still better to load a constant vector
5128   // from the constant pool and not to broadcast it from a scalar.
5129   if (ConstSplatVal && Subtarget->hasAVX2()) {
5130     EVT CVT = Ld.getValueType();
5131     assert(!CVT.isVector() && "Must not broadcast a vector type");
5132     unsigned ScalarSize = CVT.getSizeInBits();
5133
5134     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5135       const Constant *C = 0;
5136       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5137         C = CI->getConstantIntValue();
5138       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5139         C = CF->getConstantFPValue();
5140
5141       assert(C && "Invalid constant type");
5142
5143       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5144       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5145       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5146                        MachinePointerInfo::getConstantPool(),
5147                        false, false, false, Alignment);
5148
5149       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5150     }
5151   }
5152
5153   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5154   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5155
5156   // Handle AVX2 in-register broadcasts.
5157   if (!IsLoad && Subtarget->hasAVX2() &&
5158       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5159     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5160
5161   // The scalar source must be a normal load.
5162   if (!IsLoad)
5163     return SDValue();
5164
5165   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5166     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5167
5168   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5169   // double since there is no vbroadcastsd xmm
5170   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5171     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5172       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5173   }
5174
5175   // Unsupported broadcast.
5176   return SDValue();
5177 }
5178
5179 SDValue
5180 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5181   EVT VT = Op.getValueType();
5182
5183   // Skip if insert_vec_elt is not supported.
5184   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5185     return SDValue();
5186
5187   DebugLoc DL = Op.getDebugLoc();
5188   unsigned NumElems = Op.getNumOperands();
5189
5190   SDValue VecIn1;
5191   SDValue VecIn2;
5192   SmallVector<unsigned, 4> InsertIndices;
5193   SmallVector<int, 8> Mask(NumElems, -1);
5194
5195   for (unsigned i = 0; i != NumElems; ++i) {
5196     unsigned Opc = Op.getOperand(i).getOpcode();
5197
5198     if (Opc == ISD::UNDEF)
5199       continue;
5200
5201     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5202       // Quit if more than 1 elements need inserting.
5203       if (InsertIndices.size() > 1)
5204         return SDValue();
5205
5206       InsertIndices.push_back(i);
5207       continue;
5208     }
5209
5210     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5211     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5212
5213     // Quit if extracted from vector of different type.
5214     if (ExtractedFromVec.getValueType() != VT)
5215       return SDValue();
5216
5217     // Quit if non-constant index.
5218     if (!isa<ConstantSDNode>(ExtIdx))
5219       return SDValue();
5220
5221     if (VecIn1.getNode() == 0)
5222       VecIn1 = ExtractedFromVec;
5223     else if (VecIn1 != ExtractedFromVec) {
5224       if (VecIn2.getNode() == 0)
5225         VecIn2 = ExtractedFromVec;
5226       else if (VecIn2 != ExtractedFromVec)
5227         // Quit if more than 2 vectors to shuffle
5228         return SDValue();
5229     }
5230
5231     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5232
5233     if (ExtractedFromVec == VecIn1)
5234       Mask[i] = Idx;
5235     else if (ExtractedFromVec == VecIn2)
5236       Mask[i] = Idx + NumElems;
5237   }
5238
5239   if (VecIn1.getNode() == 0)
5240     return SDValue();
5241
5242   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5243   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5244   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5245     unsigned Idx = InsertIndices[i];
5246     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5247                      DAG.getIntPtrConstant(Idx));
5248   }
5249
5250   return NV;
5251 }
5252
5253 SDValue
5254 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5255   DebugLoc dl = Op.getDebugLoc();
5256
5257   EVT VT = Op.getValueType();
5258   EVT ExtVT = VT.getVectorElementType();
5259   unsigned NumElems = Op.getNumOperands();
5260
5261   // Vectors containing all zeros can be matched by pxor and xorps later
5262   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5263     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5264     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5265     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5266       return Op;
5267
5268     return getZeroVector(VT, Subtarget, DAG, dl);
5269   }
5270
5271   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5272   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5273   // vpcmpeqd on 256-bit vectors.
5274   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5275     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5276       return Op;
5277
5278     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5279   }
5280
5281   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5282   if (Broadcast.getNode())
5283     return Broadcast;
5284
5285   unsigned EVTBits = ExtVT.getSizeInBits();
5286
5287   unsigned NumZero  = 0;
5288   unsigned NumNonZero = 0;
5289   unsigned NonZeros = 0;
5290   bool IsAllConstants = true;
5291   SmallSet<SDValue, 8> Values;
5292   for (unsigned i = 0; i < NumElems; ++i) {
5293     SDValue Elt = Op.getOperand(i);
5294     if (Elt.getOpcode() == ISD::UNDEF)
5295       continue;
5296     Values.insert(Elt);
5297     if (Elt.getOpcode() != ISD::Constant &&
5298         Elt.getOpcode() != ISD::ConstantFP)
5299       IsAllConstants = false;
5300     if (X86::isZeroNode(Elt))
5301       NumZero++;
5302     else {
5303       NonZeros |= (1 << i);
5304       NumNonZero++;
5305     }
5306   }
5307
5308   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5309   if (NumNonZero == 0)
5310     return DAG.getUNDEF(VT);
5311
5312   // Special case for single non-zero, non-undef, element.
5313   if (NumNonZero == 1) {
5314     unsigned Idx = CountTrailingZeros_32(NonZeros);
5315     SDValue Item = Op.getOperand(Idx);
5316
5317     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5318     // the value are obviously zero, truncate the value to i32 and do the
5319     // insertion that way.  Only do this if the value is non-constant or if the
5320     // value is a constant being inserted into element 0.  It is cheaper to do
5321     // a constant pool load than it is to do a movd + shuffle.
5322     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5323         (!IsAllConstants || Idx == 0)) {
5324       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5325         // Handle SSE only.
5326         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5327         EVT VecVT = MVT::v4i32;
5328         unsigned VecElts = 4;
5329
5330         // Truncate the value (which may itself be a constant) to i32, and
5331         // convert it to a vector with movd (S2V+shuffle to zero extend).
5332         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5333         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5334         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5335
5336         // Now we have our 32-bit value zero extended in the low element of
5337         // a vector.  If Idx != 0, swizzle it into place.
5338         if (Idx != 0) {
5339           SmallVector<int, 4> Mask;
5340           Mask.push_back(Idx);
5341           for (unsigned i = 1; i != VecElts; ++i)
5342             Mask.push_back(i);
5343           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5344                                       &Mask[0]);
5345         }
5346         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5347       }
5348     }
5349
5350     // If we have a constant or non-constant insertion into the low element of
5351     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5352     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5353     // depending on what the source datatype is.
5354     if (Idx == 0) {
5355       if (NumZero == 0)
5356         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5357
5358       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5359           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5360         if (VT.is256BitVector()) {
5361           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5362           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5363                              Item, DAG.getIntPtrConstant(0));
5364         }
5365         assert(VT.is128BitVector() && "Expected an SSE value type!");
5366         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5368         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5369       }
5370
5371       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5372         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5373         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5374         if (VT.is256BitVector()) {
5375           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5376           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5377         } else {
5378           assert(VT.is128BitVector() && "Expected an SSE value type!");
5379           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5380         }
5381         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5382       }
5383     }
5384
5385     // Is it a vector logical left shift?
5386     if (NumElems == 2 && Idx == 1 &&
5387         X86::isZeroNode(Op.getOperand(0)) &&
5388         !X86::isZeroNode(Op.getOperand(1))) {
5389       unsigned NumBits = VT.getSizeInBits();
5390       return getVShift(true, VT,
5391                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5392                                    VT, Op.getOperand(1)),
5393                        NumBits/2, DAG, *this, dl);
5394     }
5395
5396     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5397       return SDValue();
5398
5399     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5400     // is a non-constant being inserted into an element other than the low one,
5401     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5402     // movd/movss) to move this into the low element, then shuffle it into
5403     // place.
5404     if (EVTBits == 32) {
5405       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5406
5407       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5408       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5409       SmallVector<int, 8> MaskVec;
5410       for (unsigned i = 0; i != NumElems; ++i)
5411         MaskVec.push_back(i == Idx ? 0 : 1);
5412       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5413     }
5414   }
5415
5416   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5417   if (Values.size() == 1) {
5418     if (EVTBits == 32) {
5419       // Instead of a shuffle like this:
5420       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5421       // Check if it's possible to issue this instead.
5422       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5423       unsigned Idx = CountTrailingZeros_32(NonZeros);
5424       SDValue Item = Op.getOperand(Idx);
5425       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5426         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5427     }
5428     return SDValue();
5429   }
5430
5431   // A vector full of immediates; various special cases are already
5432   // handled, so this is best done with a single constant-pool load.
5433   if (IsAllConstants)
5434     return SDValue();
5435
5436   // For AVX-length vectors, build the individual 128-bit pieces and use
5437   // shuffles to put them in place.
5438   if (VT.is256BitVector()) {
5439     SmallVector<SDValue, 32> V;
5440     for (unsigned i = 0; i != NumElems; ++i)
5441       V.push_back(Op.getOperand(i));
5442
5443     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5444
5445     // Build both the lower and upper subvector.
5446     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5447     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5448                                 NumElems/2);
5449
5450     // Recreate the wider vector with the lower and upper part.
5451     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5452   }
5453
5454   // Let legalizer expand 2-wide build_vectors.
5455   if (EVTBits == 64) {
5456     if (NumNonZero == 1) {
5457       // One half is zero or undef.
5458       unsigned Idx = CountTrailingZeros_32(NonZeros);
5459       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5460                                  Op.getOperand(Idx));
5461       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5462     }
5463     return SDValue();
5464   }
5465
5466   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5467   if (EVTBits == 8 && NumElems == 16) {
5468     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5469                                         Subtarget, *this);
5470     if (V.getNode()) return V;
5471   }
5472
5473   if (EVTBits == 16 && NumElems == 8) {
5474     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5475                                       Subtarget, *this);
5476     if (V.getNode()) return V;
5477   }
5478
5479   // If element VT is == 32 bits, turn it into a number of shuffles.
5480   SmallVector<SDValue, 8> V(NumElems);
5481   if (NumElems == 4 && NumZero > 0) {
5482     for (unsigned i = 0; i < 4; ++i) {
5483       bool isZero = !(NonZeros & (1 << i));
5484       if (isZero)
5485         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5486       else
5487         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5488     }
5489
5490     for (unsigned i = 0; i < 2; ++i) {
5491       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5492         default: break;
5493         case 0:
5494           V[i] = V[i*2];  // Must be a zero vector.
5495           break;
5496         case 1:
5497           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5498           break;
5499         case 2:
5500           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5501           break;
5502         case 3:
5503           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5504           break;
5505       }
5506     }
5507
5508     bool Reverse1 = (NonZeros & 0x3) == 2;
5509     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5510     int MaskVec[] = {
5511       Reverse1 ? 1 : 0,
5512       Reverse1 ? 0 : 1,
5513       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5514       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5515     };
5516     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5517   }
5518
5519   if (Values.size() > 1 && VT.is128BitVector()) {
5520     // Check for a build vector of consecutive loads.
5521     for (unsigned i = 0; i < NumElems; ++i)
5522       V[i] = Op.getOperand(i);
5523
5524     // Check for elements which are consecutive loads.
5525     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5526     if (LD.getNode())
5527       return LD;
5528
5529     // Check for a build vector from mostly shuffle plus few inserting.
5530     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5531     if (Sh.getNode())
5532       return Sh;
5533
5534     // For SSE 4.1, use insertps to put the high elements into the low element.
5535     if (getSubtarget()->hasSSE41()) {
5536       SDValue Result;
5537       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5538         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5539       else
5540         Result = DAG.getUNDEF(VT);
5541
5542       for (unsigned i = 1; i < NumElems; ++i) {
5543         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5544         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5545                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5546       }
5547       return Result;
5548     }
5549
5550     // Otherwise, expand into a number of unpckl*, start by extending each of
5551     // our (non-undef) elements to the full vector width with the element in the
5552     // bottom slot of the vector (which generates no code for SSE).
5553     for (unsigned i = 0; i < NumElems; ++i) {
5554       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5555         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5556       else
5557         V[i] = DAG.getUNDEF(VT);
5558     }
5559
5560     // Next, we iteratively mix elements, e.g. for v4f32:
5561     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5562     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5563     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5564     unsigned EltStride = NumElems >> 1;
5565     while (EltStride != 0) {
5566       for (unsigned i = 0; i < EltStride; ++i) {
5567         // If V[i+EltStride] is undef and this is the first round of mixing,
5568         // then it is safe to just drop this shuffle: V[i] is already in the
5569         // right place, the one element (since it's the first round) being
5570         // inserted as undef can be dropped.  This isn't safe for successive
5571         // rounds because they will permute elements within both vectors.
5572         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5573             EltStride == NumElems/2)
5574           continue;
5575
5576         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5577       }
5578       EltStride >>= 1;
5579     }
5580     return V[0];
5581   }
5582   return SDValue();
5583 }
5584
5585 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5586 // to create 256-bit vectors from two other 128-bit ones.
5587 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5588   DebugLoc dl = Op.getDebugLoc();
5589   EVT ResVT = Op.getValueType();
5590
5591   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5592
5593   SDValue V1 = Op.getOperand(0);
5594   SDValue V2 = Op.getOperand(1);
5595   unsigned NumElems = ResVT.getVectorNumElements();
5596
5597   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5598 }
5599
5600 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5601   assert(Op.getNumOperands() == 2);
5602
5603   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5604   // from two other 128-bit ones.
5605   return LowerAVXCONCAT_VECTORS(Op, DAG);
5606 }
5607
5608 // Try to lower a shuffle node into a simple blend instruction.
5609 static SDValue
5610 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5611                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5612   SDValue V1 = SVOp->getOperand(0);
5613   SDValue V2 = SVOp->getOperand(1);
5614   DebugLoc dl = SVOp->getDebugLoc();
5615   MVT VT = SVOp->getValueType(0).getSimpleVT();
5616   unsigned NumElems = VT.getVectorNumElements();
5617
5618   if (!Subtarget->hasSSE41())
5619     return SDValue();
5620
5621   unsigned ISDNo = 0;
5622   MVT OpTy;
5623
5624   switch (VT.SimpleTy) {
5625   default: return SDValue();
5626   case MVT::v8i16:
5627     ISDNo = X86ISD::BLENDPW;
5628     OpTy = MVT::v8i16;
5629     break;
5630   case MVT::v4i32:
5631   case MVT::v4f32:
5632     ISDNo = X86ISD::BLENDPS;
5633     OpTy = MVT::v4f32;
5634     break;
5635   case MVT::v2i64:
5636   case MVT::v2f64:
5637     ISDNo = X86ISD::BLENDPD;
5638     OpTy = MVT::v2f64;
5639     break;
5640   case MVT::v8i32:
5641   case MVT::v8f32:
5642     if (!Subtarget->hasAVX())
5643       return SDValue();
5644     ISDNo = X86ISD::BLENDPS;
5645     OpTy = MVT::v8f32;
5646     break;
5647   case MVT::v4i64:
5648   case MVT::v4f64:
5649     if (!Subtarget->hasAVX())
5650       return SDValue();
5651     ISDNo = X86ISD::BLENDPD;
5652     OpTy = MVT::v4f64;
5653     break;
5654   }
5655   assert(ISDNo && "Invalid Op Number");
5656
5657   unsigned MaskVals = 0;
5658
5659   for (unsigned i = 0; i != NumElems; ++i) {
5660     int EltIdx = SVOp->getMaskElt(i);
5661     if (EltIdx == (int)i || EltIdx < 0)
5662       MaskVals |= (1<<i);
5663     else if (EltIdx == (int)(i + NumElems))
5664       continue; // Bit is set to zero;
5665     else
5666       return SDValue();
5667   }
5668
5669   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5670   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5671   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5672                              DAG.getConstant(MaskVals, MVT::i32));
5673   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5674 }
5675
5676 // v8i16 shuffles - Prefer shuffles in the following order:
5677 // 1. [all]   pshuflw, pshufhw, optional move
5678 // 2. [ssse3] 1 x pshufb
5679 // 3. [ssse3] 2 x pshufb + 1 x por
5680 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5681 static SDValue
5682 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5683                          SelectionDAG &DAG) {
5684   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5685   SDValue V1 = SVOp->getOperand(0);
5686   SDValue V2 = SVOp->getOperand(1);
5687   DebugLoc dl = SVOp->getDebugLoc();
5688   SmallVector<int, 8> MaskVals;
5689
5690   // Determine if more than 1 of the words in each of the low and high quadwords
5691   // of the result come from the same quadword of one of the two inputs.  Undef
5692   // mask values count as coming from any quadword, for better codegen.
5693   unsigned LoQuad[] = { 0, 0, 0, 0 };
5694   unsigned HiQuad[] = { 0, 0, 0, 0 };
5695   std::bitset<4> InputQuads;
5696   for (unsigned i = 0; i < 8; ++i) {
5697     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5698     int EltIdx = SVOp->getMaskElt(i);
5699     MaskVals.push_back(EltIdx);
5700     if (EltIdx < 0) {
5701       ++Quad[0];
5702       ++Quad[1];
5703       ++Quad[2];
5704       ++Quad[3];
5705       continue;
5706     }
5707     ++Quad[EltIdx / 4];
5708     InputQuads.set(EltIdx / 4);
5709   }
5710
5711   int BestLoQuad = -1;
5712   unsigned MaxQuad = 1;
5713   for (unsigned i = 0; i < 4; ++i) {
5714     if (LoQuad[i] > MaxQuad) {
5715       BestLoQuad = i;
5716       MaxQuad = LoQuad[i];
5717     }
5718   }
5719
5720   int BestHiQuad = -1;
5721   MaxQuad = 1;
5722   for (unsigned i = 0; i < 4; ++i) {
5723     if (HiQuad[i] > MaxQuad) {
5724       BestHiQuad = i;
5725       MaxQuad = HiQuad[i];
5726     }
5727   }
5728
5729   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5730   // of the two input vectors, shuffle them into one input vector so only a
5731   // single pshufb instruction is necessary. If There are more than 2 input
5732   // quads, disable the next transformation since it does not help SSSE3.
5733   bool V1Used = InputQuads[0] || InputQuads[1];
5734   bool V2Used = InputQuads[2] || InputQuads[3];
5735   if (Subtarget->hasSSSE3()) {
5736     if (InputQuads.count() == 2 && V1Used && V2Used) {
5737       BestLoQuad = InputQuads[0] ? 0 : 1;
5738       BestHiQuad = InputQuads[2] ? 2 : 3;
5739     }
5740     if (InputQuads.count() > 2) {
5741       BestLoQuad = -1;
5742       BestHiQuad = -1;
5743     }
5744   }
5745
5746   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5747   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5748   // words from all 4 input quadwords.
5749   SDValue NewV;
5750   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5751     int MaskV[] = {
5752       BestLoQuad < 0 ? 0 : BestLoQuad,
5753       BestHiQuad < 0 ? 1 : BestHiQuad
5754     };
5755     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5756                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5757                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5758     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5759
5760     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5761     // source words for the shuffle, to aid later transformations.
5762     bool AllWordsInNewV = true;
5763     bool InOrder[2] = { true, true };
5764     for (unsigned i = 0; i != 8; ++i) {
5765       int idx = MaskVals[i];
5766       if (idx != (int)i)
5767         InOrder[i/4] = false;
5768       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5769         continue;
5770       AllWordsInNewV = false;
5771       break;
5772     }
5773
5774     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5775     if (AllWordsInNewV) {
5776       for (int i = 0; i != 8; ++i) {
5777         int idx = MaskVals[i];
5778         if (idx < 0)
5779           continue;
5780         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5781         if ((idx != i) && idx < 4)
5782           pshufhw = false;
5783         if ((idx != i) && idx > 3)
5784           pshuflw = false;
5785       }
5786       V1 = NewV;
5787       V2Used = false;
5788       BestLoQuad = 0;
5789       BestHiQuad = 1;
5790     }
5791
5792     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5793     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5794     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5795       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5796       unsigned TargetMask = 0;
5797       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5798                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5799       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5800       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5801                              getShufflePSHUFLWImmediate(SVOp);
5802       V1 = NewV.getOperand(0);
5803       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5804     }
5805   }
5806
5807   // If we have SSSE3, and all words of the result are from 1 input vector,
5808   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5809   // is present, fall back to case 4.
5810   if (Subtarget->hasSSSE3()) {
5811     SmallVector<SDValue,16> pshufbMask;
5812
5813     // If we have elements from both input vectors, set the high bit of the
5814     // shuffle mask element to zero out elements that come from V2 in the V1
5815     // mask, and elements that come from V1 in the V2 mask, so that the two
5816     // results can be OR'd together.
5817     bool TwoInputs = V1Used && V2Used;
5818     for (unsigned i = 0; i != 8; ++i) {
5819       int EltIdx = MaskVals[i] * 2;
5820       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5821       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5822       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5823       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5824     }
5825     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5826     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5827                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5828                                  MVT::v16i8, &pshufbMask[0], 16));
5829     if (!TwoInputs)
5830       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5831
5832     // Calculate the shuffle mask for the second input, shuffle it, and
5833     // OR it with the first shuffled input.
5834     pshufbMask.clear();
5835     for (unsigned i = 0; i != 8; ++i) {
5836       int EltIdx = MaskVals[i] * 2;
5837       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5838       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5839       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5840       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5841     }
5842     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5843     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5844                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5845                                  MVT::v16i8, &pshufbMask[0], 16));
5846     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5847     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5848   }
5849
5850   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5851   // and update MaskVals with new element order.
5852   std::bitset<8> InOrder;
5853   if (BestLoQuad >= 0) {
5854     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5855     for (int i = 0; i != 4; ++i) {
5856       int idx = MaskVals[i];
5857       if (idx < 0) {
5858         InOrder.set(i);
5859       } else if ((idx / 4) == BestLoQuad) {
5860         MaskV[i] = idx & 3;
5861         InOrder.set(i);
5862       }
5863     }
5864     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5865                                 &MaskV[0]);
5866
5867     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5868       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5869       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5870                                   NewV.getOperand(0),
5871                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5872     }
5873   }
5874
5875   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5876   // and update MaskVals with the new element order.
5877   if (BestHiQuad >= 0) {
5878     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5879     for (unsigned i = 4; i != 8; ++i) {
5880       int idx = MaskVals[i];
5881       if (idx < 0) {
5882         InOrder.set(i);
5883       } else if ((idx / 4) == BestHiQuad) {
5884         MaskV[i] = (idx & 3) + 4;
5885         InOrder.set(i);
5886       }
5887     }
5888     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5889                                 &MaskV[0]);
5890
5891     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5892       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5893       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5894                                   NewV.getOperand(0),
5895                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5896     }
5897   }
5898
5899   // In case BestHi & BestLo were both -1, which means each quadword has a word
5900   // from each of the four input quadwords, calculate the InOrder bitvector now
5901   // before falling through to the insert/extract cleanup.
5902   if (BestLoQuad == -1 && BestHiQuad == -1) {
5903     NewV = V1;
5904     for (int i = 0; i != 8; ++i)
5905       if (MaskVals[i] < 0 || MaskVals[i] == i)
5906         InOrder.set(i);
5907   }
5908
5909   // The other elements are put in the right place using pextrw and pinsrw.
5910   for (unsigned i = 0; i != 8; ++i) {
5911     if (InOrder[i])
5912       continue;
5913     int EltIdx = MaskVals[i];
5914     if (EltIdx < 0)
5915       continue;
5916     SDValue ExtOp = (EltIdx < 8) ?
5917       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5918                   DAG.getIntPtrConstant(EltIdx)) :
5919       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5920                   DAG.getIntPtrConstant(EltIdx - 8));
5921     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5922                        DAG.getIntPtrConstant(i));
5923   }
5924   return NewV;
5925 }
5926
5927 // v16i8 shuffles - Prefer shuffles in the following order:
5928 // 1. [ssse3] 1 x pshufb
5929 // 2. [ssse3] 2 x pshufb + 1 x por
5930 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5931 static
5932 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5933                                  SelectionDAG &DAG,
5934                                  const X86TargetLowering &TLI) {
5935   SDValue V1 = SVOp->getOperand(0);
5936   SDValue V2 = SVOp->getOperand(1);
5937   DebugLoc dl = SVOp->getDebugLoc();
5938   ArrayRef<int> MaskVals = SVOp->getMask();
5939
5940   // If we have SSSE3, case 1 is generated when all result bytes come from
5941   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5942   // present, fall back to case 3.
5943
5944   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5945   if (TLI.getSubtarget()->hasSSSE3()) {
5946     SmallVector<SDValue,16> pshufbMask;
5947
5948     // If all result elements are from one input vector, then only translate
5949     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5950     //
5951     // Otherwise, we have elements from both input vectors, and must zero out
5952     // elements that come from V2 in the first mask, and V1 in the second mask
5953     // so that we can OR them together.
5954     for (unsigned i = 0; i != 16; ++i) {
5955       int EltIdx = MaskVals[i];
5956       if (EltIdx < 0 || EltIdx >= 16)
5957         EltIdx = 0x80;
5958       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5959     }
5960     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5961                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5962                                  MVT::v16i8, &pshufbMask[0], 16));
5963
5964     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5965     // the 2nd operand if it's undefined or zero.
5966     if (V2.getOpcode() == ISD::UNDEF ||
5967         ISD::isBuildVectorAllZeros(V2.getNode()))
5968       return V1;
5969
5970     // Calculate the shuffle mask for the second input, shuffle it, and
5971     // OR it with the first shuffled input.
5972     pshufbMask.clear();
5973     for (unsigned i = 0; i != 16; ++i) {
5974       int EltIdx = MaskVals[i];
5975       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5976       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5977     }
5978     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5979                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5980                                  MVT::v16i8, &pshufbMask[0], 16));
5981     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5982   }
5983
5984   // No SSSE3 - Calculate in place words and then fix all out of place words
5985   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5986   // the 16 different words that comprise the two doublequadword input vectors.
5987   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5988   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5989   SDValue NewV = V1;
5990   for (int i = 0; i != 8; ++i) {
5991     int Elt0 = MaskVals[i*2];
5992     int Elt1 = MaskVals[i*2+1];
5993
5994     // This word of the result is all undef, skip it.
5995     if (Elt0 < 0 && Elt1 < 0)
5996       continue;
5997
5998     // This word of the result is already in the correct place, skip it.
5999     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6000       continue;
6001
6002     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6003     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6004     SDValue InsElt;
6005
6006     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6007     // using a single extract together, load it and store it.
6008     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6009       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6010                            DAG.getIntPtrConstant(Elt1 / 2));
6011       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6012                         DAG.getIntPtrConstant(i));
6013       continue;
6014     }
6015
6016     // If Elt1 is defined, extract it from the appropriate source.  If the
6017     // source byte is not also odd, shift the extracted word left 8 bits
6018     // otherwise clear the bottom 8 bits if we need to do an or.
6019     if (Elt1 >= 0) {
6020       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6021                            DAG.getIntPtrConstant(Elt1 / 2));
6022       if ((Elt1 & 1) == 0)
6023         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6024                              DAG.getConstant(8,
6025                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6026       else if (Elt0 >= 0)
6027         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6028                              DAG.getConstant(0xFF00, MVT::i16));
6029     }
6030     // If Elt0 is defined, extract it from the appropriate source.  If the
6031     // source byte is not also even, shift the extracted word right 8 bits. If
6032     // Elt1 was also defined, OR the extracted values together before
6033     // inserting them in the result.
6034     if (Elt0 >= 0) {
6035       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6036                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6037       if ((Elt0 & 1) != 0)
6038         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6039                               DAG.getConstant(8,
6040                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6041       else if (Elt1 >= 0)
6042         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6043                              DAG.getConstant(0x00FF, MVT::i16));
6044       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6045                          : InsElt0;
6046     }
6047     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6048                        DAG.getIntPtrConstant(i));
6049   }
6050   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6051 }
6052
6053 // v32i8 shuffles - Translate to VPSHUFB if possible.
6054 static
6055 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6056                                  const X86Subtarget *Subtarget,
6057                                  SelectionDAG &DAG) {
6058   EVT VT = SVOp->getValueType(0);
6059   SDValue V1 = SVOp->getOperand(0);
6060   SDValue V2 = SVOp->getOperand(1);
6061   DebugLoc dl = SVOp->getDebugLoc();
6062   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6063
6064   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6065   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6066   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6067
6068   // VPSHUFB may be generated if
6069   // (1) one of input vector is undefined or zeroinitializer.
6070   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6071   // And (2) the mask indexes don't cross the 128-bit lane.
6072   if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6073       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6074     return SDValue();
6075
6076   if (V1IsAllZero && !V2IsAllZero) {
6077     CommuteVectorShuffleMask(MaskVals, 32);
6078     V1 = V2;
6079   }
6080   SmallVector<SDValue, 32> pshufbMask;
6081   for (unsigned i = 0; i != 32; i++) {
6082     int EltIdx = MaskVals[i];
6083     if (EltIdx < 0 || EltIdx >= 32)
6084       EltIdx = 0x80;
6085     else {
6086       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6087         // Cross lane is not allowed.
6088         return SDValue();
6089       EltIdx &= 0xf;
6090     }
6091     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6092   }
6093   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6094                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6095                                   MVT::v32i8, &pshufbMask[0], 32));
6096 }
6097
6098 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6099 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6100 /// done when every pair / quad of shuffle mask elements point to elements in
6101 /// the right sequence. e.g.
6102 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6103 static
6104 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6105                                  SelectionDAG &DAG, DebugLoc dl) {
6106   MVT VT = SVOp->getValueType(0).getSimpleVT();
6107   unsigned NumElems = VT.getVectorNumElements();
6108   MVT NewVT;
6109   unsigned Scale;
6110   switch (VT.SimpleTy) {
6111   default: llvm_unreachable("Unexpected!");
6112   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6113   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6114   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6115   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6116   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6117   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6118   }
6119
6120   SmallVector<int, 8> MaskVec;
6121   for (unsigned i = 0; i != NumElems; i += Scale) {
6122     int StartIdx = -1;
6123     for (unsigned j = 0; j != Scale; ++j) {
6124       int EltIdx = SVOp->getMaskElt(i+j);
6125       if (EltIdx < 0)
6126         continue;
6127       if (StartIdx < 0)
6128         StartIdx = (EltIdx / Scale);
6129       if (EltIdx != (int)(StartIdx*Scale + j))
6130         return SDValue();
6131     }
6132     MaskVec.push_back(StartIdx);
6133   }
6134
6135   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6136   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6137   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6138 }
6139
6140 /// getVZextMovL - Return a zero-extending vector move low node.
6141 ///
6142 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6143                             SDValue SrcOp, SelectionDAG &DAG,
6144                             const X86Subtarget *Subtarget, DebugLoc dl) {
6145   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6146     LoadSDNode *LD = NULL;
6147     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6148       LD = dyn_cast<LoadSDNode>(SrcOp);
6149     if (!LD) {
6150       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6151       // instead.
6152       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6153       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6154           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6155           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6156           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6157         // PR2108
6158         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6159         return DAG.getNode(ISD::BITCAST, dl, VT,
6160                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6161                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6162                                                    OpVT,
6163                                                    SrcOp.getOperand(0)
6164                                                           .getOperand(0))));
6165       }
6166     }
6167   }
6168
6169   return DAG.getNode(ISD::BITCAST, dl, VT,
6170                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6171                                  DAG.getNode(ISD::BITCAST, dl,
6172                                              OpVT, SrcOp)));
6173 }
6174
6175 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6176 /// which could not be matched by any known target speficic shuffle
6177 static SDValue
6178 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6179
6180   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6181   if (NewOp.getNode())
6182     return NewOp;
6183
6184   EVT VT = SVOp->getValueType(0);
6185
6186   unsigned NumElems = VT.getVectorNumElements();
6187   unsigned NumLaneElems = NumElems / 2;
6188
6189   DebugLoc dl = SVOp->getDebugLoc();
6190   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6191   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6192   SDValue Output[2];
6193
6194   SmallVector<int, 16> Mask;
6195   for (unsigned l = 0; l < 2; ++l) {
6196     // Build a shuffle mask for the output, discovering on the fly which
6197     // input vectors to use as shuffle operands (recorded in InputUsed).
6198     // If building a suitable shuffle vector proves too hard, then bail
6199     // out with UseBuildVector set.
6200     bool UseBuildVector = false;
6201     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6202     unsigned LaneStart = l * NumLaneElems;
6203     for (unsigned i = 0; i != NumLaneElems; ++i) {
6204       // The mask element.  This indexes into the input.
6205       int Idx = SVOp->getMaskElt(i+LaneStart);
6206       if (Idx < 0) {
6207         // the mask element does not index into any input vector.
6208         Mask.push_back(-1);
6209         continue;
6210       }
6211
6212       // The input vector this mask element indexes into.
6213       int Input = Idx / NumLaneElems;
6214
6215       // Turn the index into an offset from the start of the input vector.
6216       Idx -= Input * NumLaneElems;
6217
6218       // Find or create a shuffle vector operand to hold this input.
6219       unsigned OpNo;
6220       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6221         if (InputUsed[OpNo] == Input)
6222           // This input vector is already an operand.
6223           break;
6224         if (InputUsed[OpNo] < 0) {
6225           // Create a new operand for this input vector.
6226           InputUsed[OpNo] = Input;
6227           break;
6228         }
6229       }
6230
6231       if (OpNo >= array_lengthof(InputUsed)) {
6232         // More than two input vectors used!  Give up on trying to create a
6233         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6234         UseBuildVector = true;
6235         break;
6236       }
6237
6238       // Add the mask index for the new shuffle vector.
6239       Mask.push_back(Idx + OpNo * NumLaneElems);
6240     }
6241
6242     if (UseBuildVector) {
6243       SmallVector<SDValue, 16> SVOps;
6244       for (unsigned i = 0; i != NumLaneElems; ++i) {
6245         // The mask element.  This indexes into the input.
6246         int Idx = SVOp->getMaskElt(i+LaneStart);
6247         if (Idx < 0) {
6248           SVOps.push_back(DAG.getUNDEF(EltVT));
6249           continue;
6250         }
6251
6252         // The input vector this mask element indexes into.
6253         int Input = Idx / NumElems;
6254
6255         // Turn the index into an offset from the start of the input vector.
6256         Idx -= Input * NumElems;
6257
6258         // Extract the vector element by hand.
6259         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6260                                     SVOp->getOperand(Input),
6261                                     DAG.getIntPtrConstant(Idx)));
6262       }
6263
6264       // Construct the output using a BUILD_VECTOR.
6265       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6266                               SVOps.size());
6267     } else if (InputUsed[0] < 0) {
6268       // No input vectors were used! The result is undefined.
6269       Output[l] = DAG.getUNDEF(NVT);
6270     } else {
6271       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6272                                         (InputUsed[0] % 2) * NumLaneElems,
6273                                         DAG, dl);
6274       // If only one input was used, use an undefined vector for the other.
6275       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6276         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6277                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6278       // At least one input vector was used. Create a new shuffle vector.
6279       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6280     }
6281
6282     Mask.clear();
6283   }
6284
6285   // Concatenate the result back
6286   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6287 }
6288
6289 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6290 /// 4 elements, and match them with several different shuffle types.
6291 static SDValue
6292 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6293   SDValue V1 = SVOp->getOperand(0);
6294   SDValue V2 = SVOp->getOperand(1);
6295   DebugLoc dl = SVOp->getDebugLoc();
6296   EVT VT = SVOp->getValueType(0);
6297
6298   assert(VT.is128BitVector() && "Unsupported vector size");
6299
6300   std::pair<int, int> Locs[4];
6301   int Mask1[] = { -1, -1, -1, -1 };
6302   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6303
6304   unsigned NumHi = 0;
6305   unsigned NumLo = 0;
6306   for (unsigned i = 0; i != 4; ++i) {
6307     int Idx = PermMask[i];
6308     if (Idx < 0) {
6309       Locs[i] = std::make_pair(-1, -1);
6310     } else {
6311       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6312       if (Idx < 4) {
6313         Locs[i] = std::make_pair(0, NumLo);
6314         Mask1[NumLo] = Idx;
6315         NumLo++;
6316       } else {
6317         Locs[i] = std::make_pair(1, NumHi);
6318         if (2+NumHi < 4)
6319           Mask1[2+NumHi] = Idx;
6320         NumHi++;
6321       }
6322     }
6323   }
6324
6325   if (NumLo <= 2 && NumHi <= 2) {
6326     // If no more than two elements come from either vector. This can be
6327     // implemented with two shuffles. First shuffle gather the elements.
6328     // The second shuffle, which takes the first shuffle as both of its
6329     // vector operands, put the elements into the right order.
6330     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6331
6332     int Mask2[] = { -1, -1, -1, -1 };
6333
6334     for (unsigned i = 0; i != 4; ++i)
6335       if (Locs[i].first != -1) {
6336         unsigned Idx = (i < 2) ? 0 : 4;
6337         Idx += Locs[i].first * 2 + Locs[i].second;
6338         Mask2[i] = Idx;
6339       }
6340
6341     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6342   }
6343
6344   if (NumLo == 3 || NumHi == 3) {
6345     // Otherwise, we must have three elements from one vector, call it X, and
6346     // one element from the other, call it Y.  First, use a shufps to build an
6347     // intermediate vector with the one element from Y and the element from X
6348     // that will be in the same half in the final destination (the indexes don't
6349     // matter). Then, use a shufps to build the final vector, taking the half
6350     // containing the element from Y from the intermediate, and the other half
6351     // from X.
6352     if (NumHi == 3) {
6353       // Normalize it so the 3 elements come from V1.
6354       CommuteVectorShuffleMask(PermMask, 4);
6355       std::swap(V1, V2);
6356     }
6357
6358     // Find the element from V2.
6359     unsigned HiIndex;
6360     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6361       int Val = PermMask[HiIndex];
6362       if (Val < 0)
6363         continue;
6364       if (Val >= 4)
6365         break;
6366     }
6367
6368     Mask1[0] = PermMask[HiIndex];
6369     Mask1[1] = -1;
6370     Mask1[2] = PermMask[HiIndex^1];
6371     Mask1[3] = -1;
6372     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6373
6374     if (HiIndex >= 2) {
6375       Mask1[0] = PermMask[0];
6376       Mask1[1] = PermMask[1];
6377       Mask1[2] = HiIndex & 1 ? 6 : 4;
6378       Mask1[3] = HiIndex & 1 ? 4 : 6;
6379       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6380     }
6381
6382     Mask1[0] = HiIndex & 1 ? 2 : 0;
6383     Mask1[1] = HiIndex & 1 ? 0 : 2;
6384     Mask1[2] = PermMask[2];
6385     Mask1[3] = PermMask[3];
6386     if (Mask1[2] >= 0)
6387       Mask1[2] += 4;
6388     if (Mask1[3] >= 0)
6389       Mask1[3] += 4;
6390     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6391   }
6392
6393   // Break it into (shuffle shuffle_hi, shuffle_lo).
6394   int LoMask[] = { -1, -1, -1, -1 };
6395   int HiMask[] = { -1, -1, -1, -1 };
6396
6397   int *MaskPtr = LoMask;
6398   unsigned MaskIdx = 0;
6399   unsigned LoIdx = 0;
6400   unsigned HiIdx = 2;
6401   for (unsigned i = 0; i != 4; ++i) {
6402     if (i == 2) {
6403       MaskPtr = HiMask;
6404       MaskIdx = 1;
6405       LoIdx = 0;
6406       HiIdx = 2;
6407     }
6408     int Idx = PermMask[i];
6409     if (Idx < 0) {
6410       Locs[i] = std::make_pair(-1, -1);
6411     } else if (Idx < 4) {
6412       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6413       MaskPtr[LoIdx] = Idx;
6414       LoIdx++;
6415     } else {
6416       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6417       MaskPtr[HiIdx] = Idx;
6418       HiIdx++;
6419     }
6420   }
6421
6422   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6423   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6424   int MaskOps[] = { -1, -1, -1, -1 };
6425   for (unsigned i = 0; i != 4; ++i)
6426     if (Locs[i].first != -1)
6427       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6428   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6429 }
6430
6431 static bool MayFoldVectorLoad(SDValue V) {
6432   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6433     V = V.getOperand(0);
6434   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6435     V = V.getOperand(0);
6436   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6437       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6438     // BUILD_VECTOR (load), undef
6439     V = V.getOperand(0);
6440   if (MayFoldLoad(V))
6441     return true;
6442   return false;
6443 }
6444
6445 // FIXME: the version above should always be used. Since there's
6446 // a bug where several vector shuffles can't be folded because the
6447 // DAG is not updated during lowering and a node claims to have two
6448 // uses while it only has one, use this version, and let isel match
6449 // another instruction if the load really happens to have more than
6450 // one use. Remove this version after this bug get fixed.
6451 // rdar://8434668, PR8156
6452 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6453   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6454     V = V.getOperand(0);
6455   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6456     V = V.getOperand(0);
6457   if (ISD::isNormalLoad(V.getNode()))
6458     return true;
6459   return false;
6460 }
6461
6462 static
6463 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6464   EVT VT = Op.getValueType();
6465
6466   // Canonizalize to v2f64.
6467   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6468   return DAG.getNode(ISD::BITCAST, dl, VT,
6469                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6470                                           V1, DAG));
6471 }
6472
6473 static
6474 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6475                         bool HasSSE2) {
6476   SDValue V1 = Op.getOperand(0);
6477   SDValue V2 = Op.getOperand(1);
6478   EVT VT = Op.getValueType();
6479
6480   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6481
6482   if (HasSSE2 && VT == MVT::v2f64)
6483     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6484
6485   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6486   return DAG.getNode(ISD::BITCAST, dl, VT,
6487                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6488                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6489                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6490 }
6491
6492 static
6493 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6494   SDValue V1 = Op.getOperand(0);
6495   SDValue V2 = Op.getOperand(1);
6496   EVT VT = Op.getValueType();
6497
6498   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6499          "unsupported shuffle type");
6500
6501   if (V2.getOpcode() == ISD::UNDEF)
6502     V2 = V1;
6503
6504   // v4i32 or v4f32
6505   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6506 }
6507
6508 static
6509 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6510   SDValue V1 = Op.getOperand(0);
6511   SDValue V2 = Op.getOperand(1);
6512   EVT VT = Op.getValueType();
6513   unsigned NumElems = VT.getVectorNumElements();
6514
6515   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6516   // operand of these instructions is only memory, so check if there's a
6517   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6518   // same masks.
6519   bool CanFoldLoad = false;
6520
6521   // Trivial case, when V2 comes from a load.
6522   if (MayFoldVectorLoad(V2))
6523     CanFoldLoad = true;
6524
6525   // When V1 is a load, it can be folded later into a store in isel, example:
6526   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6527   //    turns into:
6528   //  (MOVLPSmr addr:$src1, VR128:$src2)
6529   // So, recognize this potential and also use MOVLPS or MOVLPD
6530   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6531     CanFoldLoad = true;
6532
6533   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6534   if (CanFoldLoad) {
6535     if (HasSSE2 && NumElems == 2)
6536       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6537
6538     if (NumElems == 4)
6539       // If we don't care about the second element, proceed to use movss.
6540       if (SVOp->getMaskElt(1) != -1)
6541         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6542   }
6543
6544   // movl and movlp will both match v2i64, but v2i64 is never matched by
6545   // movl earlier because we make it strict to avoid messing with the movlp load
6546   // folding logic (see the code above getMOVLP call). Match it here then,
6547   // this is horrible, but will stay like this until we move all shuffle
6548   // matching to x86 specific nodes. Note that for the 1st condition all
6549   // types are matched with movsd.
6550   if (HasSSE2) {
6551     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6552     // as to remove this logic from here, as much as possible
6553     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6554       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6555     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6556   }
6557
6558   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6559
6560   // Invert the operand order and use SHUFPS to match it.
6561   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6562                               getShuffleSHUFImmediate(SVOp), DAG);
6563 }
6564
6565 SDValue
6566 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6567   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6568   EVT VT = Op.getValueType();
6569   DebugLoc dl = Op.getDebugLoc();
6570   SDValue V1 = Op.getOperand(0);
6571   SDValue V2 = Op.getOperand(1);
6572
6573   if (isZeroShuffle(SVOp))
6574     return getZeroVector(VT, Subtarget, DAG, dl);
6575
6576   // Handle splat operations
6577   if (SVOp->isSplat()) {
6578     unsigned NumElem = VT.getVectorNumElements();
6579     int Size = VT.getSizeInBits();
6580
6581     // Use vbroadcast whenever the splat comes from a foldable load
6582     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6583     if (Broadcast.getNode())
6584       return Broadcast;
6585
6586     // Handle splats by matching through known shuffle masks
6587     if ((Size == 128 && NumElem <= 4) ||
6588         (Size == 256 && NumElem < 8))
6589       return SDValue();
6590
6591     // All remaning splats are promoted to target supported vector shuffles.
6592     return PromoteSplat(SVOp, DAG);
6593   }
6594
6595   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6596   // do it!
6597   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6598       VT == MVT::v16i16 || VT == MVT::v32i8) {
6599     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6600     if (NewOp.getNode())
6601       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6602   } else if ((VT == MVT::v4i32 ||
6603              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6604     // FIXME: Figure out a cleaner way to do this.
6605     // Try to make use of movq to zero out the top part.
6606     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6607       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6608       if (NewOp.getNode()) {
6609         EVT NewVT = NewOp.getValueType();
6610         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6611                                NewVT, true, false))
6612           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6613                               DAG, Subtarget, dl);
6614       }
6615     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6616       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6617       if (NewOp.getNode()) {
6618         EVT NewVT = NewOp.getValueType();
6619         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6620           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6621                               DAG, Subtarget, dl);
6622       }
6623     }
6624   }
6625   return SDValue();
6626 }
6627
6628 SDValue
6629 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6630   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6631   SDValue V1 = Op.getOperand(0);
6632   SDValue V2 = Op.getOperand(1);
6633   EVT VT = Op.getValueType();
6634   DebugLoc dl = Op.getDebugLoc();
6635   unsigned NumElems = VT.getVectorNumElements();
6636   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6637   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6638   bool V1IsSplat = false;
6639   bool V2IsSplat = false;
6640   bool HasSSE2 = Subtarget->hasSSE2();
6641   bool HasAVX    = Subtarget->hasAVX();
6642   bool HasAVX2   = Subtarget->hasAVX2();
6643   MachineFunction &MF = DAG.getMachineFunction();
6644   bool OptForSize = MF.getFunction()->getFnAttributes().
6645     hasAttribute(Attributes::OptimizeForSize);
6646
6647   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6648
6649   if (V1IsUndef && V2IsUndef)
6650     return DAG.getUNDEF(VT);
6651
6652   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6653
6654   // Vector shuffle lowering takes 3 steps:
6655   //
6656   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6657   //    narrowing and commutation of operands should be handled.
6658   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6659   //    shuffle nodes.
6660   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6661   //    so the shuffle can be broken into other shuffles and the legalizer can
6662   //    try the lowering again.
6663   //
6664   // The general idea is that no vector_shuffle operation should be left to
6665   // be matched during isel, all of them must be converted to a target specific
6666   // node here.
6667
6668   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6669   // narrowing and commutation of operands should be handled. The actual code
6670   // doesn't include all of those, work in progress...
6671   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6672   if (NewOp.getNode())
6673     return NewOp;
6674
6675   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6676
6677   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6678   // unpckh_undef). Only use pshufd if speed is more important than size.
6679   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6680     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6681   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6682     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6683
6684   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6685       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6686     return getMOVDDup(Op, dl, V1, DAG);
6687
6688   if (isMOVHLPS_v_undef_Mask(M, VT))
6689     return getMOVHighToLow(Op, dl, DAG);
6690
6691   // Use to match splats
6692   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6693       (VT == MVT::v2f64 || VT == MVT::v2i64))
6694     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6695
6696   if (isPSHUFDMask(M, VT)) {
6697     // The actual implementation will match the mask in the if above and then
6698     // during isel it can match several different instructions, not only pshufd
6699     // as its name says, sad but true, emulate the behavior for now...
6700     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6701       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6702
6703     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6704
6705     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6706       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6707
6708     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6709       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6710
6711     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6712                                 TargetMask, DAG);
6713   }
6714
6715   // Check if this can be converted into a logical shift.
6716   bool isLeft = false;
6717   unsigned ShAmt = 0;
6718   SDValue ShVal;
6719   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6720   if (isShift && ShVal.hasOneUse()) {
6721     // If the shifted value has multiple uses, it may be cheaper to use
6722     // v_set0 + movlhps or movhlps, etc.
6723     EVT EltVT = VT.getVectorElementType();
6724     ShAmt *= EltVT.getSizeInBits();
6725     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6726   }
6727
6728   if (isMOVLMask(M, VT)) {
6729     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6730       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6731     if (!isMOVLPMask(M, VT)) {
6732       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6733         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6734
6735       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6736         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6737     }
6738   }
6739
6740   // FIXME: fold these into legal mask.
6741   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6742     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6743
6744   if (isMOVHLPSMask(M, VT))
6745     return getMOVHighToLow(Op, dl, DAG);
6746
6747   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6748     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6749
6750   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6751     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6752
6753   if (isMOVLPMask(M, VT))
6754     return getMOVLP(Op, dl, DAG, HasSSE2);
6755
6756   if (ShouldXformToMOVHLPS(M, VT) ||
6757       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6758     return CommuteVectorShuffle(SVOp, DAG);
6759
6760   if (isShift) {
6761     // No better options. Use a vshldq / vsrldq.
6762     EVT EltVT = VT.getVectorElementType();
6763     ShAmt *= EltVT.getSizeInBits();
6764     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6765   }
6766
6767   bool Commuted = false;
6768   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6769   // 1,1,1,1 -> v8i16 though.
6770   V1IsSplat = isSplatVector(V1.getNode());
6771   V2IsSplat = isSplatVector(V2.getNode());
6772
6773   // Canonicalize the splat or undef, if present, to be on the RHS.
6774   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6775     CommuteVectorShuffleMask(M, NumElems);
6776     std::swap(V1, V2);
6777     std::swap(V1IsSplat, V2IsSplat);
6778     Commuted = true;
6779   }
6780
6781   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6782     // Shuffling low element of v1 into undef, just return v1.
6783     if (V2IsUndef)
6784       return V1;
6785     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6786     // the instruction selector will not match, so get a canonical MOVL with
6787     // swapped operands to undo the commute.
6788     return getMOVL(DAG, dl, VT, V2, V1);
6789   }
6790
6791   if (isUNPCKLMask(M, VT, HasAVX2))
6792     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6793
6794   if (isUNPCKHMask(M, VT, HasAVX2))
6795     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6796
6797   if (V2IsSplat) {
6798     // Normalize mask so all entries that point to V2 points to its first
6799     // element then try to match unpck{h|l} again. If match, return a
6800     // new vector_shuffle with the corrected mask.p
6801     SmallVector<int, 8> NewMask(M.begin(), M.end());
6802     NormalizeMask(NewMask, NumElems);
6803     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6804       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6805     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6806       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6807   }
6808
6809   if (Commuted) {
6810     // Commute is back and try unpck* again.
6811     // FIXME: this seems wrong.
6812     CommuteVectorShuffleMask(M, NumElems);
6813     std::swap(V1, V2);
6814     std::swap(V1IsSplat, V2IsSplat);
6815     Commuted = false;
6816
6817     if (isUNPCKLMask(M, VT, HasAVX2))
6818       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6819
6820     if (isUNPCKHMask(M, VT, HasAVX2))
6821       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6822   }
6823
6824   // Normalize the node to match x86 shuffle ops if needed
6825   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6826     return CommuteVectorShuffle(SVOp, DAG);
6827
6828   // The checks below are all present in isShuffleMaskLegal, but they are
6829   // inlined here right now to enable us to directly emit target specific
6830   // nodes, and remove one by one until they don't return Op anymore.
6831
6832   if (isPALIGNRMask(M, VT, Subtarget))
6833     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6834                                 getShufflePALIGNRImmediate(SVOp),
6835                                 DAG);
6836
6837   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6838       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6839     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6840       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6841   }
6842
6843   if (isPSHUFHWMask(M, VT, HasAVX2))
6844     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6845                                 getShufflePSHUFHWImmediate(SVOp),
6846                                 DAG);
6847
6848   if (isPSHUFLWMask(M, VT, HasAVX2))
6849     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6850                                 getShufflePSHUFLWImmediate(SVOp),
6851                                 DAG);
6852
6853   if (isSHUFPMask(M, VT, HasAVX))
6854     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6855                                 getShuffleSHUFImmediate(SVOp), DAG);
6856
6857   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6858     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6859   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6860     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6861
6862   //===--------------------------------------------------------------------===//
6863   // Generate target specific nodes for 128 or 256-bit shuffles only
6864   // supported in the AVX instruction set.
6865   //
6866
6867   // Handle VMOVDDUPY permutations
6868   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6869     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6870
6871   // Handle VPERMILPS/D* permutations
6872   if (isVPERMILPMask(M, VT, HasAVX)) {
6873     if (HasAVX2 && VT == MVT::v8i32)
6874       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6875                                   getShuffleSHUFImmediate(SVOp), DAG);
6876     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6877                                 getShuffleSHUFImmediate(SVOp), DAG);
6878   }
6879
6880   // Handle VPERM2F128/VPERM2I128 permutations
6881   if (isVPERM2X128Mask(M, VT, HasAVX))
6882     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6883                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6884
6885   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6886   if (BlendOp.getNode())
6887     return BlendOp;
6888
6889   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6890     SmallVector<SDValue, 8> permclMask;
6891     for (unsigned i = 0; i != 8; ++i) {
6892       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6893     }
6894     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6895                                &permclMask[0], 8);
6896     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6897     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6898                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6899   }
6900
6901   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6902     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6903                                 getShuffleCLImmediate(SVOp), DAG);
6904
6905
6906   //===--------------------------------------------------------------------===//
6907   // Since no target specific shuffle was selected for this generic one,
6908   // lower it into other known shuffles. FIXME: this isn't true yet, but
6909   // this is the plan.
6910   //
6911
6912   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6913   if (VT == MVT::v8i16) {
6914     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6915     if (NewOp.getNode())
6916       return NewOp;
6917   }
6918
6919   if (VT == MVT::v16i8) {
6920     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6921     if (NewOp.getNode())
6922       return NewOp;
6923   }
6924
6925   if (VT == MVT::v32i8) {
6926     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6927     if (NewOp.getNode())
6928       return NewOp;
6929   }
6930
6931   // Handle all 128-bit wide vectors with 4 elements, and match them with
6932   // several different shuffle types.
6933   if (NumElems == 4 && VT.is128BitVector())
6934     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6935
6936   // Handle general 256-bit shuffles
6937   if (VT.is256BitVector())
6938     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6939
6940   return SDValue();
6941 }
6942
6943 SDValue
6944 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6945                                                 SelectionDAG &DAG) const {
6946   EVT VT = Op.getValueType();
6947   DebugLoc dl = Op.getDebugLoc();
6948
6949   if (!Op.getOperand(0).getValueType().is128BitVector())
6950     return SDValue();
6951
6952   if (VT.getSizeInBits() == 8) {
6953     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6954                                   Op.getOperand(0), Op.getOperand(1));
6955     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6956                                   DAG.getValueType(VT));
6957     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6958   }
6959
6960   if (VT.getSizeInBits() == 16) {
6961     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6962     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6963     if (Idx == 0)
6964       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6965                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6966                                      DAG.getNode(ISD::BITCAST, dl,
6967                                                  MVT::v4i32,
6968                                                  Op.getOperand(0)),
6969                                      Op.getOperand(1)));
6970     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6971                                   Op.getOperand(0), Op.getOperand(1));
6972     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6973                                   DAG.getValueType(VT));
6974     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6975   }
6976
6977   if (VT == MVT::f32) {
6978     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6979     // the result back to FR32 register. It's only worth matching if the
6980     // result has a single use which is a store or a bitcast to i32.  And in
6981     // the case of a store, it's not worth it if the index is a constant 0,
6982     // because a MOVSSmr can be used instead, which is smaller and faster.
6983     if (!Op.hasOneUse())
6984       return SDValue();
6985     SDNode *User = *Op.getNode()->use_begin();
6986     if ((User->getOpcode() != ISD::STORE ||
6987          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6988           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6989         (User->getOpcode() != ISD::BITCAST ||
6990          User->getValueType(0) != MVT::i32))
6991       return SDValue();
6992     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6993                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6994                                               Op.getOperand(0)),
6995                                               Op.getOperand(1));
6996     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6997   }
6998
6999   if (VT == MVT::i32 || VT == MVT::i64) {
7000     // ExtractPS/pextrq works with constant index.
7001     if (isa<ConstantSDNode>(Op.getOperand(1)))
7002       return Op;
7003   }
7004   return SDValue();
7005 }
7006
7007
7008 SDValue
7009 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7010                                            SelectionDAG &DAG) const {
7011   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7012     return SDValue();
7013
7014   SDValue Vec = Op.getOperand(0);
7015   EVT VecVT = Vec.getValueType();
7016
7017   // If this is a 256-bit vector result, first extract the 128-bit vector and
7018   // then extract the element from the 128-bit vector.
7019   if (VecVT.is256BitVector()) {
7020     DebugLoc dl = Op.getNode()->getDebugLoc();
7021     unsigned NumElems = VecVT.getVectorNumElements();
7022     SDValue Idx = Op.getOperand(1);
7023     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7024
7025     // Get the 128-bit vector.
7026     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7027
7028     if (IdxVal >= NumElems/2)
7029       IdxVal -= NumElems/2;
7030     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7031                        DAG.getConstant(IdxVal, MVT::i32));
7032   }
7033
7034   assert(VecVT.is128BitVector() && "Unexpected vector length");
7035
7036   if (Subtarget->hasSSE41()) {
7037     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7038     if (Res.getNode())
7039       return Res;
7040   }
7041
7042   EVT VT = Op.getValueType();
7043   DebugLoc dl = Op.getDebugLoc();
7044   // TODO: handle v16i8.
7045   if (VT.getSizeInBits() == 16) {
7046     SDValue Vec = Op.getOperand(0);
7047     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7048     if (Idx == 0)
7049       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7050                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7051                                      DAG.getNode(ISD::BITCAST, dl,
7052                                                  MVT::v4i32, Vec),
7053                                      Op.getOperand(1)));
7054     // Transform it so it match pextrw which produces a 32-bit result.
7055     EVT EltVT = MVT::i32;
7056     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7057                                   Op.getOperand(0), Op.getOperand(1));
7058     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7059                                   DAG.getValueType(VT));
7060     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7061   }
7062
7063   if (VT.getSizeInBits() == 32) {
7064     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7065     if (Idx == 0)
7066       return Op;
7067
7068     // SHUFPS the element to the lowest double word, then movss.
7069     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7070     EVT VVT = Op.getOperand(0).getValueType();
7071     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7072                                        DAG.getUNDEF(VVT), Mask);
7073     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7074                        DAG.getIntPtrConstant(0));
7075   }
7076
7077   if (VT.getSizeInBits() == 64) {
7078     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7079     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7080     //        to match extract_elt for f64.
7081     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7082     if (Idx == 0)
7083       return Op;
7084
7085     // UNPCKHPD the element to the lowest double word, then movsd.
7086     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7087     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7088     int Mask[2] = { 1, -1 };
7089     EVT VVT = Op.getOperand(0).getValueType();
7090     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7091                                        DAG.getUNDEF(VVT), Mask);
7092     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7093                        DAG.getIntPtrConstant(0));
7094   }
7095
7096   return SDValue();
7097 }
7098
7099 SDValue
7100 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7101                                                SelectionDAG &DAG) const {
7102   EVT VT = Op.getValueType();
7103   EVT EltVT = VT.getVectorElementType();
7104   DebugLoc dl = Op.getDebugLoc();
7105
7106   SDValue N0 = Op.getOperand(0);
7107   SDValue N1 = Op.getOperand(1);
7108   SDValue N2 = Op.getOperand(2);
7109
7110   if (!VT.is128BitVector())
7111     return SDValue();
7112
7113   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7114       isa<ConstantSDNode>(N2)) {
7115     unsigned Opc;
7116     if (VT == MVT::v8i16)
7117       Opc = X86ISD::PINSRW;
7118     else if (VT == MVT::v16i8)
7119       Opc = X86ISD::PINSRB;
7120     else
7121       Opc = X86ISD::PINSRB;
7122
7123     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7124     // argument.
7125     if (N1.getValueType() != MVT::i32)
7126       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7127     if (N2.getValueType() != MVT::i32)
7128       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7129     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7130   }
7131
7132   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7133     // Bits [7:6] of the constant are the source select.  This will always be
7134     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7135     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7136     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7137     // Bits [5:4] of the constant are the destination select.  This is the
7138     //  value of the incoming immediate.
7139     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7140     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7141     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7142     // Create this as a scalar to vector..
7143     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7144     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7145   }
7146
7147   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7148     // PINSR* works with constant index.
7149     return Op;
7150   }
7151   return SDValue();
7152 }
7153
7154 SDValue
7155 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7156   EVT VT = Op.getValueType();
7157   EVT EltVT = VT.getVectorElementType();
7158
7159   DebugLoc dl = Op.getDebugLoc();
7160   SDValue N0 = Op.getOperand(0);
7161   SDValue N1 = Op.getOperand(1);
7162   SDValue N2 = Op.getOperand(2);
7163
7164   // If this is a 256-bit vector result, first extract the 128-bit vector,
7165   // insert the element into the extracted half and then place it back.
7166   if (VT.is256BitVector()) {
7167     if (!isa<ConstantSDNode>(N2))
7168       return SDValue();
7169
7170     // Get the desired 128-bit vector half.
7171     unsigned NumElems = VT.getVectorNumElements();
7172     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7173     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7174
7175     // Insert the element into the desired half.
7176     bool Upper = IdxVal >= NumElems/2;
7177     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7178                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7179
7180     // Insert the changed part back to the 256-bit vector
7181     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7182   }
7183
7184   if (Subtarget->hasSSE41())
7185     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7186
7187   if (EltVT == MVT::i8)
7188     return SDValue();
7189
7190   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7191     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7192     // as its second argument.
7193     if (N1.getValueType() != MVT::i32)
7194       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7195     if (N2.getValueType() != MVT::i32)
7196       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7197     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7198   }
7199   return SDValue();
7200 }
7201
7202 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7203   LLVMContext *Context = DAG.getContext();
7204   DebugLoc dl = Op.getDebugLoc();
7205   EVT OpVT = Op.getValueType();
7206
7207   // If this is a 256-bit vector result, first insert into a 128-bit
7208   // vector and then insert into the 256-bit vector.
7209   if (!OpVT.is128BitVector()) {
7210     // Insert into a 128-bit vector.
7211     EVT VT128 = EVT::getVectorVT(*Context,
7212                                  OpVT.getVectorElementType(),
7213                                  OpVT.getVectorNumElements() / 2);
7214
7215     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7216
7217     // Insert the 128-bit vector.
7218     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7219   }
7220
7221   if (OpVT == MVT::v1i64 &&
7222       Op.getOperand(0).getValueType() == MVT::i64)
7223     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7224
7225   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7226   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7227   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7228                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7229 }
7230
7231 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7232 // a simple subregister reference or explicit instructions to grab
7233 // upper bits of a vector.
7234 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7235                                       SelectionDAG &DAG) {
7236   if (Subtarget->hasAVX()) {
7237     DebugLoc dl = Op.getNode()->getDebugLoc();
7238     SDValue Vec = Op.getNode()->getOperand(0);
7239     SDValue Idx = Op.getNode()->getOperand(1);
7240
7241     if (Op.getNode()->getValueType(0).is128BitVector() &&
7242         Vec.getNode()->getValueType(0).is256BitVector() &&
7243         isa<ConstantSDNode>(Idx)) {
7244       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7245       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7246     }
7247   }
7248   return SDValue();
7249 }
7250
7251 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7252 // simple superregister reference or explicit instructions to insert
7253 // the upper bits of a vector.
7254 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7255                                      SelectionDAG &DAG) {
7256   if (Subtarget->hasAVX()) {
7257     DebugLoc dl = Op.getNode()->getDebugLoc();
7258     SDValue Vec = Op.getNode()->getOperand(0);
7259     SDValue SubVec = Op.getNode()->getOperand(1);
7260     SDValue Idx = Op.getNode()->getOperand(2);
7261
7262     if (Op.getNode()->getValueType(0).is256BitVector() &&
7263         SubVec.getNode()->getValueType(0).is128BitVector() &&
7264         isa<ConstantSDNode>(Idx)) {
7265       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7266       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7267     }
7268   }
7269   return SDValue();
7270 }
7271
7272 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7273 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7274 // one of the above mentioned nodes. It has to be wrapped because otherwise
7275 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7276 // be used to form addressing mode. These wrapped nodes will be selected
7277 // into MOV32ri.
7278 SDValue
7279 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7280   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7281
7282   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7283   // global base reg.
7284   unsigned char OpFlag = 0;
7285   unsigned WrapperKind = X86ISD::Wrapper;
7286   CodeModel::Model M = getTargetMachine().getCodeModel();
7287
7288   if (Subtarget->isPICStyleRIPRel() &&
7289       (M == CodeModel::Small || M == CodeModel::Kernel))
7290     WrapperKind = X86ISD::WrapperRIP;
7291   else if (Subtarget->isPICStyleGOT())
7292     OpFlag = X86II::MO_GOTOFF;
7293   else if (Subtarget->isPICStyleStubPIC())
7294     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7295
7296   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7297                                              CP->getAlignment(),
7298                                              CP->getOffset(), OpFlag);
7299   DebugLoc DL = CP->getDebugLoc();
7300   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7301   // With PIC, the address is actually $g + Offset.
7302   if (OpFlag) {
7303     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7304                          DAG.getNode(X86ISD::GlobalBaseReg,
7305                                      DebugLoc(), getPointerTy()),
7306                          Result);
7307   }
7308
7309   return Result;
7310 }
7311
7312 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7313   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7314
7315   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7316   // global base reg.
7317   unsigned char OpFlag = 0;
7318   unsigned WrapperKind = X86ISD::Wrapper;
7319   CodeModel::Model M = getTargetMachine().getCodeModel();
7320
7321   if (Subtarget->isPICStyleRIPRel() &&
7322       (M == CodeModel::Small || M == CodeModel::Kernel))
7323     WrapperKind = X86ISD::WrapperRIP;
7324   else if (Subtarget->isPICStyleGOT())
7325     OpFlag = X86II::MO_GOTOFF;
7326   else if (Subtarget->isPICStyleStubPIC())
7327     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7328
7329   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7330                                           OpFlag);
7331   DebugLoc DL = JT->getDebugLoc();
7332   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7333
7334   // With PIC, the address is actually $g + Offset.
7335   if (OpFlag)
7336     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7337                          DAG.getNode(X86ISD::GlobalBaseReg,
7338                                      DebugLoc(), getPointerTy()),
7339                          Result);
7340
7341   return Result;
7342 }
7343
7344 SDValue
7345 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7346   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7347
7348   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7349   // global base reg.
7350   unsigned char OpFlag = 0;
7351   unsigned WrapperKind = X86ISD::Wrapper;
7352   CodeModel::Model M = getTargetMachine().getCodeModel();
7353
7354   if (Subtarget->isPICStyleRIPRel() &&
7355       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7356     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7357       OpFlag = X86II::MO_GOTPCREL;
7358     WrapperKind = X86ISD::WrapperRIP;
7359   } else if (Subtarget->isPICStyleGOT()) {
7360     OpFlag = X86II::MO_GOT;
7361   } else if (Subtarget->isPICStyleStubPIC()) {
7362     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7363   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7364     OpFlag = X86II::MO_DARWIN_NONLAZY;
7365   }
7366
7367   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7368
7369   DebugLoc DL = Op.getDebugLoc();
7370   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7371
7372
7373   // With PIC, the address is actually $g + Offset.
7374   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7375       !Subtarget->is64Bit()) {
7376     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7377                          DAG.getNode(X86ISD::GlobalBaseReg,
7378                                      DebugLoc(), getPointerTy()),
7379                          Result);
7380   }
7381
7382   // For symbols that require a load from a stub to get the address, emit the
7383   // load.
7384   if (isGlobalStubReference(OpFlag))
7385     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7386                          MachinePointerInfo::getGOT(), false, false, false, 0);
7387
7388   return Result;
7389 }
7390
7391 SDValue
7392 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7393   // Create the TargetBlockAddressAddress node.
7394   unsigned char OpFlags =
7395     Subtarget->ClassifyBlockAddressReference();
7396   CodeModel::Model M = getTargetMachine().getCodeModel();
7397   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7398   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7399   DebugLoc dl = Op.getDebugLoc();
7400   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7401                                              OpFlags);
7402
7403   if (Subtarget->isPICStyleRIPRel() &&
7404       (M == CodeModel::Small || M == CodeModel::Kernel))
7405     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7406   else
7407     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7408
7409   // With PIC, the address is actually $g + Offset.
7410   if (isGlobalRelativeToPICBase(OpFlags)) {
7411     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7412                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7413                          Result);
7414   }
7415
7416   return Result;
7417 }
7418
7419 SDValue
7420 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7421                                       int64_t Offset,
7422                                       SelectionDAG &DAG) const {
7423   // Create the TargetGlobalAddress node, folding in the constant
7424   // offset if it is legal.
7425   unsigned char OpFlags =
7426     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7427   CodeModel::Model M = getTargetMachine().getCodeModel();
7428   SDValue Result;
7429   if (OpFlags == X86II::MO_NO_FLAG &&
7430       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7431     // A direct static reference to a global.
7432     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7433     Offset = 0;
7434   } else {
7435     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7436   }
7437
7438   if (Subtarget->isPICStyleRIPRel() &&
7439       (M == CodeModel::Small || M == CodeModel::Kernel))
7440     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7441   else
7442     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7443
7444   // With PIC, the address is actually $g + Offset.
7445   if (isGlobalRelativeToPICBase(OpFlags)) {
7446     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7447                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7448                          Result);
7449   }
7450
7451   // For globals that require a load from a stub to get the address, emit the
7452   // load.
7453   if (isGlobalStubReference(OpFlags))
7454     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7455                          MachinePointerInfo::getGOT(), false, false, false, 0);
7456
7457   // If there was a non-zero offset that we didn't fold, create an explicit
7458   // addition for it.
7459   if (Offset != 0)
7460     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7461                          DAG.getConstant(Offset, getPointerTy()));
7462
7463   return Result;
7464 }
7465
7466 SDValue
7467 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7468   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7469   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7470   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7471 }
7472
7473 static SDValue
7474 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7475            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7476            unsigned char OperandFlags, bool LocalDynamic = false) {
7477   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7478   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7479   DebugLoc dl = GA->getDebugLoc();
7480   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7481                                            GA->getValueType(0),
7482                                            GA->getOffset(),
7483                                            OperandFlags);
7484
7485   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7486                                            : X86ISD::TLSADDR;
7487
7488   if (InFlag) {
7489     SDValue Ops[] = { Chain,  TGA, *InFlag };
7490     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7491   } else {
7492     SDValue Ops[]  = { Chain, TGA };
7493     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7494   }
7495
7496   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7497   MFI->setAdjustsStack(true);
7498
7499   SDValue Flag = Chain.getValue(1);
7500   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7501 }
7502
7503 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7504 static SDValue
7505 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7506                                 const EVT PtrVT) {
7507   SDValue InFlag;
7508   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7509   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7510                                    DAG.getNode(X86ISD::GlobalBaseReg,
7511                                                DebugLoc(), PtrVT), InFlag);
7512   InFlag = Chain.getValue(1);
7513
7514   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7515 }
7516
7517 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7518 static SDValue
7519 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7520                                 const EVT PtrVT) {
7521   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7522                     X86::RAX, X86II::MO_TLSGD);
7523 }
7524
7525 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7526                                            SelectionDAG &DAG,
7527                                            const EVT PtrVT,
7528                                            bool is64Bit) {
7529   DebugLoc dl = GA->getDebugLoc();
7530
7531   // Get the start address of the TLS block for this module.
7532   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7533       .getInfo<X86MachineFunctionInfo>();
7534   MFI->incNumLocalDynamicTLSAccesses();
7535
7536   SDValue Base;
7537   if (is64Bit) {
7538     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7539                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7540   } else {
7541     SDValue InFlag;
7542     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7543         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7544     InFlag = Chain.getValue(1);
7545     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7546                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7547   }
7548
7549   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7550   // of Base.
7551
7552   // Build x@dtpoff.
7553   unsigned char OperandFlags = X86II::MO_DTPOFF;
7554   unsigned WrapperKind = X86ISD::Wrapper;
7555   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7556                                            GA->getValueType(0),
7557                                            GA->getOffset(), OperandFlags);
7558   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7559
7560   // Add x@dtpoff with the base.
7561   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7562 }
7563
7564 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7565 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7566                                    const EVT PtrVT, TLSModel::Model model,
7567                                    bool is64Bit, bool isPIC) {
7568   DebugLoc dl = GA->getDebugLoc();
7569
7570   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7571   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7572                                                          is64Bit ? 257 : 256));
7573
7574   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7575                                       DAG.getIntPtrConstant(0),
7576                                       MachinePointerInfo(Ptr),
7577                                       false, false, false, 0);
7578
7579   unsigned char OperandFlags = 0;
7580   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7581   // initialexec.
7582   unsigned WrapperKind = X86ISD::Wrapper;
7583   if (model == TLSModel::LocalExec) {
7584     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7585   } else if (model == TLSModel::InitialExec) {
7586     if (is64Bit) {
7587       OperandFlags = X86II::MO_GOTTPOFF;
7588       WrapperKind = X86ISD::WrapperRIP;
7589     } else {
7590       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7591     }
7592   } else {
7593     llvm_unreachable("Unexpected model");
7594   }
7595
7596   // emit "addl x@ntpoff,%eax" (local exec)
7597   // or "addl x@indntpoff,%eax" (initial exec)
7598   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7599   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7600                                            GA->getValueType(0),
7601                                            GA->getOffset(), OperandFlags);
7602   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7603
7604   if (model == TLSModel::InitialExec) {
7605     if (isPIC && !is64Bit) {
7606       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7607                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7608                            Offset);
7609     }
7610
7611     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7612                          MachinePointerInfo::getGOT(), false, false, false,
7613                          0);
7614   }
7615
7616   // The address of the thread local variable is the add of the thread
7617   // pointer with the offset of the variable.
7618   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7619 }
7620
7621 SDValue
7622 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7623
7624   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7625   const GlobalValue *GV = GA->getGlobal();
7626
7627   if (Subtarget->isTargetELF()) {
7628     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7629
7630     switch (model) {
7631       case TLSModel::GeneralDynamic:
7632         if (Subtarget->is64Bit())
7633           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7634         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7635       case TLSModel::LocalDynamic:
7636         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7637                                            Subtarget->is64Bit());
7638       case TLSModel::InitialExec:
7639       case TLSModel::LocalExec:
7640         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7641                                    Subtarget->is64Bit(),
7642                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7643     }
7644     llvm_unreachable("Unknown TLS model.");
7645   }
7646
7647   if (Subtarget->isTargetDarwin()) {
7648     // Darwin only has one model of TLS.  Lower to that.
7649     unsigned char OpFlag = 0;
7650     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7651                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7652
7653     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7654     // global base reg.
7655     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7656                   !Subtarget->is64Bit();
7657     if (PIC32)
7658       OpFlag = X86II::MO_TLVP_PIC_BASE;
7659     else
7660       OpFlag = X86II::MO_TLVP;
7661     DebugLoc DL = Op.getDebugLoc();
7662     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7663                                                 GA->getValueType(0),
7664                                                 GA->getOffset(), OpFlag);
7665     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7666
7667     // With PIC32, the address is actually $g + Offset.
7668     if (PIC32)
7669       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7670                            DAG.getNode(X86ISD::GlobalBaseReg,
7671                                        DebugLoc(), getPointerTy()),
7672                            Offset);
7673
7674     // Lowering the machine isd will make sure everything is in the right
7675     // location.
7676     SDValue Chain = DAG.getEntryNode();
7677     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7678     SDValue Args[] = { Chain, Offset };
7679     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7680
7681     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7682     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7683     MFI->setAdjustsStack(true);
7684
7685     // And our return value (tls address) is in the standard call return value
7686     // location.
7687     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7688     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7689                               Chain.getValue(1));
7690   }
7691
7692   if (Subtarget->isTargetWindows()) {
7693     // Just use the implicit TLS architecture
7694     // Need to generate someting similar to:
7695     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7696     //                                  ; from TEB
7697     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7698     //   mov     rcx, qword [rdx+rcx*8]
7699     //   mov     eax, .tls$:tlsvar
7700     //   [rax+rcx] contains the address
7701     // Windows 64bit: gs:0x58
7702     // Windows 32bit: fs:__tls_array
7703
7704     // If GV is an alias then use the aliasee for determining
7705     // thread-localness.
7706     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7707       GV = GA->resolveAliasedGlobal(false);
7708     DebugLoc dl = GA->getDebugLoc();
7709     SDValue Chain = DAG.getEntryNode();
7710
7711     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7712     // %gs:0x58 (64-bit).
7713     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7714                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7715                                                              256)
7716                                         : Type::getInt32PtrTy(*DAG.getContext(),
7717                                                               257));
7718
7719     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7720                                         Subtarget->is64Bit()
7721                                         ? DAG.getIntPtrConstant(0x58)
7722                                         : DAG.getExternalSymbol("_tls_array",
7723                                                                 getPointerTy()),
7724                                         MachinePointerInfo(Ptr),
7725                                         false, false, false, 0);
7726
7727     // Load the _tls_index variable
7728     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7729     if (Subtarget->is64Bit())
7730       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7731                            IDX, MachinePointerInfo(), MVT::i32,
7732                            false, false, 0);
7733     else
7734       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7735                         false, false, false, 0);
7736
7737     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7738                                     getPointerTy());
7739     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7740
7741     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7742     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7743                       false, false, false, 0);
7744
7745     // Get the offset of start of .tls section
7746     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7747                                              GA->getValueType(0),
7748                                              GA->getOffset(), X86II::MO_SECREL);
7749     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7750
7751     // The address of the thread local variable is the add of the thread
7752     // pointer with the offset of the variable.
7753     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7754   }
7755
7756   llvm_unreachable("TLS not implemented for this target.");
7757 }
7758
7759
7760 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7761 /// and take a 2 x i32 value to shift plus a shift amount.
7762 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7763   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7764   EVT VT = Op.getValueType();
7765   unsigned VTBits = VT.getSizeInBits();
7766   DebugLoc dl = Op.getDebugLoc();
7767   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7768   SDValue ShOpLo = Op.getOperand(0);
7769   SDValue ShOpHi = Op.getOperand(1);
7770   SDValue ShAmt  = Op.getOperand(2);
7771   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7772                                      DAG.getConstant(VTBits - 1, MVT::i8))
7773                        : DAG.getConstant(0, VT);
7774
7775   SDValue Tmp2, Tmp3;
7776   if (Op.getOpcode() == ISD::SHL_PARTS) {
7777     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7778     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7779   } else {
7780     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7781     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7782   }
7783
7784   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7785                                 DAG.getConstant(VTBits, MVT::i8));
7786   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7787                              AndNode, DAG.getConstant(0, MVT::i8));
7788
7789   SDValue Hi, Lo;
7790   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7791   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7792   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7793
7794   if (Op.getOpcode() == ISD::SHL_PARTS) {
7795     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7796     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7797   } else {
7798     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7799     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7800   }
7801
7802   SDValue Ops[2] = { Lo, Hi };
7803   return DAG.getMergeValues(Ops, 2, dl);
7804 }
7805
7806 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7807                                            SelectionDAG &DAG) const {
7808   EVT SrcVT = Op.getOperand(0).getValueType();
7809
7810   if (SrcVT.isVector())
7811     return SDValue();
7812
7813   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7814          "Unknown SINT_TO_FP to lower!");
7815
7816   // These are really Legal; return the operand so the caller accepts it as
7817   // Legal.
7818   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7819     return Op;
7820   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7821       Subtarget->is64Bit()) {
7822     return Op;
7823   }
7824
7825   DebugLoc dl = Op.getDebugLoc();
7826   unsigned Size = SrcVT.getSizeInBits()/8;
7827   MachineFunction &MF = DAG.getMachineFunction();
7828   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7829   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7830   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7831                                StackSlot,
7832                                MachinePointerInfo::getFixedStack(SSFI),
7833                                false, false, 0);
7834   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7835 }
7836
7837 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7838                                      SDValue StackSlot,
7839                                      SelectionDAG &DAG) const {
7840   // Build the FILD
7841   DebugLoc DL = Op.getDebugLoc();
7842   SDVTList Tys;
7843   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7844   if (useSSE)
7845     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7846   else
7847     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7848
7849   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7850
7851   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7852   MachineMemOperand *MMO;
7853   if (FI) {
7854     int SSFI = FI->getIndex();
7855     MMO =
7856       DAG.getMachineFunction()
7857       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7858                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7859   } else {
7860     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7861     StackSlot = StackSlot.getOperand(1);
7862   }
7863   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7864   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7865                                            X86ISD::FILD, DL,
7866                                            Tys, Ops, array_lengthof(Ops),
7867                                            SrcVT, MMO);
7868
7869   if (useSSE) {
7870     Chain = Result.getValue(1);
7871     SDValue InFlag = Result.getValue(2);
7872
7873     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7874     // shouldn't be necessary except that RFP cannot be live across
7875     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7876     MachineFunction &MF = DAG.getMachineFunction();
7877     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7878     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7879     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7880     Tys = DAG.getVTList(MVT::Other);
7881     SDValue Ops[] = {
7882       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7883     };
7884     MachineMemOperand *MMO =
7885       DAG.getMachineFunction()
7886       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7887                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7888
7889     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7890                                     Ops, array_lengthof(Ops),
7891                                     Op.getValueType(), MMO);
7892     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7893                          MachinePointerInfo::getFixedStack(SSFI),
7894                          false, false, false, 0);
7895   }
7896
7897   return Result;
7898 }
7899
7900 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7901 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7902                                                SelectionDAG &DAG) const {
7903   // This algorithm is not obvious. Here it is what we're trying to output:
7904   /*
7905      movq       %rax,  %xmm0
7906      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7907      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7908      #ifdef __SSE3__
7909        haddpd   %xmm0, %xmm0
7910      #else
7911        pshufd   $0x4e, %xmm0, %xmm1
7912        addpd    %xmm1, %xmm0
7913      #endif
7914   */
7915
7916   DebugLoc dl = Op.getDebugLoc();
7917   LLVMContext *Context = DAG.getContext();
7918
7919   // Build some magic constants.
7920   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7921   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7922   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7923
7924   SmallVector<Constant*,2> CV1;
7925   CV1.push_back(
7926         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7927   CV1.push_back(
7928         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7929   Constant *C1 = ConstantVector::get(CV1);
7930   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7931
7932   // Load the 64-bit value into an XMM register.
7933   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7934                             Op.getOperand(0));
7935   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7936                               MachinePointerInfo::getConstantPool(),
7937                               false, false, false, 16);
7938   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7939                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7940                               CLod0);
7941
7942   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7943                               MachinePointerInfo::getConstantPool(),
7944                               false, false, false, 16);
7945   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7946   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7947   SDValue Result;
7948
7949   if (Subtarget->hasSSE3()) {
7950     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7951     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7952   } else {
7953     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7954     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7955                                            S2F, 0x4E, DAG);
7956     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7957                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7958                          Sub);
7959   }
7960
7961   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7962                      DAG.getIntPtrConstant(0));
7963 }
7964
7965 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7966 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7967                                                SelectionDAG &DAG) const {
7968   DebugLoc dl = Op.getDebugLoc();
7969   // FP constant to bias correct the final result.
7970   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7971                                    MVT::f64);
7972
7973   // Load the 32-bit value into an XMM register.
7974   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7975                              Op.getOperand(0));
7976
7977   // Zero out the upper parts of the register.
7978   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7979
7980   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7981                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7982                      DAG.getIntPtrConstant(0));
7983
7984   // Or the load with the bias.
7985   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7986                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7987                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7988                                                    MVT::v2f64, Load)),
7989                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7990                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7991                                                    MVT::v2f64, Bias)));
7992   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7993                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7994                    DAG.getIntPtrConstant(0));
7995
7996   // Subtract the bias.
7997   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7998
7999   // Handle final rounding.
8000   EVT DestVT = Op.getValueType();
8001
8002   if (DestVT.bitsLT(MVT::f64))
8003     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8004                        DAG.getIntPtrConstant(0));
8005   if (DestVT.bitsGT(MVT::f64))
8006     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8007
8008   // Handle final rounding.
8009   return Sub;
8010 }
8011
8012 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8013                                            SelectionDAG &DAG) const {
8014   SDValue N0 = Op.getOperand(0);
8015   DebugLoc dl = Op.getDebugLoc();
8016
8017   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8018   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8019   // the optimization here.
8020   if (DAG.SignBitIsZero(N0))
8021     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8022
8023   EVT SrcVT = N0.getValueType();
8024   EVT DstVT = Op.getValueType();
8025   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8026     return LowerUINT_TO_FP_i64(Op, DAG);
8027   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8028     return LowerUINT_TO_FP_i32(Op, DAG);
8029   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8030     return SDValue();
8031
8032   // Make a 64-bit buffer, and use it to build an FILD.
8033   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8034   if (SrcVT == MVT::i32) {
8035     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8036     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8037                                      getPointerTy(), StackSlot, WordOff);
8038     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8039                                   StackSlot, MachinePointerInfo(),
8040                                   false, false, 0);
8041     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8042                                   OffsetSlot, MachinePointerInfo(),
8043                                   false, false, 0);
8044     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8045     return Fild;
8046   }
8047
8048   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8049   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8050                                StackSlot, MachinePointerInfo(),
8051                                false, false, 0);
8052   // For i64 source, we need to add the appropriate power of 2 if the input
8053   // was negative.  This is the same as the optimization in
8054   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8055   // we must be careful to do the computation in x87 extended precision, not
8056   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8057   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8058   MachineMemOperand *MMO =
8059     DAG.getMachineFunction()
8060     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8061                           MachineMemOperand::MOLoad, 8, 8);
8062
8063   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8064   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8065   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8066                                          MVT::i64, MMO);
8067
8068   APInt FF(32, 0x5F800000ULL);
8069
8070   // Check whether the sign bit is set.
8071   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8072                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8073                                  ISD::SETLT);
8074
8075   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8076   SDValue FudgePtr = DAG.getConstantPool(
8077                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8078                                          getPointerTy());
8079
8080   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8081   SDValue Zero = DAG.getIntPtrConstant(0);
8082   SDValue Four = DAG.getIntPtrConstant(4);
8083   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8084                                Zero, Four);
8085   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8086
8087   // Load the value out, extending it from f32 to f80.
8088   // FIXME: Avoid the extend by constructing the right constant pool?
8089   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8090                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8091                                  MVT::f32, false, false, 4);
8092   // Extend everything to 80 bits to force it to be done on x87.
8093   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8094   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8095 }
8096
8097 std::pair<SDValue,SDValue> X86TargetLowering::
8098 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8099   DebugLoc DL = Op.getDebugLoc();
8100
8101   EVT DstTy = Op.getValueType();
8102
8103   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8104     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8105     DstTy = MVT::i64;
8106   }
8107
8108   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8109          DstTy.getSimpleVT() >= MVT::i16 &&
8110          "Unknown FP_TO_INT to lower!");
8111
8112   // These are really Legal.
8113   if (DstTy == MVT::i32 &&
8114       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8115     return std::make_pair(SDValue(), SDValue());
8116   if (Subtarget->is64Bit() &&
8117       DstTy == MVT::i64 &&
8118       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8119     return std::make_pair(SDValue(), SDValue());
8120
8121   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8122   // stack slot, or into the FTOL runtime function.
8123   MachineFunction &MF = DAG.getMachineFunction();
8124   unsigned MemSize = DstTy.getSizeInBits()/8;
8125   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8126   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8127
8128   unsigned Opc;
8129   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8130     Opc = X86ISD::WIN_FTOL;
8131   else
8132     switch (DstTy.getSimpleVT().SimpleTy) {
8133     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8134     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8135     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8136     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8137     }
8138
8139   SDValue Chain = DAG.getEntryNode();
8140   SDValue Value = Op.getOperand(0);
8141   EVT TheVT = Op.getOperand(0).getValueType();
8142   // FIXME This causes a redundant load/store if the SSE-class value is already
8143   // in memory, such as if it is on the callstack.
8144   if (isScalarFPTypeInSSEReg(TheVT)) {
8145     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8146     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8147                          MachinePointerInfo::getFixedStack(SSFI),
8148                          false, false, 0);
8149     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8150     SDValue Ops[] = {
8151       Chain, StackSlot, DAG.getValueType(TheVT)
8152     };
8153
8154     MachineMemOperand *MMO =
8155       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8156                               MachineMemOperand::MOLoad, MemSize, MemSize);
8157     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8158                                     DstTy, MMO);
8159     Chain = Value.getValue(1);
8160     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8161     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8162   }
8163
8164   MachineMemOperand *MMO =
8165     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8166                             MachineMemOperand::MOStore, MemSize, MemSize);
8167
8168   if (Opc != X86ISD::WIN_FTOL) {
8169     // Build the FP_TO_INT*_IN_MEM
8170     SDValue Ops[] = { Chain, Value, StackSlot };
8171     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8172                                            Ops, 3, DstTy, MMO);
8173     return std::make_pair(FIST, StackSlot);
8174   } else {
8175     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8176       DAG.getVTList(MVT::Other, MVT::Glue),
8177       Chain, Value);
8178     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8179       MVT::i32, ftol.getValue(1));
8180     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8181       MVT::i32, eax.getValue(2));
8182     SDValue Ops[] = { eax, edx };
8183     SDValue pair = IsReplace
8184       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8185       : DAG.getMergeValues(Ops, 2, DL);
8186     return std::make_pair(pair, SDValue());
8187   }
8188 }
8189
8190 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8191   DebugLoc DL = Op.getDebugLoc();
8192   EVT VT = Op.getValueType();
8193   EVT SVT = Op.getOperand(0).getValueType();
8194
8195   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8196       VT.getVectorNumElements() != SVT.getVectorNumElements())
8197     return SDValue();
8198
8199   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8200
8201   unsigned NumElems = VT.getVectorNumElements();
8202   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8203                              NumElems * 2);
8204
8205   SDValue In = Op.getOperand(0);
8206   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8207   // Prepare truncation shuffle mask
8208   for (unsigned i = 0; i != NumElems; ++i)
8209     MaskVec[i] = i * 2;
8210   SDValue V = DAG.getVectorShuffle(NVT, DL,
8211                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8212                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8213   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8214                      DAG.getIntPtrConstant(0));
8215 }
8216
8217 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8218                                            SelectionDAG &DAG) const {
8219   if (Op.getValueType().isVector()) {
8220     if (Op.getValueType() == MVT::v8i16)
8221       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8222                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8223                                      MVT::v8i32, Op.getOperand(0)));
8224     return SDValue();
8225   }
8226
8227   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8228     /*IsSigned=*/ true, /*IsReplace=*/ false);
8229   SDValue FIST = Vals.first, StackSlot = Vals.second;
8230   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8231   if (FIST.getNode() == 0) return Op;
8232
8233   if (StackSlot.getNode())
8234     // Load the result.
8235     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8236                        FIST, StackSlot, MachinePointerInfo(),
8237                        false, false, false, 0);
8238
8239   // The node is the result.
8240   return FIST;
8241 }
8242
8243 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8244                                            SelectionDAG &DAG) const {
8245   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8246     /*IsSigned=*/ false, /*IsReplace=*/ false);
8247   SDValue FIST = Vals.first, StackSlot = Vals.second;
8248   assert(FIST.getNode() && "Unexpected failure");
8249
8250   if (StackSlot.getNode())
8251     // Load the result.
8252     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8253                        FIST, StackSlot, MachinePointerInfo(),
8254                        false, false, false, 0);
8255
8256   // The node is the result.
8257   return FIST;
8258 }
8259
8260 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8261                                           SelectionDAG &DAG) const {
8262   DebugLoc DL = Op.getDebugLoc();
8263   EVT VT = Op.getValueType();
8264   SDValue In = Op.getOperand(0);
8265   EVT SVT = In.getValueType();
8266
8267   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8268
8269   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8270                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8271                                  In, DAG.getUNDEF(SVT)));
8272 }
8273
8274 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8275   LLVMContext *Context = DAG.getContext();
8276   DebugLoc dl = Op.getDebugLoc();
8277   EVT VT = Op.getValueType();
8278   EVT EltVT = VT;
8279   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8280   if (VT.isVector()) {
8281     EltVT = VT.getVectorElementType();
8282     NumElts = VT.getVectorNumElements();
8283   }
8284   Constant *C;
8285   if (EltVT == MVT::f64)
8286     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8287   else
8288     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8289   C = ConstantVector::getSplat(NumElts, C);
8290   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8291   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8292   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8293                              MachinePointerInfo::getConstantPool(),
8294                              false, false, false, Alignment);
8295   if (VT.isVector()) {
8296     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8297     return DAG.getNode(ISD::BITCAST, dl, VT,
8298                        DAG.getNode(ISD::AND, dl, ANDVT,
8299                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8300                                                Op.getOperand(0)),
8301                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8302   }
8303   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8304 }
8305
8306 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8307   LLVMContext *Context = DAG.getContext();
8308   DebugLoc dl = Op.getDebugLoc();
8309   EVT VT = Op.getValueType();
8310   EVT EltVT = VT;
8311   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8312   if (VT.isVector()) {
8313     EltVT = VT.getVectorElementType();
8314     NumElts = VT.getVectorNumElements();
8315   }
8316   Constant *C;
8317   if (EltVT == MVT::f64)
8318     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8319   else
8320     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8321   C = ConstantVector::getSplat(NumElts, C);
8322   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8323   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8324   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8325                              MachinePointerInfo::getConstantPool(),
8326                              false, false, false, Alignment);
8327   if (VT.isVector()) {
8328     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8329     return DAG.getNode(ISD::BITCAST, dl, VT,
8330                        DAG.getNode(ISD::XOR, dl, XORVT,
8331                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8332                                                Op.getOperand(0)),
8333                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8334   }
8335
8336   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8337 }
8338
8339 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8340   LLVMContext *Context = DAG.getContext();
8341   SDValue Op0 = Op.getOperand(0);
8342   SDValue Op1 = Op.getOperand(1);
8343   DebugLoc dl = Op.getDebugLoc();
8344   EVT VT = Op.getValueType();
8345   EVT SrcVT = Op1.getValueType();
8346
8347   // If second operand is smaller, extend it first.
8348   if (SrcVT.bitsLT(VT)) {
8349     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8350     SrcVT = VT;
8351   }
8352   // And if it is bigger, shrink it first.
8353   if (SrcVT.bitsGT(VT)) {
8354     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8355     SrcVT = VT;
8356   }
8357
8358   // At this point the operands and the result should have the same
8359   // type, and that won't be f80 since that is not custom lowered.
8360
8361   // First get the sign bit of second operand.
8362   SmallVector<Constant*,4> CV;
8363   if (SrcVT == MVT::f64) {
8364     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8365     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8366   } else {
8367     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8368     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8369     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8370     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8371   }
8372   Constant *C = ConstantVector::get(CV);
8373   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8374   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8375                               MachinePointerInfo::getConstantPool(),
8376                               false, false, false, 16);
8377   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8378
8379   // Shift sign bit right or left if the two operands have different types.
8380   if (SrcVT.bitsGT(VT)) {
8381     // Op0 is MVT::f32, Op1 is MVT::f64.
8382     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8383     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8384                           DAG.getConstant(32, MVT::i32));
8385     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8386     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8387                           DAG.getIntPtrConstant(0));
8388   }
8389
8390   // Clear first operand sign bit.
8391   CV.clear();
8392   if (VT == MVT::f64) {
8393     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8394     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8395   } else {
8396     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8397     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8398     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8399     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8400   }
8401   C = ConstantVector::get(CV);
8402   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8403   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8404                               MachinePointerInfo::getConstantPool(),
8405                               false, false, false, 16);
8406   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8407
8408   // Or the value with the sign bit.
8409   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8410 }
8411
8412 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8413   SDValue N0 = Op.getOperand(0);
8414   DebugLoc dl = Op.getDebugLoc();
8415   EVT VT = Op.getValueType();
8416
8417   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8418   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8419                                   DAG.getConstant(1, VT));
8420   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8421 }
8422
8423 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8424 //
8425 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8426   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8427
8428   if (!Subtarget->hasSSE41())
8429     return SDValue();
8430
8431   if (!Op->hasOneUse())
8432     return SDValue();
8433
8434   SDNode *N = Op.getNode();
8435   DebugLoc DL = N->getDebugLoc();
8436
8437   SmallVector<SDValue, 8> Opnds;
8438   DenseMap<SDValue, unsigned> VecInMap;
8439   EVT VT = MVT::Other;
8440
8441   // Recognize a special case where a vector is casted into wide integer to
8442   // test all 0s.
8443   Opnds.push_back(N->getOperand(0));
8444   Opnds.push_back(N->getOperand(1));
8445
8446   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8447     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8448     // BFS traverse all OR'd operands.
8449     if (I->getOpcode() == ISD::OR) {
8450       Opnds.push_back(I->getOperand(0));
8451       Opnds.push_back(I->getOperand(1));
8452       // Re-evaluate the number of nodes to be traversed.
8453       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8454       continue;
8455     }
8456
8457     // Quit if a non-EXTRACT_VECTOR_ELT
8458     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8459       return SDValue();
8460
8461     // Quit if without a constant index.
8462     SDValue Idx = I->getOperand(1);
8463     if (!isa<ConstantSDNode>(Idx))
8464       return SDValue();
8465
8466     SDValue ExtractedFromVec = I->getOperand(0);
8467     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8468     if (M == VecInMap.end()) {
8469       VT = ExtractedFromVec.getValueType();
8470       // Quit if not 128/256-bit vector.
8471       if (!VT.is128BitVector() && !VT.is256BitVector())
8472         return SDValue();
8473       // Quit if not the same type.
8474       if (VecInMap.begin() != VecInMap.end() &&
8475           VT != VecInMap.begin()->first.getValueType())
8476         return SDValue();
8477       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8478     }
8479     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8480   }
8481
8482   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8483          "Not extracted from 128-/256-bit vector.");
8484
8485   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8486   SmallVector<SDValue, 8> VecIns;
8487
8488   for (DenseMap<SDValue, unsigned>::const_iterator
8489         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8490     // Quit if not all elements are used.
8491     if (I->second != FullMask)
8492       return SDValue();
8493     VecIns.push_back(I->first);
8494   }
8495
8496   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8497
8498   // Cast all vectors into TestVT for PTEST.
8499   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8500     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8501
8502   // If more than one full vectors are evaluated, OR them first before PTEST.
8503   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8504     // Each iteration will OR 2 nodes and append the result until there is only
8505     // 1 node left, i.e. the final OR'd value of all vectors.
8506     SDValue LHS = VecIns[Slot];
8507     SDValue RHS = VecIns[Slot + 1];
8508     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8509   }
8510
8511   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8512                      VecIns.back(), VecIns.back());
8513 }
8514
8515 /// Emit nodes that will be selected as "test Op0,Op0", or something
8516 /// equivalent.
8517 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8518                                     SelectionDAG &DAG) const {
8519   DebugLoc dl = Op.getDebugLoc();
8520
8521   // CF and OF aren't always set the way we want. Determine which
8522   // of these we need.
8523   bool NeedCF = false;
8524   bool NeedOF = false;
8525   switch (X86CC) {
8526   default: break;
8527   case X86::COND_A: case X86::COND_AE:
8528   case X86::COND_B: case X86::COND_BE:
8529     NeedCF = true;
8530     break;
8531   case X86::COND_G: case X86::COND_GE:
8532   case X86::COND_L: case X86::COND_LE:
8533   case X86::COND_O: case X86::COND_NO:
8534     NeedOF = true;
8535     break;
8536   }
8537
8538   // See if we can use the EFLAGS value from the operand instead of
8539   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8540   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8541   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8542     // Emit a CMP with 0, which is the TEST pattern.
8543     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8544                        DAG.getConstant(0, Op.getValueType()));
8545
8546   unsigned Opcode = 0;
8547   unsigned NumOperands = 0;
8548
8549   // Truncate operations may prevent the merge of the SETCC instruction
8550   // and the arithmetic intruction before it. Attempt to truncate the operands
8551   // of the arithmetic instruction and use a reduced bit-width instruction.
8552   bool NeedTruncation = false;
8553   SDValue ArithOp = Op;
8554   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8555     SDValue Arith = Op->getOperand(0);
8556     // Both the trunc and the arithmetic op need to have one user each.
8557     if (Arith->hasOneUse())
8558       switch (Arith.getOpcode()) {
8559         default: break;
8560         case ISD::ADD:
8561         case ISD::SUB:
8562         case ISD::AND:
8563         case ISD::OR:
8564         case ISD::XOR: {
8565           NeedTruncation = true;
8566           ArithOp = Arith;
8567         }
8568       }
8569   }
8570
8571   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8572   // which may be the result of a CAST.  We use the variable 'Op', which is the
8573   // non-casted variable when we check for possible users.
8574   switch (ArithOp.getOpcode()) {
8575   case ISD::ADD:
8576     // Due to an isel shortcoming, be conservative if this add is likely to be
8577     // selected as part of a load-modify-store instruction. When the root node
8578     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8579     // uses of other nodes in the match, such as the ADD in this case. This
8580     // leads to the ADD being left around and reselected, with the result being
8581     // two adds in the output.  Alas, even if none our users are stores, that
8582     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8583     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8584     // climbing the DAG back to the root, and it doesn't seem to be worth the
8585     // effort.
8586     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8587          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8588       if (UI->getOpcode() != ISD::CopyToReg &&
8589           UI->getOpcode() != ISD::SETCC &&
8590           UI->getOpcode() != ISD::STORE)
8591         goto default_case;
8592
8593     if (ConstantSDNode *C =
8594         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8595       // An add of one will be selected as an INC.
8596       if (C->getAPIntValue() == 1) {
8597         Opcode = X86ISD::INC;
8598         NumOperands = 1;
8599         break;
8600       }
8601
8602       // An add of negative one (subtract of one) will be selected as a DEC.
8603       if (C->getAPIntValue().isAllOnesValue()) {
8604         Opcode = X86ISD::DEC;
8605         NumOperands = 1;
8606         break;
8607       }
8608     }
8609
8610     // Otherwise use a regular EFLAGS-setting add.
8611     Opcode = X86ISD::ADD;
8612     NumOperands = 2;
8613     break;
8614   case ISD::AND: {
8615     // If the primary and result isn't used, don't bother using X86ISD::AND,
8616     // because a TEST instruction will be better.
8617     bool NonFlagUse = false;
8618     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8619            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8620       SDNode *User = *UI;
8621       unsigned UOpNo = UI.getOperandNo();
8622       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8623         // Look pass truncate.
8624         UOpNo = User->use_begin().getOperandNo();
8625         User = *User->use_begin();
8626       }
8627
8628       if (User->getOpcode() != ISD::BRCOND &&
8629           User->getOpcode() != ISD::SETCC &&
8630           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8631         NonFlagUse = true;
8632         break;
8633       }
8634     }
8635
8636     if (!NonFlagUse)
8637       break;
8638   }
8639     // FALL THROUGH
8640   case ISD::SUB:
8641   case ISD::OR:
8642   case ISD::XOR:
8643     // Due to the ISEL shortcoming noted above, be conservative if this op is
8644     // likely to be selected as part of a load-modify-store instruction.
8645     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8646            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8647       if (UI->getOpcode() == ISD::STORE)
8648         goto default_case;
8649
8650     // Otherwise use a regular EFLAGS-setting instruction.
8651     switch (ArithOp.getOpcode()) {
8652     default: llvm_unreachable("unexpected operator!");
8653     case ISD::SUB: Opcode = X86ISD::SUB; break;
8654     case ISD::XOR: Opcode = X86ISD::XOR; break;
8655     case ISD::AND: Opcode = X86ISD::AND; break;
8656     case ISD::OR: {
8657       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8658         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8659         if (EFLAGS.getNode())
8660           return EFLAGS;
8661       }
8662       Opcode = X86ISD::OR;
8663       break;
8664     }
8665     }
8666
8667     NumOperands = 2;
8668     break;
8669   case X86ISD::ADD:
8670   case X86ISD::SUB:
8671   case X86ISD::INC:
8672   case X86ISD::DEC:
8673   case X86ISD::OR:
8674   case X86ISD::XOR:
8675   case X86ISD::AND:
8676     return SDValue(Op.getNode(), 1);
8677   default:
8678   default_case:
8679     break;
8680   }
8681
8682   // If we found that truncation is beneficial, perform the truncation and
8683   // update 'Op'.
8684   if (NeedTruncation) {
8685     EVT VT = Op.getValueType();
8686     SDValue WideVal = Op->getOperand(0);
8687     EVT WideVT = WideVal.getValueType();
8688     unsigned ConvertedOp = 0;
8689     // Use a target machine opcode to prevent further DAGCombine
8690     // optimizations that may separate the arithmetic operations
8691     // from the setcc node.
8692     switch (WideVal.getOpcode()) {
8693       default: break;
8694       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8695       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8696       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8697       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8698       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8699     }
8700
8701     if (ConvertedOp) {
8702       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8703       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8704         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8705         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8706         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8707       }
8708     }
8709   }
8710
8711   if (Opcode == 0)
8712     // Emit a CMP with 0, which is the TEST pattern.
8713     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8714                        DAG.getConstant(0, Op.getValueType()));
8715
8716   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8717   SmallVector<SDValue, 4> Ops;
8718   for (unsigned i = 0; i != NumOperands; ++i)
8719     Ops.push_back(Op.getOperand(i));
8720
8721   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8722   DAG.ReplaceAllUsesWith(Op, New);
8723   return SDValue(New.getNode(), 1);
8724 }
8725
8726 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8727 /// equivalent.
8728 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8729                                    SelectionDAG &DAG) const {
8730   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8731     if (C->getAPIntValue() == 0)
8732       return EmitTest(Op0, X86CC, DAG);
8733
8734   DebugLoc dl = Op0.getDebugLoc();
8735   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8736        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8737     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8738     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8739     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8740                               Op0, Op1);
8741     return SDValue(Sub.getNode(), 1);
8742   }
8743   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8744 }
8745
8746 /// Convert a comparison if required by the subtarget.
8747 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8748                                                  SelectionDAG &DAG) const {
8749   // If the subtarget does not support the FUCOMI instruction, floating-point
8750   // comparisons have to be converted.
8751   if (Subtarget->hasCMov() ||
8752       Cmp.getOpcode() != X86ISD::CMP ||
8753       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8754       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8755     return Cmp;
8756
8757   // The instruction selector will select an FUCOM instruction instead of
8758   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8759   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8760   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8761   DebugLoc dl = Cmp.getDebugLoc();
8762   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8763   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8764   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8765                             DAG.getConstant(8, MVT::i8));
8766   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8767   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8768 }
8769
8770 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8771 /// if it's possible.
8772 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8773                                      DebugLoc dl, SelectionDAG &DAG) const {
8774   SDValue Op0 = And.getOperand(0);
8775   SDValue Op1 = And.getOperand(1);
8776   if (Op0.getOpcode() == ISD::TRUNCATE)
8777     Op0 = Op0.getOperand(0);
8778   if (Op1.getOpcode() == ISD::TRUNCATE)
8779     Op1 = Op1.getOperand(0);
8780
8781   SDValue LHS, RHS;
8782   if (Op1.getOpcode() == ISD::SHL)
8783     std::swap(Op0, Op1);
8784   if (Op0.getOpcode() == ISD::SHL) {
8785     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8786       if (And00C->getZExtValue() == 1) {
8787         // If we looked past a truncate, check that it's only truncating away
8788         // known zeros.
8789         unsigned BitWidth = Op0.getValueSizeInBits();
8790         unsigned AndBitWidth = And.getValueSizeInBits();
8791         if (BitWidth > AndBitWidth) {
8792           APInt Zeros, Ones;
8793           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8794           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8795             return SDValue();
8796         }
8797         LHS = Op1;
8798         RHS = Op0.getOperand(1);
8799       }
8800   } else if (Op1.getOpcode() == ISD::Constant) {
8801     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8802     uint64_t AndRHSVal = AndRHS->getZExtValue();
8803     SDValue AndLHS = Op0;
8804
8805     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8806       LHS = AndLHS.getOperand(0);
8807       RHS = AndLHS.getOperand(1);
8808     }
8809
8810     // Use BT if the immediate can't be encoded in a TEST instruction.
8811     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8812       LHS = AndLHS;
8813       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8814     }
8815   }
8816
8817   if (LHS.getNode()) {
8818     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8819     // instruction.  Since the shift amount is in-range-or-undefined, we know
8820     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8821     // the encoding for the i16 version is larger than the i32 version.
8822     // Also promote i16 to i32 for performance / code size reason.
8823     if (LHS.getValueType() == MVT::i8 ||
8824         LHS.getValueType() == MVT::i16)
8825       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8826
8827     // If the operand types disagree, extend the shift amount to match.  Since
8828     // BT ignores high bits (like shifts) we can use anyextend.
8829     if (LHS.getValueType() != RHS.getValueType())
8830       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8831
8832     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8833     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8834     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8835                        DAG.getConstant(Cond, MVT::i8), BT);
8836   }
8837
8838   return SDValue();
8839 }
8840
8841 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8842
8843   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8844
8845   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8846   SDValue Op0 = Op.getOperand(0);
8847   SDValue Op1 = Op.getOperand(1);
8848   DebugLoc dl = Op.getDebugLoc();
8849   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8850
8851   // Optimize to BT if possible.
8852   // Lower (X & (1 << N)) == 0 to BT(X, N).
8853   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8854   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8855   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8856       Op1.getOpcode() == ISD::Constant &&
8857       cast<ConstantSDNode>(Op1)->isNullValue() &&
8858       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8859     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8860     if (NewSetCC.getNode())
8861       return NewSetCC;
8862   }
8863
8864   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8865   // these.
8866   if (Op1.getOpcode() == ISD::Constant &&
8867       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8868        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8869       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8870
8871     // If the input is a setcc, then reuse the input setcc or use a new one with
8872     // the inverted condition.
8873     if (Op0.getOpcode() == X86ISD::SETCC) {
8874       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8875       bool Invert = (CC == ISD::SETNE) ^
8876         cast<ConstantSDNode>(Op1)->isNullValue();
8877       if (!Invert) return Op0;
8878
8879       CCode = X86::GetOppositeBranchCondition(CCode);
8880       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8881                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8882     }
8883   }
8884
8885   bool isFP = Op1.getValueType().isFloatingPoint();
8886   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8887   if (X86CC == X86::COND_INVALID)
8888     return SDValue();
8889
8890   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8891   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8892   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8893                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8894 }
8895
8896 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8897 // ones, and then concatenate the result back.
8898 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8899   EVT VT = Op.getValueType();
8900
8901   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8902          "Unsupported value type for operation");
8903
8904   unsigned NumElems = VT.getVectorNumElements();
8905   DebugLoc dl = Op.getDebugLoc();
8906   SDValue CC = Op.getOperand(2);
8907
8908   // Extract the LHS vectors
8909   SDValue LHS = Op.getOperand(0);
8910   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8911   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8912
8913   // Extract the RHS vectors
8914   SDValue RHS = Op.getOperand(1);
8915   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8916   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8917
8918   // Issue the operation on the smaller types and concatenate the result back
8919   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8920   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8921   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8922                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8923                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8924 }
8925
8926
8927 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8928   SDValue Cond;
8929   SDValue Op0 = Op.getOperand(0);
8930   SDValue Op1 = Op.getOperand(1);
8931   SDValue CC = Op.getOperand(2);
8932   EVT VT = Op.getValueType();
8933   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8934   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8935   DebugLoc dl = Op.getDebugLoc();
8936
8937   if (isFP) {
8938 #ifndef NDEBUG
8939     EVT EltVT = Op0.getValueType().getVectorElementType();
8940     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8941 #endif
8942
8943     unsigned SSECC;
8944     bool Swap = false;
8945
8946     // SSE Condition code mapping:
8947     //  0 - EQ
8948     //  1 - LT
8949     //  2 - LE
8950     //  3 - UNORD
8951     //  4 - NEQ
8952     //  5 - NLT
8953     //  6 - NLE
8954     //  7 - ORD
8955     switch (SetCCOpcode) {
8956     default: llvm_unreachable("Unexpected SETCC condition");
8957     case ISD::SETOEQ:
8958     case ISD::SETEQ:  SSECC = 0; break;
8959     case ISD::SETOGT:
8960     case ISD::SETGT: Swap = true; // Fallthrough
8961     case ISD::SETLT:
8962     case ISD::SETOLT: SSECC = 1; break;
8963     case ISD::SETOGE:
8964     case ISD::SETGE: Swap = true; // Fallthrough
8965     case ISD::SETLE:
8966     case ISD::SETOLE: SSECC = 2; break;
8967     case ISD::SETUO:  SSECC = 3; break;
8968     case ISD::SETUNE:
8969     case ISD::SETNE:  SSECC = 4; break;
8970     case ISD::SETULE: Swap = true; // Fallthrough
8971     case ISD::SETUGE: SSECC = 5; break;
8972     case ISD::SETULT: Swap = true; // Fallthrough
8973     case ISD::SETUGT: SSECC = 6; break;
8974     case ISD::SETO:   SSECC = 7; break;
8975     case ISD::SETUEQ:
8976     case ISD::SETONE: SSECC = 8; break;
8977     }
8978     if (Swap)
8979       std::swap(Op0, Op1);
8980
8981     // In the two special cases we can't handle, emit two comparisons.
8982     if (SSECC == 8) {
8983       unsigned CC0, CC1;
8984       unsigned CombineOpc;
8985       if (SetCCOpcode == ISD::SETUEQ) {
8986         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8987       } else {
8988         assert(SetCCOpcode == ISD::SETONE);
8989         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8990       }
8991
8992       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8993                                  DAG.getConstant(CC0, MVT::i8));
8994       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8995                                  DAG.getConstant(CC1, MVT::i8));
8996       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8997     }
8998     // Handle all other FP comparisons here.
8999     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9000                        DAG.getConstant(SSECC, MVT::i8));
9001   }
9002
9003   // Break 256-bit integer vector compare into smaller ones.
9004   if (VT.is256BitVector() && !Subtarget->hasAVX2())
9005     return Lower256IntVSETCC(Op, DAG);
9006
9007   // We are handling one of the integer comparisons here.  Since SSE only has
9008   // GT and EQ comparisons for integer, swapping operands and multiple
9009   // operations may be required for some comparisons.
9010   unsigned Opc;
9011   bool Swap = false, Invert = false, FlipSigns = false;
9012
9013   switch (SetCCOpcode) {
9014   default: llvm_unreachable("Unexpected SETCC condition");
9015   case ISD::SETNE:  Invert = true;
9016   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9017   case ISD::SETLT:  Swap = true;
9018   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9019   case ISD::SETGE:  Swap = true;
9020   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9021   case ISD::SETULT: Swap = true;
9022   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9023   case ISD::SETUGE: Swap = true;
9024   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9025   }
9026   if (Swap)
9027     std::swap(Op0, Op1);
9028
9029   // Check that the operation in question is available (most are plain SSE2,
9030   // but PCMPGTQ and PCMPEQQ have different requirements).
9031   if (VT == MVT::v2i64) {
9032     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9033       return SDValue();
9034     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9035       return SDValue();
9036   }
9037
9038   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9039   // bits of the inputs before performing those operations.
9040   if (FlipSigns) {
9041     EVT EltVT = VT.getVectorElementType();
9042     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9043                                       EltVT);
9044     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9045     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9046                                     SignBits.size());
9047     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9048     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9049   }
9050
9051   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9052
9053   // If the logical-not of the result is required, perform that now.
9054   if (Invert)
9055     Result = DAG.getNOT(dl, Result, VT);
9056
9057   return Result;
9058 }
9059
9060 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9061 static bool isX86LogicalCmp(SDValue Op) {
9062   unsigned Opc = Op.getNode()->getOpcode();
9063   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9064       Opc == X86ISD::SAHF)
9065     return true;
9066   if (Op.getResNo() == 1 &&
9067       (Opc == X86ISD::ADD ||
9068        Opc == X86ISD::SUB ||
9069        Opc == X86ISD::ADC ||
9070        Opc == X86ISD::SBB ||
9071        Opc == X86ISD::SMUL ||
9072        Opc == X86ISD::UMUL ||
9073        Opc == X86ISD::INC ||
9074        Opc == X86ISD::DEC ||
9075        Opc == X86ISD::OR ||
9076        Opc == X86ISD::XOR ||
9077        Opc == X86ISD::AND))
9078     return true;
9079
9080   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9081     return true;
9082
9083   return false;
9084 }
9085
9086 static bool isZero(SDValue V) {
9087   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9088   return C && C->isNullValue();
9089 }
9090
9091 static bool isAllOnes(SDValue V) {
9092   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9093   return C && C->isAllOnesValue();
9094 }
9095
9096 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9097   if (V.getOpcode() != ISD::TRUNCATE)
9098     return false;
9099
9100   SDValue VOp0 = V.getOperand(0);
9101   unsigned InBits = VOp0.getValueSizeInBits();
9102   unsigned Bits = V.getValueSizeInBits();
9103   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9104 }
9105
9106 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9107   bool addTest = true;
9108   SDValue Cond  = Op.getOperand(0);
9109   SDValue Op1 = Op.getOperand(1);
9110   SDValue Op2 = Op.getOperand(2);
9111   DebugLoc DL = Op.getDebugLoc();
9112   SDValue CC;
9113
9114   if (Cond.getOpcode() == ISD::SETCC) {
9115     SDValue NewCond = LowerSETCC(Cond, DAG);
9116     if (NewCond.getNode())
9117       Cond = NewCond;
9118   }
9119
9120   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9121   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9122   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9123   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9124   if (Cond.getOpcode() == X86ISD::SETCC &&
9125       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9126       isZero(Cond.getOperand(1).getOperand(1))) {
9127     SDValue Cmp = Cond.getOperand(1);
9128
9129     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9130
9131     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9132         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9133       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9134
9135       SDValue CmpOp0 = Cmp.getOperand(0);
9136       // Apply further optimizations for special cases
9137       // (select (x != 0), -1, 0) -> neg & sbb
9138       // (select (x == 0), 0, -1) -> neg & sbb
9139       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9140         if (YC->isNullValue() &&
9141             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9142           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9143           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9144                                     DAG.getConstant(0, CmpOp0.getValueType()),
9145                                     CmpOp0);
9146           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9147                                     DAG.getConstant(X86::COND_B, MVT::i8),
9148                                     SDValue(Neg.getNode(), 1));
9149           return Res;
9150         }
9151
9152       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9153                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9154       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9155
9156       SDValue Res =   // Res = 0 or -1.
9157         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9158                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9159
9160       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9161         Res = DAG.getNOT(DL, Res, Res.getValueType());
9162
9163       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9164       if (N2C == 0 || !N2C->isNullValue())
9165         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9166       return Res;
9167     }
9168   }
9169
9170   // Look past (and (setcc_carry (cmp ...)), 1).
9171   if (Cond.getOpcode() == ISD::AND &&
9172       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9173     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9174     if (C && C->getAPIntValue() == 1)
9175       Cond = Cond.getOperand(0);
9176   }
9177
9178   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9179   // setting operand in place of the X86ISD::SETCC.
9180   unsigned CondOpcode = Cond.getOpcode();
9181   if (CondOpcode == X86ISD::SETCC ||
9182       CondOpcode == X86ISD::SETCC_CARRY) {
9183     CC = Cond.getOperand(0);
9184
9185     SDValue Cmp = Cond.getOperand(1);
9186     unsigned Opc = Cmp.getOpcode();
9187     EVT VT = Op.getValueType();
9188
9189     bool IllegalFPCMov = false;
9190     if (VT.isFloatingPoint() && !VT.isVector() &&
9191         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9192       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9193
9194     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9195         Opc == X86ISD::BT) { // FIXME
9196       Cond = Cmp;
9197       addTest = false;
9198     }
9199   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9200              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9201              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9202               Cond.getOperand(0).getValueType() != MVT::i8)) {
9203     SDValue LHS = Cond.getOperand(0);
9204     SDValue RHS = Cond.getOperand(1);
9205     unsigned X86Opcode;
9206     unsigned X86Cond;
9207     SDVTList VTs;
9208     switch (CondOpcode) {
9209     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9210     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9211     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9212     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9213     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9214     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9215     default: llvm_unreachable("unexpected overflowing operator");
9216     }
9217     if (CondOpcode == ISD::UMULO)
9218       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9219                           MVT::i32);
9220     else
9221       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9222
9223     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9224
9225     if (CondOpcode == ISD::UMULO)
9226       Cond = X86Op.getValue(2);
9227     else
9228       Cond = X86Op.getValue(1);
9229
9230     CC = DAG.getConstant(X86Cond, MVT::i8);
9231     addTest = false;
9232   }
9233
9234   if (addTest) {
9235     // Look pass the truncate if the high bits are known zero.
9236     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9237         Cond = Cond.getOperand(0);
9238
9239     // We know the result of AND is compared against zero. Try to match
9240     // it to BT.
9241     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9242       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9243       if (NewSetCC.getNode()) {
9244         CC = NewSetCC.getOperand(0);
9245         Cond = NewSetCC.getOperand(1);
9246         addTest = false;
9247       }
9248     }
9249   }
9250
9251   if (addTest) {
9252     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9253     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9254   }
9255
9256   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9257   // a <  b ?  0 : -1 -> RES = setcc_carry
9258   // a >= b ? -1 :  0 -> RES = setcc_carry
9259   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9260   if (Cond.getOpcode() == X86ISD::SUB) {
9261     Cond = ConvertCmpIfNecessary(Cond, DAG);
9262     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9263
9264     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9265         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9266       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9267                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9268       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9269         return DAG.getNOT(DL, Res, Res.getValueType());
9270       return Res;
9271     }
9272   }
9273
9274   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9275   // widen the cmov and push the truncate through. This avoids introducing a new
9276   // branch during isel and doesn't add any extensions.
9277   if (Op.getValueType() == MVT::i8 &&
9278       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9279     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9280     if (T1.getValueType() == T2.getValueType() &&
9281         // Blacklist CopyFromReg to avoid partial register stalls.
9282         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9283       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9284       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9285       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9286     }
9287   }
9288
9289   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9290   // condition is true.
9291   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9292   SDValue Ops[] = { Op2, Op1, CC, Cond };
9293   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9294 }
9295
9296 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9297 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9298 // from the AND / OR.
9299 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9300   Opc = Op.getOpcode();
9301   if (Opc != ISD::OR && Opc != ISD::AND)
9302     return false;
9303   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9304           Op.getOperand(0).hasOneUse() &&
9305           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9306           Op.getOperand(1).hasOneUse());
9307 }
9308
9309 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9310 // 1 and that the SETCC node has a single use.
9311 static bool isXor1OfSetCC(SDValue Op) {
9312   if (Op.getOpcode() != ISD::XOR)
9313     return false;
9314   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9315   if (N1C && N1C->getAPIntValue() == 1) {
9316     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9317       Op.getOperand(0).hasOneUse();
9318   }
9319   return false;
9320 }
9321
9322 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9323   bool addTest = true;
9324   SDValue Chain = Op.getOperand(0);
9325   SDValue Cond  = Op.getOperand(1);
9326   SDValue Dest  = Op.getOperand(2);
9327   DebugLoc dl = Op.getDebugLoc();
9328   SDValue CC;
9329   bool Inverted = false;
9330
9331   if (Cond.getOpcode() == ISD::SETCC) {
9332     // Check for setcc([su]{add,sub,mul}o == 0).
9333     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9334         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9335         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9336         Cond.getOperand(0).getResNo() == 1 &&
9337         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9338          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9339          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9340          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9341          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9342          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9343       Inverted = true;
9344       Cond = Cond.getOperand(0);
9345     } else {
9346       SDValue NewCond = LowerSETCC(Cond, DAG);
9347       if (NewCond.getNode())
9348         Cond = NewCond;
9349     }
9350   }
9351 #if 0
9352   // FIXME: LowerXALUO doesn't handle these!!
9353   else if (Cond.getOpcode() == X86ISD::ADD  ||
9354            Cond.getOpcode() == X86ISD::SUB  ||
9355            Cond.getOpcode() == X86ISD::SMUL ||
9356            Cond.getOpcode() == X86ISD::UMUL)
9357     Cond = LowerXALUO(Cond, DAG);
9358 #endif
9359
9360   // Look pass (and (setcc_carry (cmp ...)), 1).
9361   if (Cond.getOpcode() == ISD::AND &&
9362       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9363     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9364     if (C && C->getAPIntValue() == 1)
9365       Cond = Cond.getOperand(0);
9366   }
9367
9368   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9369   // setting operand in place of the X86ISD::SETCC.
9370   unsigned CondOpcode = Cond.getOpcode();
9371   if (CondOpcode == X86ISD::SETCC ||
9372       CondOpcode == X86ISD::SETCC_CARRY) {
9373     CC = Cond.getOperand(0);
9374
9375     SDValue Cmp = Cond.getOperand(1);
9376     unsigned Opc = Cmp.getOpcode();
9377     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9378     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9379       Cond = Cmp;
9380       addTest = false;
9381     } else {
9382       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9383       default: break;
9384       case X86::COND_O:
9385       case X86::COND_B:
9386         // These can only come from an arithmetic instruction with overflow,
9387         // e.g. SADDO, UADDO.
9388         Cond = Cond.getNode()->getOperand(1);
9389         addTest = false;
9390         break;
9391       }
9392     }
9393   }
9394   CondOpcode = Cond.getOpcode();
9395   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9396       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9397       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9398        Cond.getOperand(0).getValueType() != MVT::i8)) {
9399     SDValue LHS = Cond.getOperand(0);
9400     SDValue RHS = Cond.getOperand(1);
9401     unsigned X86Opcode;
9402     unsigned X86Cond;
9403     SDVTList VTs;
9404     switch (CondOpcode) {
9405     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9406     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9407     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9408     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9409     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9410     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9411     default: llvm_unreachable("unexpected overflowing operator");
9412     }
9413     if (Inverted)
9414       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9415     if (CondOpcode == ISD::UMULO)
9416       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9417                           MVT::i32);
9418     else
9419       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9420
9421     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9422
9423     if (CondOpcode == ISD::UMULO)
9424       Cond = X86Op.getValue(2);
9425     else
9426       Cond = X86Op.getValue(1);
9427
9428     CC = DAG.getConstant(X86Cond, MVT::i8);
9429     addTest = false;
9430   } else {
9431     unsigned CondOpc;
9432     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9433       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9434       if (CondOpc == ISD::OR) {
9435         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9436         // two branches instead of an explicit OR instruction with a
9437         // separate test.
9438         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9439             isX86LogicalCmp(Cmp)) {
9440           CC = Cond.getOperand(0).getOperand(0);
9441           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9442                               Chain, Dest, CC, Cmp);
9443           CC = Cond.getOperand(1).getOperand(0);
9444           Cond = Cmp;
9445           addTest = false;
9446         }
9447       } else { // ISD::AND
9448         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9449         // two branches instead of an explicit AND instruction with a
9450         // separate test. However, we only do this if this block doesn't
9451         // have a fall-through edge, because this requires an explicit
9452         // jmp when the condition is false.
9453         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9454             isX86LogicalCmp(Cmp) &&
9455             Op.getNode()->hasOneUse()) {
9456           X86::CondCode CCode =
9457             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9458           CCode = X86::GetOppositeBranchCondition(CCode);
9459           CC = DAG.getConstant(CCode, MVT::i8);
9460           SDNode *User = *Op.getNode()->use_begin();
9461           // Look for an unconditional branch following this conditional branch.
9462           // We need this because we need to reverse the successors in order
9463           // to implement FCMP_OEQ.
9464           if (User->getOpcode() == ISD::BR) {
9465             SDValue FalseBB = User->getOperand(1);
9466             SDNode *NewBR =
9467               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9468             assert(NewBR == User);
9469             (void)NewBR;
9470             Dest = FalseBB;
9471
9472             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9473                                 Chain, Dest, CC, Cmp);
9474             X86::CondCode CCode =
9475               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9476             CCode = X86::GetOppositeBranchCondition(CCode);
9477             CC = DAG.getConstant(CCode, MVT::i8);
9478             Cond = Cmp;
9479             addTest = false;
9480           }
9481         }
9482       }
9483     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9484       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9485       // It should be transformed during dag combiner except when the condition
9486       // is set by a arithmetics with overflow node.
9487       X86::CondCode CCode =
9488         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9489       CCode = X86::GetOppositeBranchCondition(CCode);
9490       CC = DAG.getConstant(CCode, MVT::i8);
9491       Cond = Cond.getOperand(0).getOperand(1);
9492       addTest = false;
9493     } else if (Cond.getOpcode() == ISD::SETCC &&
9494                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9495       // For FCMP_OEQ, we can emit
9496       // two branches instead of an explicit AND instruction with a
9497       // separate test. However, we only do this if this block doesn't
9498       // have a fall-through edge, because this requires an explicit
9499       // jmp when the condition is false.
9500       if (Op.getNode()->hasOneUse()) {
9501         SDNode *User = *Op.getNode()->use_begin();
9502         // Look for an unconditional branch following this conditional branch.
9503         // We need this because we need to reverse the successors in order
9504         // to implement FCMP_OEQ.
9505         if (User->getOpcode() == ISD::BR) {
9506           SDValue FalseBB = User->getOperand(1);
9507           SDNode *NewBR =
9508             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9509           assert(NewBR == User);
9510           (void)NewBR;
9511           Dest = FalseBB;
9512
9513           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9514                                     Cond.getOperand(0), Cond.getOperand(1));
9515           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9516           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9517           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9518                               Chain, Dest, CC, Cmp);
9519           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9520           Cond = Cmp;
9521           addTest = false;
9522         }
9523       }
9524     } else if (Cond.getOpcode() == ISD::SETCC &&
9525                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9526       // For FCMP_UNE, we can emit
9527       // two branches instead of an explicit AND instruction with a
9528       // separate test. However, we only do this if this block doesn't
9529       // have a fall-through edge, because this requires an explicit
9530       // jmp when the condition is false.
9531       if (Op.getNode()->hasOneUse()) {
9532         SDNode *User = *Op.getNode()->use_begin();
9533         // Look for an unconditional branch following this conditional branch.
9534         // We need this because we need to reverse the successors in order
9535         // to implement FCMP_UNE.
9536         if (User->getOpcode() == ISD::BR) {
9537           SDValue FalseBB = User->getOperand(1);
9538           SDNode *NewBR =
9539             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9540           assert(NewBR == User);
9541           (void)NewBR;
9542
9543           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9544                                     Cond.getOperand(0), Cond.getOperand(1));
9545           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9546           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9547           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9548                               Chain, Dest, CC, Cmp);
9549           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9550           Cond = Cmp;
9551           addTest = false;
9552           Dest = FalseBB;
9553         }
9554       }
9555     }
9556   }
9557
9558   if (addTest) {
9559     // Look pass the truncate if the high bits are known zero.
9560     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9561         Cond = Cond.getOperand(0);
9562
9563     // We know the result of AND is compared against zero. Try to match
9564     // it to BT.
9565     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9566       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9567       if (NewSetCC.getNode()) {
9568         CC = NewSetCC.getOperand(0);
9569         Cond = NewSetCC.getOperand(1);
9570         addTest = false;
9571       }
9572     }
9573   }
9574
9575   if (addTest) {
9576     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9577     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9578   }
9579   Cond = ConvertCmpIfNecessary(Cond, DAG);
9580   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9581                      Chain, Dest, CC, Cond);
9582 }
9583
9584
9585 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9586 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9587 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9588 // that the guard pages used by the OS virtual memory manager are allocated in
9589 // correct sequence.
9590 SDValue
9591 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9592                                            SelectionDAG &DAG) const {
9593   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9594           getTargetMachine().Options.EnableSegmentedStacks) &&
9595          "This should be used only on Windows targets or when segmented stacks "
9596          "are being used");
9597   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9598   DebugLoc dl = Op.getDebugLoc();
9599
9600   // Get the inputs.
9601   SDValue Chain = Op.getOperand(0);
9602   SDValue Size  = Op.getOperand(1);
9603   // FIXME: Ensure alignment here
9604
9605   bool Is64Bit = Subtarget->is64Bit();
9606   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9607
9608   if (getTargetMachine().Options.EnableSegmentedStacks) {
9609     MachineFunction &MF = DAG.getMachineFunction();
9610     MachineRegisterInfo &MRI = MF.getRegInfo();
9611
9612     if (Is64Bit) {
9613       // The 64 bit implementation of segmented stacks needs to clobber both r10
9614       // r11. This makes it impossible to use it along with nested parameters.
9615       const Function *F = MF.getFunction();
9616
9617       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9618            I != E; ++I)
9619         if (I->hasNestAttr())
9620           report_fatal_error("Cannot use segmented stacks with functions that "
9621                              "have nested arguments.");
9622     }
9623
9624     const TargetRegisterClass *AddrRegClass =
9625       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9626     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9627     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9628     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9629                                 DAG.getRegister(Vreg, SPTy));
9630     SDValue Ops1[2] = { Value, Chain };
9631     return DAG.getMergeValues(Ops1, 2, dl);
9632   } else {
9633     SDValue Flag;
9634     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9635
9636     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9637     Flag = Chain.getValue(1);
9638     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9639
9640     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9641     Flag = Chain.getValue(1);
9642
9643     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9644
9645     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9646     return DAG.getMergeValues(Ops1, 2, dl);
9647   }
9648 }
9649
9650 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9651   MachineFunction &MF = DAG.getMachineFunction();
9652   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9653
9654   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9655   DebugLoc DL = Op.getDebugLoc();
9656
9657   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9658     // vastart just stores the address of the VarArgsFrameIndex slot into the
9659     // memory location argument.
9660     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9661                                    getPointerTy());
9662     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9663                         MachinePointerInfo(SV), false, false, 0);
9664   }
9665
9666   // __va_list_tag:
9667   //   gp_offset         (0 - 6 * 8)
9668   //   fp_offset         (48 - 48 + 8 * 16)
9669   //   overflow_arg_area (point to parameters coming in memory).
9670   //   reg_save_area
9671   SmallVector<SDValue, 8> MemOps;
9672   SDValue FIN = Op.getOperand(1);
9673   // Store gp_offset
9674   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9675                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9676                                                MVT::i32),
9677                                FIN, MachinePointerInfo(SV), false, false, 0);
9678   MemOps.push_back(Store);
9679
9680   // Store fp_offset
9681   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9682                     FIN, DAG.getIntPtrConstant(4));
9683   Store = DAG.getStore(Op.getOperand(0), DL,
9684                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9685                                        MVT::i32),
9686                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9687   MemOps.push_back(Store);
9688
9689   // Store ptr to overflow_arg_area
9690   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9691                     FIN, DAG.getIntPtrConstant(4));
9692   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9693                                     getPointerTy());
9694   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9695                        MachinePointerInfo(SV, 8),
9696                        false, false, 0);
9697   MemOps.push_back(Store);
9698
9699   // Store ptr to reg_save_area.
9700   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9701                     FIN, DAG.getIntPtrConstant(8));
9702   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9703                                     getPointerTy());
9704   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9705                        MachinePointerInfo(SV, 16), false, false, 0);
9706   MemOps.push_back(Store);
9707   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9708                      &MemOps[0], MemOps.size());
9709 }
9710
9711 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9712   assert(Subtarget->is64Bit() &&
9713          "LowerVAARG only handles 64-bit va_arg!");
9714   assert((Subtarget->isTargetLinux() ||
9715           Subtarget->isTargetDarwin()) &&
9716           "Unhandled target in LowerVAARG");
9717   assert(Op.getNode()->getNumOperands() == 4);
9718   SDValue Chain = Op.getOperand(0);
9719   SDValue SrcPtr = Op.getOperand(1);
9720   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9721   unsigned Align = Op.getConstantOperandVal(3);
9722   DebugLoc dl = Op.getDebugLoc();
9723
9724   EVT ArgVT = Op.getNode()->getValueType(0);
9725   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9726   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9727   uint8_t ArgMode;
9728
9729   // Decide which area this value should be read from.
9730   // TODO: Implement the AMD64 ABI in its entirety. This simple
9731   // selection mechanism works only for the basic types.
9732   if (ArgVT == MVT::f80) {
9733     llvm_unreachable("va_arg for f80 not yet implemented");
9734   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9735     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9736   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9737     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9738   } else {
9739     llvm_unreachable("Unhandled argument type in LowerVAARG");
9740   }
9741
9742   if (ArgMode == 2) {
9743     // Sanity Check: Make sure using fp_offset makes sense.
9744     assert(!getTargetMachine().Options.UseSoftFloat &&
9745            !(DAG.getMachineFunction()
9746                 .getFunction()->getFnAttributes()
9747                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9748            Subtarget->hasSSE1());
9749   }
9750
9751   // Insert VAARG_64 node into the DAG
9752   // VAARG_64 returns two values: Variable Argument Address, Chain
9753   SmallVector<SDValue, 11> InstOps;
9754   InstOps.push_back(Chain);
9755   InstOps.push_back(SrcPtr);
9756   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9757   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9758   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9759   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9760   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9761                                           VTs, &InstOps[0], InstOps.size(),
9762                                           MVT::i64,
9763                                           MachinePointerInfo(SV),
9764                                           /*Align=*/0,
9765                                           /*Volatile=*/false,
9766                                           /*ReadMem=*/true,
9767                                           /*WriteMem=*/true);
9768   Chain = VAARG.getValue(1);
9769
9770   // Load the next argument and return it
9771   return DAG.getLoad(ArgVT, dl,
9772                      Chain,
9773                      VAARG,
9774                      MachinePointerInfo(),
9775                      false, false, false, 0);
9776 }
9777
9778 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9779                            SelectionDAG &DAG) {
9780   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9781   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9782   SDValue Chain = Op.getOperand(0);
9783   SDValue DstPtr = Op.getOperand(1);
9784   SDValue SrcPtr = Op.getOperand(2);
9785   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9786   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9787   DebugLoc DL = Op.getDebugLoc();
9788
9789   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9790                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9791                        false,
9792                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9793 }
9794
9795 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9796 // may or may not be a constant. Takes immediate version of shift as input.
9797 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9798                                    SDValue SrcOp, SDValue ShAmt,
9799                                    SelectionDAG &DAG) {
9800   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9801
9802   if (isa<ConstantSDNode>(ShAmt)) {
9803     // Constant may be a TargetConstant. Use a regular constant.
9804     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9805     switch (Opc) {
9806       default: llvm_unreachable("Unknown target vector shift node");
9807       case X86ISD::VSHLI:
9808       case X86ISD::VSRLI:
9809       case X86ISD::VSRAI:
9810         return DAG.getNode(Opc, dl, VT, SrcOp,
9811                            DAG.getConstant(ShiftAmt, MVT::i32));
9812     }
9813   }
9814
9815   // Change opcode to non-immediate version
9816   switch (Opc) {
9817     default: llvm_unreachable("Unknown target vector shift node");
9818     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9819     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9820     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9821   }
9822
9823   // Need to build a vector containing shift amount
9824   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9825   SDValue ShOps[4];
9826   ShOps[0] = ShAmt;
9827   ShOps[1] = DAG.getConstant(0, MVT::i32);
9828   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9829   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9830
9831   // The return type has to be a 128-bit type with the same element
9832   // type as the input type.
9833   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9834   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9835
9836   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9837   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9838 }
9839
9840 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9841   DebugLoc dl = Op.getDebugLoc();
9842   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9843   switch (IntNo) {
9844   default: return SDValue();    // Don't custom lower most intrinsics.
9845   // Comparison intrinsics.
9846   case Intrinsic::x86_sse_comieq_ss:
9847   case Intrinsic::x86_sse_comilt_ss:
9848   case Intrinsic::x86_sse_comile_ss:
9849   case Intrinsic::x86_sse_comigt_ss:
9850   case Intrinsic::x86_sse_comige_ss:
9851   case Intrinsic::x86_sse_comineq_ss:
9852   case Intrinsic::x86_sse_ucomieq_ss:
9853   case Intrinsic::x86_sse_ucomilt_ss:
9854   case Intrinsic::x86_sse_ucomile_ss:
9855   case Intrinsic::x86_sse_ucomigt_ss:
9856   case Intrinsic::x86_sse_ucomige_ss:
9857   case Intrinsic::x86_sse_ucomineq_ss:
9858   case Intrinsic::x86_sse2_comieq_sd:
9859   case Intrinsic::x86_sse2_comilt_sd:
9860   case Intrinsic::x86_sse2_comile_sd:
9861   case Intrinsic::x86_sse2_comigt_sd:
9862   case Intrinsic::x86_sse2_comige_sd:
9863   case Intrinsic::x86_sse2_comineq_sd:
9864   case Intrinsic::x86_sse2_ucomieq_sd:
9865   case Intrinsic::x86_sse2_ucomilt_sd:
9866   case Intrinsic::x86_sse2_ucomile_sd:
9867   case Intrinsic::x86_sse2_ucomigt_sd:
9868   case Intrinsic::x86_sse2_ucomige_sd:
9869   case Intrinsic::x86_sse2_ucomineq_sd: {
9870     unsigned Opc;
9871     ISD::CondCode CC;
9872     switch (IntNo) {
9873     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9874     case Intrinsic::x86_sse_comieq_ss:
9875     case Intrinsic::x86_sse2_comieq_sd:
9876       Opc = X86ISD::COMI;
9877       CC = ISD::SETEQ;
9878       break;
9879     case Intrinsic::x86_sse_comilt_ss:
9880     case Intrinsic::x86_sse2_comilt_sd:
9881       Opc = X86ISD::COMI;
9882       CC = ISD::SETLT;
9883       break;
9884     case Intrinsic::x86_sse_comile_ss:
9885     case Intrinsic::x86_sse2_comile_sd:
9886       Opc = X86ISD::COMI;
9887       CC = ISD::SETLE;
9888       break;
9889     case Intrinsic::x86_sse_comigt_ss:
9890     case Intrinsic::x86_sse2_comigt_sd:
9891       Opc = X86ISD::COMI;
9892       CC = ISD::SETGT;
9893       break;
9894     case Intrinsic::x86_sse_comige_ss:
9895     case Intrinsic::x86_sse2_comige_sd:
9896       Opc = X86ISD::COMI;
9897       CC = ISD::SETGE;
9898       break;
9899     case Intrinsic::x86_sse_comineq_ss:
9900     case Intrinsic::x86_sse2_comineq_sd:
9901       Opc = X86ISD::COMI;
9902       CC = ISD::SETNE;
9903       break;
9904     case Intrinsic::x86_sse_ucomieq_ss:
9905     case Intrinsic::x86_sse2_ucomieq_sd:
9906       Opc = X86ISD::UCOMI;
9907       CC = ISD::SETEQ;
9908       break;
9909     case Intrinsic::x86_sse_ucomilt_ss:
9910     case Intrinsic::x86_sse2_ucomilt_sd:
9911       Opc = X86ISD::UCOMI;
9912       CC = ISD::SETLT;
9913       break;
9914     case Intrinsic::x86_sse_ucomile_ss:
9915     case Intrinsic::x86_sse2_ucomile_sd:
9916       Opc = X86ISD::UCOMI;
9917       CC = ISD::SETLE;
9918       break;
9919     case Intrinsic::x86_sse_ucomigt_ss:
9920     case Intrinsic::x86_sse2_ucomigt_sd:
9921       Opc = X86ISD::UCOMI;
9922       CC = ISD::SETGT;
9923       break;
9924     case Intrinsic::x86_sse_ucomige_ss:
9925     case Intrinsic::x86_sse2_ucomige_sd:
9926       Opc = X86ISD::UCOMI;
9927       CC = ISD::SETGE;
9928       break;
9929     case Intrinsic::x86_sse_ucomineq_ss:
9930     case Intrinsic::x86_sse2_ucomineq_sd:
9931       Opc = X86ISD::UCOMI;
9932       CC = ISD::SETNE;
9933       break;
9934     }
9935
9936     SDValue LHS = Op.getOperand(1);
9937     SDValue RHS = Op.getOperand(2);
9938     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9939     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9940     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9941     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9942                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9943     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9944   }
9945
9946   // Arithmetic intrinsics.
9947   case Intrinsic::x86_sse2_pmulu_dq:
9948   case Intrinsic::x86_avx2_pmulu_dq:
9949     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9950                        Op.getOperand(1), Op.getOperand(2));
9951
9952   // SSE3/AVX horizontal add/sub intrinsics
9953   case Intrinsic::x86_sse3_hadd_ps:
9954   case Intrinsic::x86_sse3_hadd_pd:
9955   case Intrinsic::x86_avx_hadd_ps_256:
9956   case Intrinsic::x86_avx_hadd_pd_256:
9957   case Intrinsic::x86_sse3_hsub_ps:
9958   case Intrinsic::x86_sse3_hsub_pd:
9959   case Intrinsic::x86_avx_hsub_ps_256:
9960   case Intrinsic::x86_avx_hsub_pd_256:
9961   case Intrinsic::x86_ssse3_phadd_w_128:
9962   case Intrinsic::x86_ssse3_phadd_d_128:
9963   case Intrinsic::x86_avx2_phadd_w:
9964   case Intrinsic::x86_avx2_phadd_d:
9965   case Intrinsic::x86_ssse3_phsub_w_128:
9966   case Intrinsic::x86_ssse3_phsub_d_128:
9967   case Intrinsic::x86_avx2_phsub_w:
9968   case Intrinsic::x86_avx2_phsub_d: {
9969     unsigned Opcode;
9970     switch (IntNo) {
9971     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9972     case Intrinsic::x86_sse3_hadd_ps:
9973     case Intrinsic::x86_sse3_hadd_pd:
9974     case Intrinsic::x86_avx_hadd_ps_256:
9975     case Intrinsic::x86_avx_hadd_pd_256:
9976       Opcode = X86ISD::FHADD;
9977       break;
9978     case Intrinsic::x86_sse3_hsub_ps:
9979     case Intrinsic::x86_sse3_hsub_pd:
9980     case Intrinsic::x86_avx_hsub_ps_256:
9981     case Intrinsic::x86_avx_hsub_pd_256:
9982       Opcode = X86ISD::FHSUB;
9983       break;
9984     case Intrinsic::x86_ssse3_phadd_w_128:
9985     case Intrinsic::x86_ssse3_phadd_d_128:
9986     case Intrinsic::x86_avx2_phadd_w:
9987     case Intrinsic::x86_avx2_phadd_d:
9988       Opcode = X86ISD::HADD;
9989       break;
9990     case Intrinsic::x86_ssse3_phsub_w_128:
9991     case Intrinsic::x86_ssse3_phsub_d_128:
9992     case Intrinsic::x86_avx2_phsub_w:
9993     case Intrinsic::x86_avx2_phsub_d:
9994       Opcode = X86ISD::HSUB;
9995       break;
9996     }
9997     return DAG.getNode(Opcode, dl, Op.getValueType(),
9998                        Op.getOperand(1), Op.getOperand(2));
9999   }
10000
10001   // AVX2 variable shift intrinsics
10002   case Intrinsic::x86_avx2_psllv_d:
10003   case Intrinsic::x86_avx2_psllv_q:
10004   case Intrinsic::x86_avx2_psllv_d_256:
10005   case Intrinsic::x86_avx2_psllv_q_256:
10006   case Intrinsic::x86_avx2_psrlv_d:
10007   case Intrinsic::x86_avx2_psrlv_q:
10008   case Intrinsic::x86_avx2_psrlv_d_256:
10009   case Intrinsic::x86_avx2_psrlv_q_256:
10010   case Intrinsic::x86_avx2_psrav_d:
10011   case Intrinsic::x86_avx2_psrav_d_256: {
10012     unsigned Opcode;
10013     switch (IntNo) {
10014     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10015     case Intrinsic::x86_avx2_psllv_d:
10016     case Intrinsic::x86_avx2_psllv_q:
10017     case Intrinsic::x86_avx2_psllv_d_256:
10018     case Intrinsic::x86_avx2_psllv_q_256:
10019       Opcode = ISD::SHL;
10020       break;
10021     case Intrinsic::x86_avx2_psrlv_d:
10022     case Intrinsic::x86_avx2_psrlv_q:
10023     case Intrinsic::x86_avx2_psrlv_d_256:
10024     case Intrinsic::x86_avx2_psrlv_q_256:
10025       Opcode = ISD::SRL;
10026       break;
10027     case Intrinsic::x86_avx2_psrav_d:
10028     case Intrinsic::x86_avx2_psrav_d_256:
10029       Opcode = ISD::SRA;
10030       break;
10031     }
10032     return DAG.getNode(Opcode, dl, Op.getValueType(),
10033                        Op.getOperand(1), Op.getOperand(2));
10034   }
10035
10036   case Intrinsic::x86_ssse3_pshuf_b_128:
10037   case Intrinsic::x86_avx2_pshuf_b:
10038     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10039                        Op.getOperand(1), Op.getOperand(2));
10040
10041   case Intrinsic::x86_ssse3_psign_b_128:
10042   case Intrinsic::x86_ssse3_psign_w_128:
10043   case Intrinsic::x86_ssse3_psign_d_128:
10044   case Intrinsic::x86_avx2_psign_b:
10045   case Intrinsic::x86_avx2_psign_w:
10046   case Intrinsic::x86_avx2_psign_d:
10047     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10048                        Op.getOperand(1), Op.getOperand(2));
10049
10050   case Intrinsic::x86_sse41_insertps:
10051     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10052                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10053
10054   case Intrinsic::x86_avx_vperm2f128_ps_256:
10055   case Intrinsic::x86_avx_vperm2f128_pd_256:
10056   case Intrinsic::x86_avx_vperm2f128_si_256:
10057   case Intrinsic::x86_avx2_vperm2i128:
10058     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10059                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10060
10061   case Intrinsic::x86_avx2_permd:
10062   case Intrinsic::x86_avx2_permps:
10063     // Operands intentionally swapped. Mask is last operand to intrinsic,
10064     // but second operand for node/intruction.
10065     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10066                        Op.getOperand(2), Op.getOperand(1));
10067
10068   // ptest and testp intrinsics. The intrinsic these come from are designed to
10069   // return an integer value, not just an instruction so lower it to the ptest
10070   // or testp pattern and a setcc for the result.
10071   case Intrinsic::x86_sse41_ptestz:
10072   case Intrinsic::x86_sse41_ptestc:
10073   case Intrinsic::x86_sse41_ptestnzc:
10074   case Intrinsic::x86_avx_ptestz_256:
10075   case Intrinsic::x86_avx_ptestc_256:
10076   case Intrinsic::x86_avx_ptestnzc_256:
10077   case Intrinsic::x86_avx_vtestz_ps:
10078   case Intrinsic::x86_avx_vtestc_ps:
10079   case Intrinsic::x86_avx_vtestnzc_ps:
10080   case Intrinsic::x86_avx_vtestz_pd:
10081   case Intrinsic::x86_avx_vtestc_pd:
10082   case Intrinsic::x86_avx_vtestnzc_pd:
10083   case Intrinsic::x86_avx_vtestz_ps_256:
10084   case Intrinsic::x86_avx_vtestc_ps_256:
10085   case Intrinsic::x86_avx_vtestnzc_ps_256:
10086   case Intrinsic::x86_avx_vtestz_pd_256:
10087   case Intrinsic::x86_avx_vtestc_pd_256:
10088   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10089     bool IsTestPacked = false;
10090     unsigned X86CC;
10091     switch (IntNo) {
10092     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10093     case Intrinsic::x86_avx_vtestz_ps:
10094     case Intrinsic::x86_avx_vtestz_pd:
10095     case Intrinsic::x86_avx_vtestz_ps_256:
10096     case Intrinsic::x86_avx_vtestz_pd_256:
10097       IsTestPacked = true; // Fallthrough
10098     case Intrinsic::x86_sse41_ptestz:
10099     case Intrinsic::x86_avx_ptestz_256:
10100       // ZF = 1
10101       X86CC = X86::COND_E;
10102       break;
10103     case Intrinsic::x86_avx_vtestc_ps:
10104     case Intrinsic::x86_avx_vtestc_pd:
10105     case Intrinsic::x86_avx_vtestc_ps_256:
10106     case Intrinsic::x86_avx_vtestc_pd_256:
10107       IsTestPacked = true; // Fallthrough
10108     case Intrinsic::x86_sse41_ptestc:
10109     case Intrinsic::x86_avx_ptestc_256:
10110       // CF = 1
10111       X86CC = X86::COND_B;
10112       break;
10113     case Intrinsic::x86_avx_vtestnzc_ps:
10114     case Intrinsic::x86_avx_vtestnzc_pd:
10115     case Intrinsic::x86_avx_vtestnzc_ps_256:
10116     case Intrinsic::x86_avx_vtestnzc_pd_256:
10117       IsTestPacked = true; // Fallthrough
10118     case Intrinsic::x86_sse41_ptestnzc:
10119     case Intrinsic::x86_avx_ptestnzc_256:
10120       // ZF and CF = 0
10121       X86CC = X86::COND_A;
10122       break;
10123     }
10124
10125     SDValue LHS = Op.getOperand(1);
10126     SDValue RHS = Op.getOperand(2);
10127     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10128     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10129     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10130     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10131     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10132   }
10133
10134   // SSE/AVX shift intrinsics
10135   case Intrinsic::x86_sse2_psll_w:
10136   case Intrinsic::x86_sse2_psll_d:
10137   case Intrinsic::x86_sse2_psll_q:
10138   case Intrinsic::x86_avx2_psll_w:
10139   case Intrinsic::x86_avx2_psll_d:
10140   case Intrinsic::x86_avx2_psll_q:
10141   case Intrinsic::x86_sse2_psrl_w:
10142   case Intrinsic::x86_sse2_psrl_d:
10143   case Intrinsic::x86_sse2_psrl_q:
10144   case Intrinsic::x86_avx2_psrl_w:
10145   case Intrinsic::x86_avx2_psrl_d:
10146   case Intrinsic::x86_avx2_psrl_q:
10147   case Intrinsic::x86_sse2_psra_w:
10148   case Intrinsic::x86_sse2_psra_d:
10149   case Intrinsic::x86_avx2_psra_w:
10150   case Intrinsic::x86_avx2_psra_d: {
10151     unsigned Opcode;
10152     switch (IntNo) {
10153     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10154     case Intrinsic::x86_sse2_psll_w:
10155     case Intrinsic::x86_sse2_psll_d:
10156     case Intrinsic::x86_sse2_psll_q:
10157     case Intrinsic::x86_avx2_psll_w:
10158     case Intrinsic::x86_avx2_psll_d:
10159     case Intrinsic::x86_avx2_psll_q:
10160       Opcode = X86ISD::VSHL;
10161       break;
10162     case Intrinsic::x86_sse2_psrl_w:
10163     case Intrinsic::x86_sse2_psrl_d:
10164     case Intrinsic::x86_sse2_psrl_q:
10165     case Intrinsic::x86_avx2_psrl_w:
10166     case Intrinsic::x86_avx2_psrl_d:
10167     case Intrinsic::x86_avx2_psrl_q:
10168       Opcode = X86ISD::VSRL;
10169       break;
10170     case Intrinsic::x86_sse2_psra_w:
10171     case Intrinsic::x86_sse2_psra_d:
10172     case Intrinsic::x86_avx2_psra_w:
10173     case Intrinsic::x86_avx2_psra_d:
10174       Opcode = X86ISD::VSRA;
10175       break;
10176     }
10177     return DAG.getNode(Opcode, dl, Op.getValueType(),
10178                        Op.getOperand(1), Op.getOperand(2));
10179   }
10180
10181   // SSE/AVX immediate shift intrinsics
10182   case Intrinsic::x86_sse2_pslli_w:
10183   case Intrinsic::x86_sse2_pslli_d:
10184   case Intrinsic::x86_sse2_pslli_q:
10185   case Intrinsic::x86_avx2_pslli_w:
10186   case Intrinsic::x86_avx2_pslli_d:
10187   case Intrinsic::x86_avx2_pslli_q:
10188   case Intrinsic::x86_sse2_psrli_w:
10189   case Intrinsic::x86_sse2_psrli_d:
10190   case Intrinsic::x86_sse2_psrli_q:
10191   case Intrinsic::x86_avx2_psrli_w:
10192   case Intrinsic::x86_avx2_psrli_d:
10193   case Intrinsic::x86_avx2_psrli_q:
10194   case Intrinsic::x86_sse2_psrai_w:
10195   case Intrinsic::x86_sse2_psrai_d:
10196   case Intrinsic::x86_avx2_psrai_w:
10197   case Intrinsic::x86_avx2_psrai_d: {
10198     unsigned Opcode;
10199     switch (IntNo) {
10200     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10201     case Intrinsic::x86_sse2_pslli_w:
10202     case Intrinsic::x86_sse2_pslli_d:
10203     case Intrinsic::x86_sse2_pslli_q:
10204     case Intrinsic::x86_avx2_pslli_w:
10205     case Intrinsic::x86_avx2_pslli_d:
10206     case Intrinsic::x86_avx2_pslli_q:
10207       Opcode = X86ISD::VSHLI;
10208       break;
10209     case Intrinsic::x86_sse2_psrli_w:
10210     case Intrinsic::x86_sse2_psrli_d:
10211     case Intrinsic::x86_sse2_psrli_q:
10212     case Intrinsic::x86_avx2_psrli_w:
10213     case Intrinsic::x86_avx2_psrli_d:
10214     case Intrinsic::x86_avx2_psrli_q:
10215       Opcode = X86ISD::VSRLI;
10216       break;
10217     case Intrinsic::x86_sse2_psrai_w:
10218     case Intrinsic::x86_sse2_psrai_d:
10219     case Intrinsic::x86_avx2_psrai_w:
10220     case Intrinsic::x86_avx2_psrai_d:
10221       Opcode = X86ISD::VSRAI;
10222       break;
10223     }
10224     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10225                                Op.getOperand(1), Op.getOperand(2), DAG);
10226   }
10227
10228   case Intrinsic::x86_sse42_pcmpistria128:
10229   case Intrinsic::x86_sse42_pcmpestria128:
10230   case Intrinsic::x86_sse42_pcmpistric128:
10231   case Intrinsic::x86_sse42_pcmpestric128:
10232   case Intrinsic::x86_sse42_pcmpistrio128:
10233   case Intrinsic::x86_sse42_pcmpestrio128:
10234   case Intrinsic::x86_sse42_pcmpistris128:
10235   case Intrinsic::x86_sse42_pcmpestris128:
10236   case Intrinsic::x86_sse42_pcmpistriz128:
10237   case Intrinsic::x86_sse42_pcmpestriz128: {
10238     unsigned Opcode;
10239     unsigned X86CC;
10240     switch (IntNo) {
10241     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10242     case Intrinsic::x86_sse42_pcmpistria128:
10243       Opcode = X86ISD::PCMPISTRI;
10244       X86CC = X86::COND_A;
10245       break;
10246     case Intrinsic::x86_sse42_pcmpestria128:
10247       Opcode = X86ISD::PCMPESTRI;
10248       X86CC = X86::COND_A;
10249       break;
10250     case Intrinsic::x86_sse42_pcmpistric128:
10251       Opcode = X86ISD::PCMPISTRI;
10252       X86CC = X86::COND_B;
10253       break;
10254     case Intrinsic::x86_sse42_pcmpestric128:
10255       Opcode = X86ISD::PCMPESTRI;
10256       X86CC = X86::COND_B;
10257       break;
10258     case Intrinsic::x86_sse42_pcmpistrio128:
10259       Opcode = X86ISD::PCMPISTRI;
10260       X86CC = X86::COND_O;
10261       break;
10262     case Intrinsic::x86_sse42_pcmpestrio128:
10263       Opcode = X86ISD::PCMPESTRI;
10264       X86CC = X86::COND_O;
10265       break;
10266     case Intrinsic::x86_sse42_pcmpistris128:
10267       Opcode = X86ISD::PCMPISTRI;
10268       X86CC = X86::COND_S;
10269       break;
10270     case Intrinsic::x86_sse42_pcmpestris128:
10271       Opcode = X86ISD::PCMPESTRI;
10272       X86CC = X86::COND_S;
10273       break;
10274     case Intrinsic::x86_sse42_pcmpistriz128:
10275       Opcode = X86ISD::PCMPISTRI;
10276       X86CC = X86::COND_E;
10277       break;
10278     case Intrinsic::x86_sse42_pcmpestriz128:
10279       Opcode = X86ISD::PCMPESTRI;
10280       X86CC = X86::COND_E;
10281       break;
10282     }
10283     SmallVector<SDValue, 5> NewOps;
10284     NewOps.append(Op->op_begin()+1, Op->op_end());
10285     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10286     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10287     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10288                                 DAG.getConstant(X86CC, MVT::i8),
10289                                 SDValue(PCMP.getNode(), 1));
10290     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10291   }
10292
10293   case Intrinsic::x86_sse42_pcmpistri128:
10294   case Intrinsic::x86_sse42_pcmpestri128: {
10295     unsigned Opcode;
10296     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10297       Opcode = X86ISD::PCMPISTRI;
10298     else
10299       Opcode = X86ISD::PCMPESTRI;
10300
10301     SmallVector<SDValue, 5> NewOps;
10302     NewOps.append(Op->op_begin()+1, Op->op_end());
10303     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10304     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10305   }
10306   case Intrinsic::x86_fma_vfmadd_ps:
10307   case Intrinsic::x86_fma_vfmadd_pd:
10308   case Intrinsic::x86_fma_vfmsub_ps:
10309   case Intrinsic::x86_fma_vfmsub_pd:
10310   case Intrinsic::x86_fma_vfnmadd_ps:
10311   case Intrinsic::x86_fma_vfnmadd_pd:
10312   case Intrinsic::x86_fma_vfnmsub_ps:
10313   case Intrinsic::x86_fma_vfnmsub_pd:
10314   case Intrinsic::x86_fma_vfmaddsub_ps:
10315   case Intrinsic::x86_fma_vfmaddsub_pd:
10316   case Intrinsic::x86_fma_vfmsubadd_ps:
10317   case Intrinsic::x86_fma_vfmsubadd_pd:
10318   case Intrinsic::x86_fma_vfmadd_ps_256:
10319   case Intrinsic::x86_fma_vfmadd_pd_256:
10320   case Intrinsic::x86_fma_vfmsub_ps_256:
10321   case Intrinsic::x86_fma_vfmsub_pd_256:
10322   case Intrinsic::x86_fma_vfnmadd_ps_256:
10323   case Intrinsic::x86_fma_vfnmadd_pd_256:
10324   case Intrinsic::x86_fma_vfnmsub_ps_256:
10325   case Intrinsic::x86_fma_vfnmsub_pd_256:
10326   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10327   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10328   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10329   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10330     unsigned Opc;
10331     switch (IntNo) {
10332     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10333     case Intrinsic::x86_fma_vfmadd_ps:
10334     case Intrinsic::x86_fma_vfmadd_pd:
10335     case Intrinsic::x86_fma_vfmadd_ps_256:
10336     case Intrinsic::x86_fma_vfmadd_pd_256:
10337       Opc = X86ISD::FMADD;
10338       break;
10339     case Intrinsic::x86_fma_vfmsub_ps:
10340     case Intrinsic::x86_fma_vfmsub_pd:
10341     case Intrinsic::x86_fma_vfmsub_ps_256:
10342     case Intrinsic::x86_fma_vfmsub_pd_256:
10343       Opc = X86ISD::FMSUB;
10344       break;
10345     case Intrinsic::x86_fma_vfnmadd_ps:
10346     case Intrinsic::x86_fma_vfnmadd_pd:
10347     case Intrinsic::x86_fma_vfnmadd_ps_256:
10348     case Intrinsic::x86_fma_vfnmadd_pd_256:
10349       Opc = X86ISD::FNMADD;
10350       break;
10351     case Intrinsic::x86_fma_vfnmsub_ps:
10352     case Intrinsic::x86_fma_vfnmsub_pd:
10353     case Intrinsic::x86_fma_vfnmsub_ps_256:
10354     case Intrinsic::x86_fma_vfnmsub_pd_256:
10355       Opc = X86ISD::FNMSUB;
10356       break;
10357     case Intrinsic::x86_fma_vfmaddsub_ps:
10358     case Intrinsic::x86_fma_vfmaddsub_pd:
10359     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10360     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10361       Opc = X86ISD::FMADDSUB;
10362       break;
10363     case Intrinsic::x86_fma_vfmsubadd_ps:
10364     case Intrinsic::x86_fma_vfmsubadd_pd:
10365     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10366     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10367       Opc = X86ISD::FMSUBADD;
10368       break;
10369     }
10370
10371     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10372                        Op.getOperand(2), Op.getOperand(3));
10373   }
10374   }
10375 }
10376
10377 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10378   DebugLoc dl = Op.getDebugLoc();
10379   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10380   switch (IntNo) {
10381   default: return SDValue();    // Don't custom lower most intrinsics.
10382
10383   // RDRAND intrinsics.
10384   case Intrinsic::x86_rdrand_16:
10385   case Intrinsic::x86_rdrand_32:
10386   case Intrinsic::x86_rdrand_64: {
10387     // Emit the node with the right value type.
10388     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10389     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10390
10391     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10392     // return the value from Rand, which is always 0, casted to i32.
10393     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10394                       DAG.getConstant(1, Op->getValueType(1)),
10395                       DAG.getConstant(X86::COND_B, MVT::i32),
10396                       SDValue(Result.getNode(), 1) };
10397     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10398                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10399                                   Ops, 4);
10400
10401     // Return { result, isValid, chain }.
10402     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10403                        SDValue(Result.getNode(), 2));
10404   }
10405   }
10406 }
10407
10408 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10409                                            SelectionDAG &DAG) const {
10410   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10411   MFI->setReturnAddressIsTaken(true);
10412
10413   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10414   DebugLoc dl = Op.getDebugLoc();
10415
10416   if (Depth > 0) {
10417     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10418     SDValue Offset =
10419       DAG.getConstant(TD->getPointerSize(0),
10420                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10421     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10422                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10423                                    FrameAddr, Offset),
10424                        MachinePointerInfo(), false, false, false, 0);
10425   }
10426
10427   // Just load the return address.
10428   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10429   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10430                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10431 }
10432
10433 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10434   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10435   MFI->setFrameAddressIsTaken(true);
10436
10437   EVT VT = Op.getValueType();
10438   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10439   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10440   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10441   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10442   while (Depth--)
10443     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10444                             MachinePointerInfo(),
10445                             false, false, false, 0);
10446   return FrameAddr;
10447 }
10448
10449 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10450                                                      SelectionDAG &DAG) const {
10451   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10452 }
10453
10454 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10455   SDValue Chain     = Op.getOperand(0);
10456   SDValue Offset    = Op.getOperand(1);
10457   SDValue Handler   = Op.getOperand(2);
10458   DebugLoc dl       = Op.getDebugLoc();
10459
10460   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10461                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10462                                      getPointerTy());
10463   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10464
10465   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10466                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10467   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10468   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10469                        false, false, 0);
10470   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10471
10472   return DAG.getNode(X86ISD::EH_RETURN, dl,
10473                      MVT::Other,
10474                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10475 }
10476
10477 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10478                                                SelectionDAG &DAG) const {
10479   DebugLoc DL = Op.getDebugLoc();
10480   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10481                      DAG.getVTList(MVT::i32, MVT::Other),
10482                      Op.getOperand(0), Op.getOperand(1));
10483 }
10484
10485 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10486                                                 SelectionDAG &DAG) const {
10487   DebugLoc DL = Op.getDebugLoc();
10488   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10489                      Op.getOperand(0), Op.getOperand(1));
10490 }
10491
10492 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10493   return Op.getOperand(0);
10494 }
10495
10496 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10497                                                 SelectionDAG &DAG) const {
10498   SDValue Root = Op.getOperand(0);
10499   SDValue Trmp = Op.getOperand(1); // trampoline
10500   SDValue FPtr = Op.getOperand(2); // nested function
10501   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10502   DebugLoc dl  = Op.getDebugLoc();
10503
10504   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10505   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10506
10507   if (Subtarget->is64Bit()) {
10508     SDValue OutChains[6];
10509
10510     // Large code-model.
10511     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10512     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10513
10514     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10515     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10516
10517     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10518
10519     // Load the pointer to the nested function into R11.
10520     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10521     SDValue Addr = Trmp;
10522     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10523                                 Addr, MachinePointerInfo(TrmpAddr),
10524                                 false, false, 0);
10525
10526     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10527                        DAG.getConstant(2, MVT::i64));
10528     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10529                                 MachinePointerInfo(TrmpAddr, 2),
10530                                 false, false, 2);
10531
10532     // Load the 'nest' parameter value into R10.
10533     // R10 is specified in X86CallingConv.td
10534     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10535     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10536                        DAG.getConstant(10, MVT::i64));
10537     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10538                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10539                                 false, false, 0);
10540
10541     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10542                        DAG.getConstant(12, MVT::i64));
10543     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10544                                 MachinePointerInfo(TrmpAddr, 12),
10545                                 false, false, 2);
10546
10547     // Jump to the nested function.
10548     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10549     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10550                        DAG.getConstant(20, MVT::i64));
10551     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10552                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10553                                 false, false, 0);
10554
10555     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10556     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10557                        DAG.getConstant(22, MVT::i64));
10558     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10559                                 MachinePointerInfo(TrmpAddr, 22),
10560                                 false, false, 0);
10561
10562     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10563   } else {
10564     const Function *Func =
10565       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10566     CallingConv::ID CC = Func->getCallingConv();
10567     unsigned NestReg;
10568
10569     switch (CC) {
10570     default:
10571       llvm_unreachable("Unsupported calling convention");
10572     case CallingConv::C:
10573     case CallingConv::X86_StdCall: {
10574       // Pass 'nest' parameter in ECX.
10575       // Must be kept in sync with X86CallingConv.td
10576       NestReg = X86::ECX;
10577
10578       // Check that ECX wasn't needed by an 'inreg' parameter.
10579       FunctionType *FTy = Func->getFunctionType();
10580       const AttrListPtr &Attrs = Func->getAttributes();
10581
10582       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10583         unsigned InRegCount = 0;
10584         unsigned Idx = 1;
10585
10586         for (FunctionType::param_iterator I = FTy->param_begin(),
10587              E = FTy->param_end(); I != E; ++I, ++Idx)
10588           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10589             // FIXME: should only count parameters that are lowered to integers.
10590             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10591
10592         if (InRegCount > 2) {
10593           report_fatal_error("Nest register in use - reduce number of inreg"
10594                              " parameters!");
10595         }
10596       }
10597       break;
10598     }
10599     case CallingConv::X86_FastCall:
10600     case CallingConv::X86_ThisCall:
10601     case CallingConv::Fast:
10602       // Pass 'nest' parameter in EAX.
10603       // Must be kept in sync with X86CallingConv.td
10604       NestReg = X86::EAX;
10605       break;
10606     }
10607
10608     SDValue OutChains[4];
10609     SDValue Addr, Disp;
10610
10611     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10612                        DAG.getConstant(10, MVT::i32));
10613     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10614
10615     // This is storing the opcode for MOV32ri.
10616     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10617     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10618     OutChains[0] = DAG.getStore(Root, dl,
10619                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10620                                 Trmp, MachinePointerInfo(TrmpAddr),
10621                                 false, false, 0);
10622
10623     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10624                        DAG.getConstant(1, MVT::i32));
10625     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10626                                 MachinePointerInfo(TrmpAddr, 1),
10627                                 false, false, 1);
10628
10629     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10630     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10631                        DAG.getConstant(5, MVT::i32));
10632     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10633                                 MachinePointerInfo(TrmpAddr, 5),
10634                                 false, false, 1);
10635
10636     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10637                        DAG.getConstant(6, MVT::i32));
10638     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10639                                 MachinePointerInfo(TrmpAddr, 6),
10640                                 false, false, 1);
10641
10642     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10643   }
10644 }
10645
10646 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10647                                             SelectionDAG &DAG) const {
10648   /*
10649    The rounding mode is in bits 11:10 of FPSR, and has the following
10650    settings:
10651      00 Round to nearest
10652      01 Round to -inf
10653      10 Round to +inf
10654      11 Round to 0
10655
10656   FLT_ROUNDS, on the other hand, expects the following:
10657     -1 Undefined
10658      0 Round to 0
10659      1 Round to nearest
10660      2 Round to +inf
10661      3 Round to -inf
10662
10663   To perform the conversion, we do:
10664     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10665   */
10666
10667   MachineFunction &MF = DAG.getMachineFunction();
10668   const TargetMachine &TM = MF.getTarget();
10669   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10670   unsigned StackAlignment = TFI.getStackAlignment();
10671   EVT VT = Op.getValueType();
10672   DebugLoc DL = Op.getDebugLoc();
10673
10674   // Save FP Control Word to stack slot
10675   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10676   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10677
10678
10679   MachineMemOperand *MMO =
10680    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10681                            MachineMemOperand::MOStore, 2, 2);
10682
10683   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10684   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10685                                           DAG.getVTList(MVT::Other),
10686                                           Ops, 2, MVT::i16, MMO);
10687
10688   // Load FP Control Word from stack slot
10689   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10690                             MachinePointerInfo(), false, false, false, 0);
10691
10692   // Transform as necessary
10693   SDValue CWD1 =
10694     DAG.getNode(ISD::SRL, DL, MVT::i16,
10695                 DAG.getNode(ISD::AND, DL, MVT::i16,
10696                             CWD, DAG.getConstant(0x800, MVT::i16)),
10697                 DAG.getConstant(11, MVT::i8));
10698   SDValue CWD2 =
10699     DAG.getNode(ISD::SRL, DL, MVT::i16,
10700                 DAG.getNode(ISD::AND, DL, MVT::i16,
10701                             CWD, DAG.getConstant(0x400, MVT::i16)),
10702                 DAG.getConstant(9, MVT::i8));
10703
10704   SDValue RetVal =
10705     DAG.getNode(ISD::AND, DL, MVT::i16,
10706                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10707                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10708                             DAG.getConstant(1, MVT::i16)),
10709                 DAG.getConstant(3, MVT::i16));
10710
10711
10712   return DAG.getNode((VT.getSizeInBits() < 16 ?
10713                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10714 }
10715
10716 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10717   EVT VT = Op.getValueType();
10718   EVT OpVT = VT;
10719   unsigned NumBits = VT.getSizeInBits();
10720   DebugLoc dl = Op.getDebugLoc();
10721
10722   Op = Op.getOperand(0);
10723   if (VT == MVT::i8) {
10724     // Zero extend to i32 since there is not an i8 bsr.
10725     OpVT = MVT::i32;
10726     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10727   }
10728
10729   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10730   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10731   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10732
10733   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10734   SDValue Ops[] = {
10735     Op,
10736     DAG.getConstant(NumBits+NumBits-1, OpVT),
10737     DAG.getConstant(X86::COND_E, MVT::i8),
10738     Op.getValue(1)
10739   };
10740   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10741
10742   // Finally xor with NumBits-1.
10743   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10744
10745   if (VT == MVT::i8)
10746     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10747   return Op;
10748 }
10749
10750 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10751   EVT VT = Op.getValueType();
10752   EVT OpVT = VT;
10753   unsigned NumBits = VT.getSizeInBits();
10754   DebugLoc dl = Op.getDebugLoc();
10755
10756   Op = Op.getOperand(0);
10757   if (VT == MVT::i8) {
10758     // Zero extend to i32 since there is not an i8 bsr.
10759     OpVT = MVT::i32;
10760     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10761   }
10762
10763   // Issue a bsr (scan bits in reverse).
10764   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10765   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10766
10767   // And xor with NumBits-1.
10768   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10769
10770   if (VT == MVT::i8)
10771     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10772   return Op;
10773 }
10774
10775 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10776   EVT VT = Op.getValueType();
10777   unsigned NumBits = VT.getSizeInBits();
10778   DebugLoc dl = Op.getDebugLoc();
10779   Op = Op.getOperand(0);
10780
10781   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10782   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10783   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10784
10785   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10786   SDValue Ops[] = {
10787     Op,
10788     DAG.getConstant(NumBits, VT),
10789     DAG.getConstant(X86::COND_E, MVT::i8),
10790     Op.getValue(1)
10791   };
10792   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10793 }
10794
10795 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10796 // ones, and then concatenate the result back.
10797 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10798   EVT VT = Op.getValueType();
10799
10800   assert(VT.is256BitVector() && VT.isInteger() &&
10801          "Unsupported value type for operation");
10802
10803   unsigned NumElems = VT.getVectorNumElements();
10804   DebugLoc dl = Op.getDebugLoc();
10805
10806   // Extract the LHS vectors
10807   SDValue LHS = Op.getOperand(0);
10808   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10809   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10810
10811   // Extract the RHS vectors
10812   SDValue RHS = Op.getOperand(1);
10813   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10814   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10815
10816   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10817   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10818
10819   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10820                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10821                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10822 }
10823
10824 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10825   assert(Op.getValueType().is256BitVector() &&
10826          Op.getValueType().isInteger() &&
10827          "Only handle AVX 256-bit vector integer operation");
10828   return Lower256IntArith(Op, DAG);
10829 }
10830
10831 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10832   assert(Op.getValueType().is256BitVector() &&
10833          Op.getValueType().isInteger() &&
10834          "Only handle AVX 256-bit vector integer operation");
10835   return Lower256IntArith(Op, DAG);
10836 }
10837
10838 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10839                         SelectionDAG &DAG) {
10840   EVT VT = Op.getValueType();
10841
10842   // Decompose 256-bit ops into smaller 128-bit ops.
10843   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10844     return Lower256IntArith(Op, DAG);
10845
10846   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10847          "Only know how to lower V2I64/V4I64 multiply");
10848
10849   DebugLoc dl = Op.getDebugLoc();
10850
10851   //  Ahi = psrlqi(a, 32);
10852   //  Bhi = psrlqi(b, 32);
10853   //
10854   //  AloBlo = pmuludq(a, b);
10855   //  AloBhi = pmuludq(a, Bhi);
10856   //  AhiBlo = pmuludq(Ahi, b);
10857
10858   //  AloBhi = psllqi(AloBhi, 32);
10859   //  AhiBlo = psllqi(AhiBlo, 32);
10860   //  return AloBlo + AloBhi + AhiBlo;
10861
10862   SDValue A = Op.getOperand(0);
10863   SDValue B = Op.getOperand(1);
10864
10865   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10866
10867   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10868   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10869
10870   // Bit cast to 32-bit vectors for MULUDQ
10871   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10872   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10873   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10874   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10875   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10876
10877   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10878   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10879   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10880
10881   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10882   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10883
10884   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10885   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10886 }
10887
10888 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10889
10890   EVT VT = Op.getValueType();
10891   DebugLoc dl = Op.getDebugLoc();
10892   SDValue R = Op.getOperand(0);
10893   SDValue Amt = Op.getOperand(1);
10894   LLVMContext *Context = DAG.getContext();
10895
10896   if (!Subtarget->hasSSE2())
10897     return SDValue();
10898
10899   // Optimize shl/srl/sra with constant shift amount.
10900   if (isSplatVector(Amt.getNode())) {
10901     SDValue SclrAmt = Amt->getOperand(0);
10902     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10903       uint64_t ShiftAmt = C->getZExtValue();
10904
10905       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10906           (Subtarget->hasAVX2() &&
10907            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10908         if (Op.getOpcode() == ISD::SHL)
10909           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10910                              DAG.getConstant(ShiftAmt, MVT::i32));
10911         if (Op.getOpcode() == ISD::SRL)
10912           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10913                              DAG.getConstant(ShiftAmt, MVT::i32));
10914         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10915           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10916                              DAG.getConstant(ShiftAmt, MVT::i32));
10917       }
10918
10919       if (VT == MVT::v16i8) {
10920         if (Op.getOpcode() == ISD::SHL) {
10921           // Make a large shift.
10922           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10923                                     DAG.getConstant(ShiftAmt, MVT::i32));
10924           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10925           // Zero out the rightmost bits.
10926           SmallVector<SDValue, 16> V(16,
10927                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10928                                                      MVT::i8));
10929           return DAG.getNode(ISD::AND, dl, VT, SHL,
10930                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10931         }
10932         if (Op.getOpcode() == ISD::SRL) {
10933           // Make a large shift.
10934           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10935                                     DAG.getConstant(ShiftAmt, MVT::i32));
10936           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10937           // Zero out the leftmost bits.
10938           SmallVector<SDValue, 16> V(16,
10939                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10940                                                      MVT::i8));
10941           return DAG.getNode(ISD::AND, dl, VT, SRL,
10942                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10943         }
10944         if (Op.getOpcode() == ISD::SRA) {
10945           if (ShiftAmt == 7) {
10946             // R s>> 7  ===  R s< 0
10947             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10948             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10949           }
10950
10951           // R s>> a === ((R u>> a) ^ m) - m
10952           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10953           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10954                                                          MVT::i8));
10955           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10956           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10957           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10958           return Res;
10959         }
10960         llvm_unreachable("Unknown shift opcode.");
10961       }
10962
10963       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10964         if (Op.getOpcode() == ISD::SHL) {
10965           // Make a large shift.
10966           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10967                                     DAG.getConstant(ShiftAmt, MVT::i32));
10968           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10969           // Zero out the rightmost bits.
10970           SmallVector<SDValue, 32> V(32,
10971                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10972                                                      MVT::i8));
10973           return DAG.getNode(ISD::AND, dl, VT, SHL,
10974                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10975         }
10976         if (Op.getOpcode() == ISD::SRL) {
10977           // Make a large shift.
10978           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10979                                     DAG.getConstant(ShiftAmt, MVT::i32));
10980           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10981           // Zero out the leftmost bits.
10982           SmallVector<SDValue, 32> V(32,
10983                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10984                                                      MVT::i8));
10985           return DAG.getNode(ISD::AND, dl, VT, SRL,
10986                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10987         }
10988         if (Op.getOpcode() == ISD::SRA) {
10989           if (ShiftAmt == 7) {
10990             // R s>> 7  ===  R s< 0
10991             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10992             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10993           }
10994
10995           // R s>> a === ((R u>> a) ^ m) - m
10996           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10997           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10998                                                          MVT::i8));
10999           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11000           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11001           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11002           return Res;
11003         }
11004         llvm_unreachable("Unknown shift opcode.");
11005       }
11006     }
11007   }
11008
11009   // Lower SHL with variable shift amount.
11010   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11011     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11012                      DAG.getConstant(23, MVT::i32));
11013
11014     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11015     Constant *C = ConstantDataVector::get(*Context, CV);
11016     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11017     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11018                                  MachinePointerInfo::getConstantPool(),
11019                                  false, false, false, 16);
11020
11021     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11022     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11023     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11024     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11025   }
11026   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11027     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11028
11029     // a = a << 5;
11030     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11031                      DAG.getConstant(5, MVT::i32));
11032     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11033
11034     // Turn 'a' into a mask suitable for VSELECT
11035     SDValue VSelM = DAG.getConstant(0x80, VT);
11036     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11037     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11038
11039     SDValue CM1 = DAG.getConstant(0x0f, VT);
11040     SDValue CM2 = DAG.getConstant(0x3f, VT);
11041
11042     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11043     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11044     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11045                             DAG.getConstant(4, MVT::i32), DAG);
11046     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11047     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11048
11049     // a += a
11050     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11051     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11052     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11053
11054     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11055     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11056     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11057                             DAG.getConstant(2, MVT::i32), DAG);
11058     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11059     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11060
11061     // a += a
11062     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11063     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11064     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11065
11066     // return VSELECT(r, r+r, a);
11067     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11068                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11069     return R;
11070   }
11071
11072   // Decompose 256-bit shifts into smaller 128-bit shifts.
11073   if (VT.is256BitVector()) {
11074     unsigned NumElems = VT.getVectorNumElements();
11075     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11076     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11077
11078     // Extract the two vectors
11079     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11080     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11081
11082     // Recreate the shift amount vectors
11083     SDValue Amt1, Amt2;
11084     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11085       // Constant shift amount
11086       SmallVector<SDValue, 4> Amt1Csts;
11087       SmallVector<SDValue, 4> Amt2Csts;
11088       for (unsigned i = 0; i != NumElems/2; ++i)
11089         Amt1Csts.push_back(Amt->getOperand(i));
11090       for (unsigned i = NumElems/2; i != NumElems; ++i)
11091         Amt2Csts.push_back(Amt->getOperand(i));
11092
11093       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11094                                  &Amt1Csts[0], NumElems/2);
11095       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11096                                  &Amt2Csts[0], NumElems/2);
11097     } else {
11098       // Variable shift amount
11099       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11100       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11101     }
11102
11103     // Issue new vector shifts for the smaller types
11104     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11105     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11106
11107     // Concatenate the result back
11108     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11109   }
11110
11111   return SDValue();
11112 }
11113
11114 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11115   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11116   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11117   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11118   // has only one use.
11119   SDNode *N = Op.getNode();
11120   SDValue LHS = N->getOperand(0);
11121   SDValue RHS = N->getOperand(1);
11122   unsigned BaseOp = 0;
11123   unsigned Cond = 0;
11124   DebugLoc DL = Op.getDebugLoc();
11125   switch (Op.getOpcode()) {
11126   default: llvm_unreachable("Unknown ovf instruction!");
11127   case ISD::SADDO:
11128     // A subtract of one will be selected as a INC. Note that INC doesn't
11129     // set CF, so we can't do this for UADDO.
11130     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11131       if (C->isOne()) {
11132         BaseOp = X86ISD::INC;
11133         Cond = X86::COND_O;
11134         break;
11135       }
11136     BaseOp = X86ISD::ADD;
11137     Cond = X86::COND_O;
11138     break;
11139   case ISD::UADDO:
11140     BaseOp = X86ISD::ADD;
11141     Cond = X86::COND_B;
11142     break;
11143   case ISD::SSUBO:
11144     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11145     // set CF, so we can't do this for USUBO.
11146     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11147       if (C->isOne()) {
11148         BaseOp = X86ISD::DEC;
11149         Cond = X86::COND_O;
11150         break;
11151       }
11152     BaseOp = X86ISD::SUB;
11153     Cond = X86::COND_O;
11154     break;
11155   case ISD::USUBO:
11156     BaseOp = X86ISD::SUB;
11157     Cond = X86::COND_B;
11158     break;
11159   case ISD::SMULO:
11160     BaseOp = X86ISD::SMUL;
11161     Cond = X86::COND_O;
11162     break;
11163   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11164     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11165                                  MVT::i32);
11166     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11167
11168     SDValue SetCC =
11169       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11170                   DAG.getConstant(X86::COND_O, MVT::i32),
11171                   SDValue(Sum.getNode(), 2));
11172
11173     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11174   }
11175   }
11176
11177   // Also sets EFLAGS.
11178   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11179   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11180
11181   SDValue SetCC =
11182     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11183                 DAG.getConstant(Cond, MVT::i32),
11184                 SDValue(Sum.getNode(), 1));
11185
11186   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11187 }
11188
11189 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11190                                                   SelectionDAG &DAG) const {
11191   DebugLoc dl = Op.getDebugLoc();
11192   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11193   EVT VT = Op.getValueType();
11194
11195   if (!Subtarget->hasSSE2() || !VT.isVector())
11196     return SDValue();
11197
11198   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11199                       ExtraVT.getScalarType().getSizeInBits();
11200   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11201
11202   switch (VT.getSimpleVT().SimpleTy) {
11203     default: return SDValue();
11204     case MVT::v8i32:
11205     case MVT::v16i16:
11206       if (!Subtarget->hasAVX())
11207         return SDValue();
11208       if (!Subtarget->hasAVX2()) {
11209         // needs to be split
11210         unsigned NumElems = VT.getVectorNumElements();
11211
11212         // Extract the LHS vectors
11213         SDValue LHS = Op.getOperand(0);
11214         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11215         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11216
11217         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11218         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11219
11220         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11221         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11222         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11223                                    ExtraNumElems/2);
11224         SDValue Extra = DAG.getValueType(ExtraVT);
11225
11226         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11227         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11228
11229         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11230       }
11231       // fall through
11232     case MVT::v4i32:
11233     case MVT::v8i16: {
11234       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11235                                          Op.getOperand(0), ShAmt, DAG);
11236       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11237     }
11238   }
11239 }
11240
11241
11242 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11243                               SelectionDAG &DAG) {
11244   DebugLoc dl = Op.getDebugLoc();
11245
11246   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11247   // There isn't any reason to disable it if the target processor supports it.
11248   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11249     SDValue Chain = Op.getOperand(0);
11250     SDValue Zero = DAG.getConstant(0, MVT::i32);
11251     SDValue Ops[] = {
11252       DAG.getRegister(X86::ESP, MVT::i32), // Base
11253       DAG.getTargetConstant(1, MVT::i8),   // Scale
11254       DAG.getRegister(0, MVT::i32),        // Index
11255       DAG.getTargetConstant(0, MVT::i32),  // Disp
11256       DAG.getRegister(0, MVT::i32),        // Segment.
11257       Zero,
11258       Chain
11259     };
11260     SDNode *Res =
11261       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11262                           array_lengthof(Ops));
11263     return SDValue(Res, 0);
11264   }
11265
11266   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11267   if (!isDev)
11268     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11269
11270   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11271   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11272   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11273   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11274
11275   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11276   if (!Op1 && !Op2 && !Op3 && Op4)
11277     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11278
11279   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11280   if (Op1 && !Op2 && !Op3 && !Op4)
11281     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11282
11283   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11284   //           (MFENCE)>;
11285   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11286 }
11287
11288 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11289                                  SelectionDAG &DAG) {
11290   DebugLoc dl = Op.getDebugLoc();
11291   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11292     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11293   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11294     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11295
11296   // The only fence that needs an instruction is a sequentially-consistent
11297   // cross-thread fence.
11298   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11299     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11300     // no-sse2). There isn't any reason to disable it if the target processor
11301     // supports it.
11302     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11303       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11304
11305     SDValue Chain = Op.getOperand(0);
11306     SDValue Zero = DAG.getConstant(0, MVT::i32);
11307     SDValue Ops[] = {
11308       DAG.getRegister(X86::ESP, MVT::i32), // Base
11309       DAG.getTargetConstant(1, MVT::i8),   // Scale
11310       DAG.getRegister(0, MVT::i32),        // Index
11311       DAG.getTargetConstant(0, MVT::i32),  // Disp
11312       DAG.getRegister(0, MVT::i32),        // Segment.
11313       Zero,
11314       Chain
11315     };
11316     SDNode *Res =
11317       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11318                          array_lengthof(Ops));
11319     return SDValue(Res, 0);
11320   }
11321
11322   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11323   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11324 }
11325
11326
11327 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11328                              SelectionDAG &DAG) {
11329   EVT T = Op.getValueType();
11330   DebugLoc DL = Op.getDebugLoc();
11331   unsigned Reg = 0;
11332   unsigned size = 0;
11333   switch(T.getSimpleVT().SimpleTy) {
11334   default: llvm_unreachable("Invalid value type!");
11335   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11336   case MVT::i16: Reg = X86::AX;  size = 2; break;
11337   case MVT::i32: Reg = X86::EAX; size = 4; break;
11338   case MVT::i64:
11339     assert(Subtarget->is64Bit() && "Node not type legal!");
11340     Reg = X86::RAX; size = 8;
11341     break;
11342   }
11343   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11344                                     Op.getOperand(2), SDValue());
11345   SDValue Ops[] = { cpIn.getValue(0),
11346                     Op.getOperand(1),
11347                     Op.getOperand(3),
11348                     DAG.getTargetConstant(size, MVT::i8),
11349                     cpIn.getValue(1) };
11350   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11351   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11352   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11353                                            Ops, 5, T, MMO);
11354   SDValue cpOut =
11355     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11356   return cpOut;
11357 }
11358
11359 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11360                                      SelectionDAG &DAG) {
11361   assert(Subtarget->is64Bit() && "Result not type legalized?");
11362   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11363   SDValue TheChain = Op.getOperand(0);
11364   DebugLoc dl = Op.getDebugLoc();
11365   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11366   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11367   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11368                                    rax.getValue(2));
11369   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11370                             DAG.getConstant(32, MVT::i8));
11371   SDValue Ops[] = {
11372     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11373     rdx.getValue(1)
11374   };
11375   return DAG.getMergeValues(Ops, 2, dl);
11376 }
11377
11378 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11379   EVT SrcVT = Op.getOperand(0).getValueType();
11380   EVT DstVT = Op.getValueType();
11381   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11382          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11383   assert((DstVT == MVT::i64 ||
11384           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11385          "Unexpected custom BITCAST");
11386   // i64 <=> MMX conversions are Legal.
11387   if (SrcVT==MVT::i64 && DstVT.isVector())
11388     return Op;
11389   if (DstVT==MVT::i64 && SrcVT.isVector())
11390     return Op;
11391   // MMX <=> MMX conversions are Legal.
11392   if (SrcVT.isVector() && DstVT.isVector())
11393     return Op;
11394   // All other conversions need to be expanded.
11395   return SDValue();
11396 }
11397
11398 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11399   SDNode *Node = Op.getNode();
11400   DebugLoc dl = Node->getDebugLoc();
11401   EVT T = Node->getValueType(0);
11402   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11403                               DAG.getConstant(0, T), Node->getOperand(2));
11404   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11405                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11406                        Node->getOperand(0),
11407                        Node->getOperand(1), negOp,
11408                        cast<AtomicSDNode>(Node)->getSrcValue(),
11409                        cast<AtomicSDNode>(Node)->getAlignment(),
11410                        cast<AtomicSDNode>(Node)->getOrdering(),
11411                        cast<AtomicSDNode>(Node)->getSynchScope());
11412 }
11413
11414 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11415   SDNode *Node = Op.getNode();
11416   DebugLoc dl = Node->getDebugLoc();
11417   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11418
11419   // Convert seq_cst store -> xchg
11420   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11421   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11422   //        (The only way to get a 16-byte store is cmpxchg16b)
11423   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11424   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11425       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11426     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11427                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11428                                  Node->getOperand(0),
11429                                  Node->getOperand(1), Node->getOperand(2),
11430                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11431                                  cast<AtomicSDNode>(Node)->getOrdering(),
11432                                  cast<AtomicSDNode>(Node)->getSynchScope());
11433     return Swap.getValue(1);
11434   }
11435   // Other atomic stores have a simple pattern.
11436   return Op;
11437 }
11438
11439 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11440   EVT VT = Op.getNode()->getValueType(0);
11441
11442   // Let legalize expand this if it isn't a legal type yet.
11443   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11444     return SDValue();
11445
11446   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11447
11448   unsigned Opc;
11449   bool ExtraOp = false;
11450   switch (Op.getOpcode()) {
11451   default: llvm_unreachable("Invalid code");
11452   case ISD::ADDC: Opc = X86ISD::ADD; break;
11453   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11454   case ISD::SUBC: Opc = X86ISD::SUB; break;
11455   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11456   }
11457
11458   if (!ExtraOp)
11459     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11460                        Op.getOperand(1));
11461   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11462                      Op.getOperand(1), Op.getOperand(2));
11463 }
11464
11465 /// LowerOperation - Provide custom lowering hooks for some operations.
11466 ///
11467 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11468   switch (Op.getOpcode()) {
11469   default: llvm_unreachable("Should not custom lower this!");
11470   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11471   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11472   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11473   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11474   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11475   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11476   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11477   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11478   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11479   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11480   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11481   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11482   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11483   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11484   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11485   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11486   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11487   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11488   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11489   case ISD::SHL_PARTS:
11490   case ISD::SRA_PARTS:
11491   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11492   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11493   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11494   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11495   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11496   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11497   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11498   case ISD::FABS:               return LowerFABS(Op, DAG);
11499   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11500   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11501   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11502   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11503   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11504   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11505   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11506   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11507   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11508   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11509   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11510   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11511   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11512   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11513   case ISD::FRAME_TO_ARGS_OFFSET:
11514                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11515   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11516   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11517   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11518   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11519   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11520   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11521   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11522   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11523   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11524   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11525   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11526   case ISD::SRA:
11527   case ISD::SRL:
11528   case ISD::SHL:                return LowerShift(Op, DAG);
11529   case ISD::SADDO:
11530   case ISD::UADDO:
11531   case ISD::SSUBO:
11532   case ISD::USUBO:
11533   case ISD::SMULO:
11534   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11535   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11536   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11537   case ISD::ADDC:
11538   case ISD::ADDE:
11539   case ISD::SUBC:
11540   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11541   case ISD::ADD:                return LowerADD(Op, DAG);
11542   case ISD::SUB:                return LowerSUB(Op, DAG);
11543   }
11544 }
11545
11546 static void ReplaceATOMIC_LOAD(SDNode *Node,
11547                                   SmallVectorImpl<SDValue> &Results,
11548                                   SelectionDAG &DAG) {
11549   DebugLoc dl = Node->getDebugLoc();
11550   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11551
11552   // Convert wide load -> cmpxchg8b/cmpxchg16b
11553   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11554   //        (The only way to get a 16-byte load is cmpxchg16b)
11555   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11556   SDValue Zero = DAG.getConstant(0, VT);
11557   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11558                                Node->getOperand(0),
11559                                Node->getOperand(1), Zero, Zero,
11560                                cast<AtomicSDNode>(Node)->getMemOperand(),
11561                                cast<AtomicSDNode>(Node)->getOrdering(),
11562                                cast<AtomicSDNode>(Node)->getSynchScope());
11563   Results.push_back(Swap.getValue(0));
11564   Results.push_back(Swap.getValue(1));
11565 }
11566
11567 static void
11568 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11569                         SelectionDAG &DAG, unsigned NewOp) {
11570   DebugLoc dl = Node->getDebugLoc();
11571   assert (Node->getValueType(0) == MVT::i64 &&
11572           "Only know how to expand i64 atomics");
11573
11574   SDValue Chain = Node->getOperand(0);
11575   SDValue In1 = Node->getOperand(1);
11576   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11577                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11578   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11579                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11580   SDValue Ops[] = { Chain, In1, In2L, In2H };
11581   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11582   SDValue Result =
11583     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11584                             cast<MemSDNode>(Node)->getMemOperand());
11585   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11586   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11587   Results.push_back(Result.getValue(2));
11588 }
11589
11590 /// ReplaceNodeResults - Replace a node with an illegal result type
11591 /// with a new node built out of custom code.
11592 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11593                                            SmallVectorImpl<SDValue>&Results,
11594                                            SelectionDAG &DAG) const {
11595   DebugLoc dl = N->getDebugLoc();
11596   switch (N->getOpcode()) {
11597   default:
11598     llvm_unreachable("Do not know how to custom type legalize this operation!");
11599   case ISD::SIGN_EXTEND_INREG:
11600   case ISD::ADDC:
11601   case ISD::ADDE:
11602   case ISD::SUBC:
11603   case ISD::SUBE:
11604     // We don't want to expand or promote these.
11605     return;
11606   case ISD::FP_TO_SINT:
11607   case ISD::FP_TO_UINT: {
11608     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11609
11610     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11611       return;
11612
11613     std::pair<SDValue,SDValue> Vals =
11614         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11615     SDValue FIST = Vals.first, StackSlot = Vals.second;
11616     if (FIST.getNode() != 0) {
11617       EVT VT = N->getValueType(0);
11618       // Return a load from the stack slot.
11619       if (StackSlot.getNode() != 0)
11620         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11621                                       MachinePointerInfo(),
11622                                       false, false, false, 0));
11623       else
11624         Results.push_back(FIST);
11625     }
11626     return;
11627   }
11628   case ISD::FP_ROUND: {
11629     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11630     Results.push_back(V);
11631     return;
11632   }
11633   case ISD::READCYCLECOUNTER: {
11634     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11635     SDValue TheChain = N->getOperand(0);
11636     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11637     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11638                                      rd.getValue(1));
11639     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11640                                      eax.getValue(2));
11641     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11642     SDValue Ops[] = { eax, edx };
11643     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11644     Results.push_back(edx.getValue(1));
11645     return;
11646   }
11647   case ISD::ATOMIC_CMP_SWAP: {
11648     EVT T = N->getValueType(0);
11649     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11650     bool Regs64bit = T == MVT::i128;
11651     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11652     SDValue cpInL, cpInH;
11653     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11654                         DAG.getConstant(0, HalfT));
11655     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11656                         DAG.getConstant(1, HalfT));
11657     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11658                              Regs64bit ? X86::RAX : X86::EAX,
11659                              cpInL, SDValue());
11660     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11661                              Regs64bit ? X86::RDX : X86::EDX,
11662                              cpInH, cpInL.getValue(1));
11663     SDValue swapInL, swapInH;
11664     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11665                           DAG.getConstant(0, HalfT));
11666     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11667                           DAG.getConstant(1, HalfT));
11668     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11669                                Regs64bit ? X86::RBX : X86::EBX,
11670                                swapInL, cpInH.getValue(1));
11671     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11672                                Regs64bit ? X86::RCX : X86::ECX,
11673                                swapInH, swapInL.getValue(1));
11674     SDValue Ops[] = { swapInH.getValue(0),
11675                       N->getOperand(1),
11676                       swapInH.getValue(1) };
11677     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11678     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11679     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11680                                   X86ISD::LCMPXCHG8_DAG;
11681     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11682                                              Ops, 3, T, MMO);
11683     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11684                                         Regs64bit ? X86::RAX : X86::EAX,
11685                                         HalfT, Result.getValue(1));
11686     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11687                                         Regs64bit ? X86::RDX : X86::EDX,
11688                                         HalfT, cpOutL.getValue(2));
11689     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11690     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11691     Results.push_back(cpOutH.getValue(1));
11692     return;
11693   }
11694   case ISD::ATOMIC_LOAD_ADD:
11695   case ISD::ATOMIC_LOAD_AND:
11696   case ISD::ATOMIC_LOAD_NAND:
11697   case ISD::ATOMIC_LOAD_OR:
11698   case ISD::ATOMIC_LOAD_SUB:
11699   case ISD::ATOMIC_LOAD_XOR:
11700   case ISD::ATOMIC_LOAD_MAX:
11701   case ISD::ATOMIC_LOAD_MIN:
11702   case ISD::ATOMIC_LOAD_UMAX:
11703   case ISD::ATOMIC_LOAD_UMIN:
11704   case ISD::ATOMIC_SWAP: {
11705     unsigned Opc;
11706     switch (N->getOpcode()) {
11707     default: llvm_unreachable("Unexpected opcode");
11708     case ISD::ATOMIC_LOAD_ADD:
11709       Opc = X86ISD::ATOMADD64_DAG;
11710       break;
11711     case ISD::ATOMIC_LOAD_AND:
11712       Opc = X86ISD::ATOMAND64_DAG;
11713       break;
11714     case ISD::ATOMIC_LOAD_NAND:
11715       Opc = X86ISD::ATOMNAND64_DAG;
11716       break;
11717     case ISD::ATOMIC_LOAD_OR:
11718       Opc = X86ISD::ATOMOR64_DAG;
11719       break;
11720     case ISD::ATOMIC_LOAD_SUB:
11721       Opc = X86ISD::ATOMSUB64_DAG;
11722       break;
11723     case ISD::ATOMIC_LOAD_XOR:
11724       Opc = X86ISD::ATOMXOR64_DAG;
11725       break;
11726     case ISD::ATOMIC_LOAD_MAX:
11727       Opc = X86ISD::ATOMMAX64_DAG;
11728       break;
11729     case ISD::ATOMIC_LOAD_MIN:
11730       Opc = X86ISD::ATOMMIN64_DAG;
11731       break;
11732     case ISD::ATOMIC_LOAD_UMAX:
11733       Opc = X86ISD::ATOMUMAX64_DAG;
11734       break;
11735     case ISD::ATOMIC_LOAD_UMIN:
11736       Opc = X86ISD::ATOMUMIN64_DAG;
11737       break;
11738     case ISD::ATOMIC_SWAP:
11739       Opc = X86ISD::ATOMSWAP64_DAG;
11740       break;
11741     }
11742     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11743     return;
11744   }
11745   case ISD::ATOMIC_LOAD:
11746     ReplaceATOMIC_LOAD(N, Results, DAG);
11747   }
11748 }
11749
11750 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11751   switch (Opcode) {
11752   default: return NULL;
11753   case X86ISD::BSF:                return "X86ISD::BSF";
11754   case X86ISD::BSR:                return "X86ISD::BSR";
11755   case X86ISD::SHLD:               return "X86ISD::SHLD";
11756   case X86ISD::SHRD:               return "X86ISD::SHRD";
11757   case X86ISD::FAND:               return "X86ISD::FAND";
11758   case X86ISD::FOR:                return "X86ISD::FOR";
11759   case X86ISD::FXOR:               return "X86ISD::FXOR";
11760   case X86ISD::FSRL:               return "X86ISD::FSRL";
11761   case X86ISD::FILD:               return "X86ISD::FILD";
11762   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11763   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11764   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11765   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11766   case X86ISD::FLD:                return "X86ISD::FLD";
11767   case X86ISD::FST:                return "X86ISD::FST";
11768   case X86ISD::CALL:               return "X86ISD::CALL";
11769   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11770   case X86ISD::BT:                 return "X86ISD::BT";
11771   case X86ISD::CMP:                return "X86ISD::CMP";
11772   case X86ISD::COMI:               return "X86ISD::COMI";
11773   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11774   case X86ISD::SETCC:              return "X86ISD::SETCC";
11775   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11776   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11777   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11778   case X86ISD::CMOV:               return "X86ISD::CMOV";
11779   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11780   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11781   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11782   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11783   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11784   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11785   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11786   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11787   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11788   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11789   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11790   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11791   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11792   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11793   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11794   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11795   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11796   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11797   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11798   case X86ISD::HADD:               return "X86ISD::HADD";
11799   case X86ISD::HSUB:               return "X86ISD::HSUB";
11800   case X86ISD::FHADD:              return "X86ISD::FHADD";
11801   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11802   case X86ISD::FMAX:               return "X86ISD::FMAX";
11803   case X86ISD::FMIN:               return "X86ISD::FMIN";
11804   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11805   case X86ISD::FMINC:              return "X86ISD::FMINC";
11806   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11807   case X86ISD::FRCP:               return "X86ISD::FRCP";
11808   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11809   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11810   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11811   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11812   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11813   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11814   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11815   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11816   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11817   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11818   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11819   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11820   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11821   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11822   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11823   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11824   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11825   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11826   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11827   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11828   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11829   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11830   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11831   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11832   case X86ISD::VSHL:               return "X86ISD::VSHL";
11833   case X86ISD::VSRL:               return "X86ISD::VSRL";
11834   case X86ISD::VSRA:               return "X86ISD::VSRA";
11835   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11836   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11837   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11838   case X86ISD::CMPP:               return "X86ISD::CMPP";
11839   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11840   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11841   case X86ISD::ADD:                return "X86ISD::ADD";
11842   case X86ISD::SUB:                return "X86ISD::SUB";
11843   case X86ISD::ADC:                return "X86ISD::ADC";
11844   case X86ISD::SBB:                return "X86ISD::SBB";
11845   case X86ISD::SMUL:               return "X86ISD::SMUL";
11846   case X86ISD::UMUL:               return "X86ISD::UMUL";
11847   case X86ISD::INC:                return "X86ISD::INC";
11848   case X86ISD::DEC:                return "X86ISD::DEC";
11849   case X86ISD::OR:                 return "X86ISD::OR";
11850   case X86ISD::XOR:                return "X86ISD::XOR";
11851   case X86ISD::AND:                return "X86ISD::AND";
11852   case X86ISD::ANDN:               return "X86ISD::ANDN";
11853   case X86ISD::BLSI:               return "X86ISD::BLSI";
11854   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11855   case X86ISD::BLSR:               return "X86ISD::BLSR";
11856   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11857   case X86ISD::PTEST:              return "X86ISD::PTEST";
11858   case X86ISD::TESTP:              return "X86ISD::TESTP";
11859   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11860   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11861   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11862   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11863   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11864   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11865   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11866   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11867   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11868   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11869   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11870   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11871   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11872   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11873   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11874   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11875   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11876   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11877   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11878   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11879   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11880   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11881   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11882   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11883   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11884   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11885   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11886   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11887   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11888   case X86ISD::SAHF:               return "X86ISD::SAHF";
11889   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11890   case X86ISD::FMADD:              return "X86ISD::FMADD";
11891   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11892   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11893   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11894   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11895   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11896   }
11897 }
11898
11899 // isLegalAddressingMode - Return true if the addressing mode represented
11900 // by AM is legal for this target, for a load/store of the specified type.
11901 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11902                                               Type *Ty) const {
11903   // X86 supports extremely general addressing modes.
11904   CodeModel::Model M = getTargetMachine().getCodeModel();
11905   Reloc::Model R = getTargetMachine().getRelocationModel();
11906
11907   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11908   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11909     return false;
11910
11911   if (AM.BaseGV) {
11912     unsigned GVFlags =
11913       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11914
11915     // If a reference to this global requires an extra load, we can't fold it.
11916     if (isGlobalStubReference(GVFlags))
11917       return false;
11918
11919     // If BaseGV requires a register for the PIC base, we cannot also have a
11920     // BaseReg specified.
11921     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11922       return false;
11923
11924     // If lower 4G is not available, then we must use rip-relative addressing.
11925     if ((M != CodeModel::Small || R != Reloc::Static) &&
11926         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11927       return false;
11928   }
11929
11930   switch (AM.Scale) {
11931   case 0:
11932   case 1:
11933   case 2:
11934   case 4:
11935   case 8:
11936     // These scales always work.
11937     break;
11938   case 3:
11939   case 5:
11940   case 9:
11941     // These scales are formed with basereg+scalereg.  Only accept if there is
11942     // no basereg yet.
11943     if (AM.HasBaseReg)
11944       return false;
11945     break;
11946   default:  // Other stuff never works.
11947     return false;
11948   }
11949
11950   return true;
11951 }
11952
11953
11954 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11955   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11956     return false;
11957   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11958   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11959   if (NumBits1 <= NumBits2)
11960     return false;
11961   return true;
11962 }
11963
11964 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11965   return Imm == (int32_t)Imm;
11966 }
11967
11968 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11969   // Can also use sub to handle negated immediates.
11970   return Imm == (int32_t)Imm;
11971 }
11972
11973 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11974   if (!VT1.isInteger() || !VT2.isInteger())
11975     return false;
11976   unsigned NumBits1 = VT1.getSizeInBits();
11977   unsigned NumBits2 = VT2.getSizeInBits();
11978   if (NumBits1 <= NumBits2)
11979     return false;
11980   return true;
11981 }
11982
11983 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11984   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11985   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11986 }
11987
11988 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11989   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11990   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11991 }
11992
11993 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11994   // i16 instructions are longer (0x66 prefix) and potentially slower.
11995   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11996 }
11997
11998 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11999 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12000 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12001 /// are assumed to be legal.
12002 bool
12003 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12004                                       EVT VT) const {
12005   // Very little shuffling can be done for 64-bit vectors right now.
12006   if (VT.getSizeInBits() == 64)
12007     return false;
12008
12009   // FIXME: pshufb, blends, shifts.
12010   return (VT.getVectorNumElements() == 2 ||
12011           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12012           isMOVLMask(M, VT) ||
12013           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12014           isPSHUFDMask(M, VT) ||
12015           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12016           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12017           isPALIGNRMask(M, VT, Subtarget) ||
12018           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12019           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12020           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12021           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12022 }
12023
12024 bool
12025 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12026                                           EVT VT) const {
12027   unsigned NumElts = VT.getVectorNumElements();
12028   // FIXME: This collection of masks seems suspect.
12029   if (NumElts == 2)
12030     return true;
12031   if (NumElts == 4 && VT.is128BitVector()) {
12032     return (isMOVLMask(Mask, VT)  ||
12033             isCommutedMOVLMask(Mask, VT, true) ||
12034             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12035             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12036   }
12037   return false;
12038 }
12039
12040 //===----------------------------------------------------------------------===//
12041 //                           X86 Scheduler Hooks
12042 //===----------------------------------------------------------------------===//
12043
12044 // private utility function
12045
12046 // Get CMPXCHG opcode for the specified data type.
12047 static unsigned getCmpXChgOpcode(EVT VT) {
12048   switch (VT.getSimpleVT().SimpleTy) {
12049   case MVT::i8:  return X86::LCMPXCHG8;
12050   case MVT::i16: return X86::LCMPXCHG16;
12051   case MVT::i32: return X86::LCMPXCHG32;
12052   case MVT::i64: return X86::LCMPXCHG64;
12053   default:
12054     break;
12055   }
12056   llvm_unreachable("Invalid operand size!");
12057 }
12058
12059 // Get LOAD opcode for the specified data type.
12060 static unsigned getLoadOpcode(EVT VT) {
12061   switch (VT.getSimpleVT().SimpleTy) {
12062   case MVT::i8:  return X86::MOV8rm;
12063   case MVT::i16: return X86::MOV16rm;
12064   case MVT::i32: return X86::MOV32rm;
12065   case MVT::i64: return X86::MOV64rm;
12066   default:
12067     break;
12068   }
12069   llvm_unreachable("Invalid operand size!");
12070 }
12071
12072 // Get opcode of the non-atomic one from the specified atomic instruction.
12073 static unsigned getNonAtomicOpcode(unsigned Opc) {
12074   switch (Opc) {
12075   case X86::ATOMAND8:  return X86::AND8rr;
12076   case X86::ATOMAND16: return X86::AND16rr;
12077   case X86::ATOMAND32: return X86::AND32rr;
12078   case X86::ATOMAND64: return X86::AND64rr;
12079   case X86::ATOMOR8:   return X86::OR8rr;
12080   case X86::ATOMOR16:  return X86::OR16rr;
12081   case X86::ATOMOR32:  return X86::OR32rr;
12082   case X86::ATOMOR64:  return X86::OR64rr;
12083   case X86::ATOMXOR8:  return X86::XOR8rr;
12084   case X86::ATOMXOR16: return X86::XOR16rr;
12085   case X86::ATOMXOR32: return X86::XOR32rr;
12086   case X86::ATOMXOR64: return X86::XOR64rr;
12087   }
12088   llvm_unreachable("Unhandled atomic-load-op opcode!");
12089 }
12090
12091 // Get opcode of the non-atomic one from the specified atomic instruction with
12092 // extra opcode.
12093 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12094                                                unsigned &ExtraOpc) {
12095   switch (Opc) {
12096   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12097   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12098   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12099   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12100   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12101   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12102   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12103   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12104   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12105   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12106   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12107   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12108   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12109   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12110   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12111   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12112   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12113   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12114   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12115   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12116   }
12117   llvm_unreachable("Unhandled atomic-load-op opcode!");
12118 }
12119
12120 // Get opcode of the non-atomic one from the specified atomic instruction for
12121 // 64-bit data type on 32-bit target.
12122 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12123   switch (Opc) {
12124   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12125   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12126   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12127   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12128   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12129   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12130   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12131   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12132   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12133   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12134   }
12135   llvm_unreachable("Unhandled atomic-load-op opcode!");
12136 }
12137
12138 // Get opcode of the non-atomic one from the specified atomic instruction for
12139 // 64-bit data type on 32-bit target with extra opcode.
12140 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12141                                                    unsigned &HiOpc,
12142                                                    unsigned &ExtraOpc) {
12143   switch (Opc) {
12144   case X86::ATOMNAND6432:
12145     ExtraOpc = X86::NOT32r;
12146     HiOpc = X86::AND32rr;
12147     return X86::AND32rr;
12148   }
12149   llvm_unreachable("Unhandled atomic-load-op opcode!");
12150 }
12151
12152 // Get pseudo CMOV opcode from the specified data type.
12153 static unsigned getPseudoCMOVOpc(EVT VT) {
12154   switch (VT.getSimpleVT().SimpleTy) {
12155   case MVT::i8:  return X86::CMOV_GR8;
12156   case MVT::i16: return X86::CMOV_GR16;
12157   case MVT::i32: return X86::CMOV_GR32;
12158   default:
12159     break;
12160   }
12161   llvm_unreachable("Unknown CMOV opcode!");
12162 }
12163
12164 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12165 // They will be translated into a spin-loop or compare-exchange loop from
12166 //
12167 //    ...
12168 //    dst = atomic-fetch-op MI.addr, MI.val
12169 //    ...
12170 //
12171 // to
12172 //
12173 //    ...
12174 //    EAX = LOAD MI.addr
12175 // loop:
12176 //    t1 = OP MI.val, EAX
12177 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12178 //    JNE loop
12179 // sink:
12180 //    dst = EAX
12181 //    ...
12182 MachineBasicBlock *
12183 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12184                                        MachineBasicBlock *MBB) const {
12185   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12186   DebugLoc DL = MI->getDebugLoc();
12187
12188   MachineFunction *MF = MBB->getParent();
12189   MachineRegisterInfo &MRI = MF->getRegInfo();
12190
12191   const BasicBlock *BB = MBB->getBasicBlock();
12192   MachineFunction::iterator I = MBB;
12193   ++I;
12194
12195   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12196          "Unexpected number of operands");
12197
12198   assert(MI->hasOneMemOperand() &&
12199          "Expected atomic-load-op to have one memoperand");
12200
12201   // Memory Reference
12202   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12203   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12204
12205   unsigned DstReg, SrcReg;
12206   unsigned MemOpndSlot;
12207
12208   unsigned CurOp = 0;
12209
12210   DstReg = MI->getOperand(CurOp++).getReg();
12211   MemOpndSlot = CurOp;
12212   CurOp += X86::AddrNumOperands;
12213   SrcReg = MI->getOperand(CurOp++).getReg();
12214
12215   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12216   MVT::SimpleValueType VT = *RC->vt_begin();
12217   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12218
12219   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12220   unsigned LOADOpc = getLoadOpcode(VT);
12221
12222   // For the atomic load-arith operator, we generate
12223   //
12224   //  thisMBB:
12225   //    EAX = LOAD [MI.addr]
12226   //  mainMBB:
12227   //    t1 = OP MI.val, EAX
12228   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12229   //    JNE mainMBB
12230   //  sinkMBB:
12231
12232   MachineBasicBlock *thisMBB = MBB;
12233   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12234   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12235   MF->insert(I, mainMBB);
12236   MF->insert(I, sinkMBB);
12237
12238   MachineInstrBuilder MIB;
12239
12240   // Transfer the remainder of BB and its successor edges to sinkMBB.
12241   sinkMBB->splice(sinkMBB->begin(), MBB,
12242                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12243   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12244
12245   // thisMBB:
12246   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12247   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12248     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12249   MIB.setMemRefs(MMOBegin, MMOEnd);
12250
12251   thisMBB->addSuccessor(mainMBB);
12252
12253   // mainMBB:
12254   MachineBasicBlock *origMainMBB = mainMBB;
12255   mainMBB->addLiveIn(AccPhyReg);
12256
12257   // Copy AccPhyReg as it is used more than once.
12258   unsigned AccReg = MRI.createVirtualRegister(RC);
12259   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12260     .addReg(AccPhyReg);
12261
12262   unsigned t1 = MRI.createVirtualRegister(RC);
12263   unsigned Opc = MI->getOpcode();
12264   switch (Opc) {
12265   default:
12266     llvm_unreachable("Unhandled atomic-load-op opcode!");
12267   case X86::ATOMAND8:
12268   case X86::ATOMAND16:
12269   case X86::ATOMAND32:
12270   case X86::ATOMAND64:
12271   case X86::ATOMOR8:
12272   case X86::ATOMOR16:
12273   case X86::ATOMOR32:
12274   case X86::ATOMOR64:
12275   case X86::ATOMXOR8:
12276   case X86::ATOMXOR16:
12277   case X86::ATOMXOR32:
12278   case X86::ATOMXOR64: {
12279     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12280     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12281       .addReg(AccReg);
12282     break;
12283   }
12284   case X86::ATOMNAND8:
12285   case X86::ATOMNAND16:
12286   case X86::ATOMNAND32:
12287   case X86::ATOMNAND64: {
12288     unsigned t2 = MRI.createVirtualRegister(RC);
12289     unsigned NOTOpc;
12290     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12291     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12292       .addReg(AccReg);
12293     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12294     break;
12295   }
12296   case X86::ATOMMAX8:
12297   case X86::ATOMMAX16:
12298   case X86::ATOMMAX32:
12299   case X86::ATOMMAX64:
12300   case X86::ATOMMIN8:
12301   case X86::ATOMMIN16:
12302   case X86::ATOMMIN32:
12303   case X86::ATOMMIN64:
12304   case X86::ATOMUMAX8:
12305   case X86::ATOMUMAX16:
12306   case X86::ATOMUMAX32:
12307   case X86::ATOMUMAX64:
12308   case X86::ATOMUMIN8:
12309   case X86::ATOMUMIN16:
12310   case X86::ATOMUMIN32:
12311   case X86::ATOMUMIN64: {
12312     unsigned CMPOpc;
12313     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12314
12315     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12316       .addReg(SrcReg)
12317       .addReg(AccReg);
12318
12319     if (Subtarget->hasCMov()) {
12320       if (VT != MVT::i8) {
12321         // Native support
12322         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12323           .addReg(SrcReg)
12324           .addReg(AccReg);
12325       } else {
12326         // Promote i8 to i32 to use CMOV32
12327         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12328         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12329         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12330         unsigned t2 = MRI.createVirtualRegister(RC32);
12331
12332         unsigned Undef = MRI.createVirtualRegister(RC32);
12333         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12334
12335         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12336           .addReg(Undef)
12337           .addReg(SrcReg)
12338           .addImm(X86::sub_8bit);
12339         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12340           .addReg(Undef)
12341           .addReg(AccReg)
12342           .addImm(X86::sub_8bit);
12343
12344         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12345           .addReg(SrcReg32)
12346           .addReg(AccReg32);
12347
12348         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12349           .addReg(t2, 0, X86::sub_8bit);
12350       }
12351     } else {
12352       // Use pseudo select and lower them.
12353       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12354              "Invalid atomic-load-op transformation!");
12355       unsigned SelOpc = getPseudoCMOVOpc(VT);
12356       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12357       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12358       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12359               .addReg(SrcReg).addReg(AccReg)
12360               .addImm(CC);
12361       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12362     }
12363     break;
12364   }
12365   }
12366
12367   // Copy AccPhyReg back from virtual register.
12368   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12369     .addReg(AccReg);
12370
12371   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12372   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12373     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12374   MIB.addReg(t1);
12375   MIB.setMemRefs(MMOBegin, MMOEnd);
12376
12377   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12378
12379   mainMBB->addSuccessor(origMainMBB);
12380   mainMBB->addSuccessor(sinkMBB);
12381
12382   // sinkMBB:
12383   sinkMBB->addLiveIn(AccPhyReg);
12384
12385   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12386           TII->get(TargetOpcode::COPY), DstReg)
12387     .addReg(AccPhyReg);
12388
12389   MI->eraseFromParent();
12390   return sinkMBB;
12391 }
12392
12393 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12394 // instructions. They will be translated into a spin-loop or compare-exchange
12395 // loop from
12396 //
12397 //    ...
12398 //    dst = atomic-fetch-op MI.addr, MI.val
12399 //    ...
12400 //
12401 // to
12402 //
12403 //    ...
12404 //    EAX = LOAD [MI.addr + 0]
12405 //    EDX = LOAD [MI.addr + 4]
12406 // loop:
12407 //    EBX = OP MI.val.lo, EAX
12408 //    ECX = OP MI.val.hi, EDX
12409 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12410 //    JNE loop
12411 // sink:
12412 //    dst = EDX:EAX
12413 //    ...
12414 MachineBasicBlock *
12415 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12416                                            MachineBasicBlock *MBB) const {
12417   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12418   DebugLoc DL = MI->getDebugLoc();
12419
12420   MachineFunction *MF = MBB->getParent();
12421   MachineRegisterInfo &MRI = MF->getRegInfo();
12422
12423   const BasicBlock *BB = MBB->getBasicBlock();
12424   MachineFunction::iterator I = MBB;
12425   ++I;
12426
12427   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12428          "Unexpected number of operands");
12429
12430   assert(MI->hasOneMemOperand() &&
12431          "Expected atomic-load-op32 to have one memoperand");
12432
12433   // Memory Reference
12434   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12435   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12436
12437   unsigned DstLoReg, DstHiReg;
12438   unsigned SrcLoReg, SrcHiReg;
12439   unsigned MemOpndSlot;
12440
12441   unsigned CurOp = 0;
12442
12443   DstLoReg = MI->getOperand(CurOp++).getReg();
12444   DstHiReg = MI->getOperand(CurOp++).getReg();
12445   MemOpndSlot = CurOp;
12446   CurOp += X86::AddrNumOperands;
12447   SrcLoReg = MI->getOperand(CurOp++).getReg();
12448   SrcHiReg = MI->getOperand(CurOp++).getReg();
12449
12450   const TargetRegisterClass *RC = &X86::GR32RegClass;
12451   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12452
12453   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12454   unsigned LOADOpc = X86::MOV32rm;
12455
12456   // For the atomic load-arith operator, we generate
12457   //
12458   //  thisMBB:
12459   //    EAX = LOAD [MI.addr + 0]
12460   //    EDX = LOAD [MI.addr + 4]
12461   //  mainMBB:
12462   //    EBX = OP MI.vallo, EAX
12463   //    ECX = OP MI.valhi, EDX
12464   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12465   //    JNE mainMBB
12466   //  sinkMBB:
12467
12468   MachineBasicBlock *thisMBB = MBB;
12469   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12470   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12471   MF->insert(I, mainMBB);
12472   MF->insert(I, sinkMBB);
12473
12474   MachineInstrBuilder MIB;
12475
12476   // Transfer the remainder of BB and its successor edges to sinkMBB.
12477   sinkMBB->splice(sinkMBB->begin(), MBB,
12478                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12479   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12480
12481   // thisMBB:
12482   // Lo
12483   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12484   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12485     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12486   MIB.setMemRefs(MMOBegin, MMOEnd);
12487   // Hi
12488   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12489   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12490     if (i == X86::AddrDisp)
12491       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12492     else
12493       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12494   }
12495   MIB.setMemRefs(MMOBegin, MMOEnd);
12496
12497   thisMBB->addSuccessor(mainMBB);
12498
12499   // mainMBB:
12500   MachineBasicBlock *origMainMBB = mainMBB;
12501   mainMBB->addLiveIn(X86::EAX);
12502   mainMBB->addLiveIn(X86::EDX);
12503
12504   // Copy EDX:EAX as they are used more than once.
12505   unsigned LoReg = MRI.createVirtualRegister(RC);
12506   unsigned HiReg = MRI.createVirtualRegister(RC);
12507   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12508   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12509
12510   unsigned t1L = MRI.createVirtualRegister(RC);
12511   unsigned t1H = MRI.createVirtualRegister(RC);
12512
12513   unsigned Opc = MI->getOpcode();
12514   switch (Opc) {
12515   default:
12516     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12517   case X86::ATOMAND6432:
12518   case X86::ATOMOR6432:
12519   case X86::ATOMXOR6432:
12520   case X86::ATOMADD6432:
12521   case X86::ATOMSUB6432: {
12522     unsigned HiOpc;
12523     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12524     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12525     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12526     break;
12527   }
12528   case X86::ATOMNAND6432: {
12529     unsigned HiOpc, NOTOpc;
12530     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12531     unsigned t2L = MRI.createVirtualRegister(RC);
12532     unsigned t2H = MRI.createVirtualRegister(RC);
12533     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12534     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12535     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12536     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12537     break;
12538   }
12539   case X86::ATOMMAX6432:
12540   case X86::ATOMMIN6432:
12541   case X86::ATOMUMAX6432:
12542   case X86::ATOMUMIN6432: {
12543     unsigned HiOpc;
12544     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12545     unsigned cL = MRI.createVirtualRegister(RC8);
12546     unsigned cH = MRI.createVirtualRegister(RC8);
12547     unsigned cL32 = MRI.createVirtualRegister(RC);
12548     unsigned cH32 = MRI.createVirtualRegister(RC);
12549     unsigned cc = MRI.createVirtualRegister(RC);
12550     // cl := cmp src_lo, lo
12551     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12552       .addReg(SrcLoReg).addReg(LoReg);
12553     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12554     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12555     // ch := cmp src_hi, hi
12556     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12557       .addReg(SrcHiReg).addReg(HiReg);
12558     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12559     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12560     // cc := if (src_hi == hi) ? cl : ch;
12561     if (Subtarget->hasCMov()) {
12562       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12563         .addReg(cH32).addReg(cL32);
12564     } else {
12565       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12566               .addReg(cH32).addReg(cL32)
12567               .addImm(X86::COND_E);
12568       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12569     }
12570     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12571     if (Subtarget->hasCMov()) {
12572       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12573         .addReg(SrcLoReg).addReg(LoReg);
12574       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12575         .addReg(SrcHiReg).addReg(HiReg);
12576     } else {
12577       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12578               .addReg(SrcLoReg).addReg(LoReg)
12579               .addImm(X86::COND_NE);
12580       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12581       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12582               .addReg(SrcHiReg).addReg(HiReg)
12583               .addImm(X86::COND_NE);
12584       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12585     }
12586     break;
12587   }
12588   case X86::ATOMSWAP6432: {
12589     unsigned HiOpc;
12590     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12591     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12592     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12593     break;
12594   }
12595   }
12596
12597   // Copy EDX:EAX back from HiReg:LoReg
12598   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12599   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12600   // Copy ECX:EBX from t1H:t1L
12601   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12602   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12603
12604   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12605   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12606     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12607   MIB.setMemRefs(MMOBegin, MMOEnd);
12608
12609   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12610
12611   mainMBB->addSuccessor(origMainMBB);
12612   mainMBB->addSuccessor(sinkMBB);
12613
12614   // sinkMBB:
12615   sinkMBB->addLiveIn(X86::EAX);
12616   sinkMBB->addLiveIn(X86::EDX);
12617
12618   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12619           TII->get(TargetOpcode::COPY), DstLoReg)
12620     .addReg(X86::EAX);
12621   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12622           TII->get(TargetOpcode::COPY), DstHiReg)
12623     .addReg(X86::EDX);
12624
12625   MI->eraseFromParent();
12626   return sinkMBB;
12627 }
12628
12629 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12630 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12631 // in the .td file.
12632 MachineBasicBlock *
12633 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12634                             unsigned numArgs, bool memArg) const {
12635   assert(Subtarget->hasSSE42() &&
12636          "Target must have SSE4.2 or AVX features enabled");
12637
12638   DebugLoc dl = MI->getDebugLoc();
12639   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12640   unsigned Opc;
12641   if (!Subtarget->hasAVX()) {
12642     if (memArg)
12643       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12644     else
12645       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12646   } else {
12647     if (memArg)
12648       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12649     else
12650       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12651   }
12652
12653   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12654   for (unsigned i = 0; i < numArgs; ++i) {
12655     MachineOperand &Op = MI->getOperand(i+1);
12656     if (!(Op.isReg() && Op.isImplicit()))
12657       MIB.addOperand(Op);
12658   }
12659   BuildMI(*BB, MI, dl,
12660     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12661     .addReg(X86::XMM0);
12662
12663   MI->eraseFromParent();
12664   return BB;
12665 }
12666
12667 MachineBasicBlock *
12668 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12669   DebugLoc dl = MI->getDebugLoc();
12670   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12671
12672   // Address into RAX/EAX, other two args into ECX, EDX.
12673   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12674   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12675   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12676   for (int i = 0; i < X86::AddrNumOperands; ++i)
12677     MIB.addOperand(MI->getOperand(i));
12678
12679   unsigned ValOps = X86::AddrNumOperands;
12680   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12681     .addReg(MI->getOperand(ValOps).getReg());
12682   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12683     .addReg(MI->getOperand(ValOps+1).getReg());
12684
12685   // The instruction doesn't actually take any operands though.
12686   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12687
12688   MI->eraseFromParent(); // The pseudo is gone now.
12689   return BB;
12690 }
12691
12692 MachineBasicBlock *
12693 X86TargetLowering::EmitVAARG64WithCustomInserter(
12694                    MachineInstr *MI,
12695                    MachineBasicBlock *MBB) const {
12696   // Emit va_arg instruction on X86-64.
12697
12698   // Operands to this pseudo-instruction:
12699   // 0  ) Output        : destination address (reg)
12700   // 1-5) Input         : va_list address (addr, i64mem)
12701   // 6  ) ArgSize       : Size (in bytes) of vararg type
12702   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12703   // 8  ) Align         : Alignment of type
12704   // 9  ) EFLAGS (implicit-def)
12705
12706   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12707   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12708
12709   unsigned DestReg = MI->getOperand(0).getReg();
12710   MachineOperand &Base = MI->getOperand(1);
12711   MachineOperand &Scale = MI->getOperand(2);
12712   MachineOperand &Index = MI->getOperand(3);
12713   MachineOperand &Disp = MI->getOperand(4);
12714   MachineOperand &Segment = MI->getOperand(5);
12715   unsigned ArgSize = MI->getOperand(6).getImm();
12716   unsigned ArgMode = MI->getOperand(7).getImm();
12717   unsigned Align = MI->getOperand(8).getImm();
12718
12719   // Memory Reference
12720   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12721   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12722   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12723
12724   // Machine Information
12725   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12726   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12727   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12728   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12729   DebugLoc DL = MI->getDebugLoc();
12730
12731   // struct va_list {
12732   //   i32   gp_offset
12733   //   i32   fp_offset
12734   //   i64   overflow_area (address)
12735   //   i64   reg_save_area (address)
12736   // }
12737   // sizeof(va_list) = 24
12738   // alignment(va_list) = 8
12739
12740   unsigned TotalNumIntRegs = 6;
12741   unsigned TotalNumXMMRegs = 8;
12742   bool UseGPOffset = (ArgMode == 1);
12743   bool UseFPOffset = (ArgMode == 2);
12744   unsigned MaxOffset = TotalNumIntRegs * 8 +
12745                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12746
12747   /* Align ArgSize to a multiple of 8 */
12748   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12749   bool NeedsAlign = (Align > 8);
12750
12751   MachineBasicBlock *thisMBB = MBB;
12752   MachineBasicBlock *overflowMBB;
12753   MachineBasicBlock *offsetMBB;
12754   MachineBasicBlock *endMBB;
12755
12756   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12757   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12758   unsigned OffsetReg = 0;
12759
12760   if (!UseGPOffset && !UseFPOffset) {
12761     // If we only pull from the overflow region, we don't create a branch.
12762     // We don't need to alter control flow.
12763     OffsetDestReg = 0; // unused
12764     OverflowDestReg = DestReg;
12765
12766     offsetMBB = NULL;
12767     overflowMBB = thisMBB;
12768     endMBB = thisMBB;
12769   } else {
12770     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12771     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12772     // If not, pull from overflow_area. (branch to overflowMBB)
12773     //
12774     //       thisMBB
12775     //         |     .
12776     //         |        .
12777     //     offsetMBB   overflowMBB
12778     //         |        .
12779     //         |     .
12780     //        endMBB
12781
12782     // Registers for the PHI in endMBB
12783     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12784     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12785
12786     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12787     MachineFunction *MF = MBB->getParent();
12788     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12789     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12790     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12791
12792     MachineFunction::iterator MBBIter = MBB;
12793     ++MBBIter;
12794
12795     // Insert the new basic blocks
12796     MF->insert(MBBIter, offsetMBB);
12797     MF->insert(MBBIter, overflowMBB);
12798     MF->insert(MBBIter, endMBB);
12799
12800     // Transfer the remainder of MBB and its successor edges to endMBB.
12801     endMBB->splice(endMBB->begin(), thisMBB,
12802                     llvm::next(MachineBasicBlock::iterator(MI)),
12803                     thisMBB->end());
12804     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12805
12806     // Make offsetMBB and overflowMBB successors of thisMBB
12807     thisMBB->addSuccessor(offsetMBB);
12808     thisMBB->addSuccessor(overflowMBB);
12809
12810     // endMBB is a successor of both offsetMBB and overflowMBB
12811     offsetMBB->addSuccessor(endMBB);
12812     overflowMBB->addSuccessor(endMBB);
12813
12814     // Load the offset value into a register
12815     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12816     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12817       .addOperand(Base)
12818       .addOperand(Scale)
12819       .addOperand(Index)
12820       .addDisp(Disp, UseFPOffset ? 4 : 0)
12821       .addOperand(Segment)
12822       .setMemRefs(MMOBegin, MMOEnd);
12823
12824     // Check if there is enough room left to pull this argument.
12825     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12826       .addReg(OffsetReg)
12827       .addImm(MaxOffset + 8 - ArgSizeA8);
12828
12829     // Branch to "overflowMBB" if offset >= max
12830     // Fall through to "offsetMBB" otherwise
12831     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12832       .addMBB(overflowMBB);
12833   }
12834
12835   // In offsetMBB, emit code to use the reg_save_area.
12836   if (offsetMBB) {
12837     assert(OffsetReg != 0);
12838
12839     // Read the reg_save_area address.
12840     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12841     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12842       .addOperand(Base)
12843       .addOperand(Scale)
12844       .addOperand(Index)
12845       .addDisp(Disp, 16)
12846       .addOperand(Segment)
12847       .setMemRefs(MMOBegin, MMOEnd);
12848
12849     // Zero-extend the offset
12850     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12851       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12852         .addImm(0)
12853         .addReg(OffsetReg)
12854         .addImm(X86::sub_32bit);
12855
12856     // Add the offset to the reg_save_area to get the final address.
12857     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12858       .addReg(OffsetReg64)
12859       .addReg(RegSaveReg);
12860
12861     // Compute the offset for the next argument
12862     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12863     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12864       .addReg(OffsetReg)
12865       .addImm(UseFPOffset ? 16 : 8);
12866
12867     // Store it back into the va_list.
12868     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12869       .addOperand(Base)
12870       .addOperand(Scale)
12871       .addOperand(Index)
12872       .addDisp(Disp, UseFPOffset ? 4 : 0)
12873       .addOperand(Segment)
12874       .addReg(NextOffsetReg)
12875       .setMemRefs(MMOBegin, MMOEnd);
12876
12877     // Jump to endMBB
12878     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12879       .addMBB(endMBB);
12880   }
12881
12882   //
12883   // Emit code to use overflow area
12884   //
12885
12886   // Load the overflow_area address into a register.
12887   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12888   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12889     .addOperand(Base)
12890     .addOperand(Scale)
12891     .addOperand(Index)
12892     .addDisp(Disp, 8)
12893     .addOperand(Segment)
12894     .setMemRefs(MMOBegin, MMOEnd);
12895
12896   // If we need to align it, do so. Otherwise, just copy the address
12897   // to OverflowDestReg.
12898   if (NeedsAlign) {
12899     // Align the overflow address
12900     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12901     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12902
12903     // aligned_addr = (addr + (align-1)) & ~(align-1)
12904     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12905       .addReg(OverflowAddrReg)
12906       .addImm(Align-1);
12907
12908     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12909       .addReg(TmpReg)
12910       .addImm(~(uint64_t)(Align-1));
12911   } else {
12912     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12913       .addReg(OverflowAddrReg);
12914   }
12915
12916   // Compute the next overflow address after this argument.
12917   // (the overflow address should be kept 8-byte aligned)
12918   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12919   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12920     .addReg(OverflowDestReg)
12921     .addImm(ArgSizeA8);
12922
12923   // Store the new overflow address.
12924   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12925     .addOperand(Base)
12926     .addOperand(Scale)
12927     .addOperand(Index)
12928     .addDisp(Disp, 8)
12929     .addOperand(Segment)
12930     .addReg(NextAddrReg)
12931     .setMemRefs(MMOBegin, MMOEnd);
12932
12933   // If we branched, emit the PHI to the front of endMBB.
12934   if (offsetMBB) {
12935     BuildMI(*endMBB, endMBB->begin(), DL,
12936             TII->get(X86::PHI), DestReg)
12937       .addReg(OffsetDestReg).addMBB(offsetMBB)
12938       .addReg(OverflowDestReg).addMBB(overflowMBB);
12939   }
12940
12941   // Erase the pseudo instruction
12942   MI->eraseFromParent();
12943
12944   return endMBB;
12945 }
12946
12947 MachineBasicBlock *
12948 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12949                                                  MachineInstr *MI,
12950                                                  MachineBasicBlock *MBB) const {
12951   // Emit code to save XMM registers to the stack. The ABI says that the
12952   // number of registers to save is given in %al, so it's theoretically
12953   // possible to do an indirect jump trick to avoid saving all of them,
12954   // however this code takes a simpler approach and just executes all
12955   // of the stores if %al is non-zero. It's less code, and it's probably
12956   // easier on the hardware branch predictor, and stores aren't all that
12957   // expensive anyway.
12958
12959   // Create the new basic blocks. One block contains all the XMM stores,
12960   // and one block is the final destination regardless of whether any
12961   // stores were performed.
12962   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12963   MachineFunction *F = MBB->getParent();
12964   MachineFunction::iterator MBBIter = MBB;
12965   ++MBBIter;
12966   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12967   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12968   F->insert(MBBIter, XMMSaveMBB);
12969   F->insert(MBBIter, EndMBB);
12970
12971   // Transfer the remainder of MBB and its successor edges to EndMBB.
12972   EndMBB->splice(EndMBB->begin(), MBB,
12973                  llvm::next(MachineBasicBlock::iterator(MI)),
12974                  MBB->end());
12975   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12976
12977   // The original block will now fall through to the XMM save block.
12978   MBB->addSuccessor(XMMSaveMBB);
12979   // The XMMSaveMBB will fall through to the end block.
12980   XMMSaveMBB->addSuccessor(EndMBB);
12981
12982   // Now add the instructions.
12983   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12984   DebugLoc DL = MI->getDebugLoc();
12985
12986   unsigned CountReg = MI->getOperand(0).getReg();
12987   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12988   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12989
12990   if (!Subtarget->isTargetWin64()) {
12991     // If %al is 0, branch around the XMM save block.
12992     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12993     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12994     MBB->addSuccessor(EndMBB);
12995   }
12996
12997   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12998   // In the XMM save block, save all the XMM argument registers.
12999   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13000     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13001     MachineMemOperand *MMO =
13002       F->getMachineMemOperand(
13003           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13004         MachineMemOperand::MOStore,
13005         /*Size=*/16, /*Align=*/16);
13006     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13007       .addFrameIndex(RegSaveFrameIndex)
13008       .addImm(/*Scale=*/1)
13009       .addReg(/*IndexReg=*/0)
13010       .addImm(/*Disp=*/Offset)
13011       .addReg(/*Segment=*/0)
13012       .addReg(MI->getOperand(i).getReg())
13013       .addMemOperand(MMO);
13014   }
13015
13016   MI->eraseFromParent();   // The pseudo instruction is gone now.
13017
13018   return EndMBB;
13019 }
13020
13021 // The EFLAGS operand of SelectItr might be missing a kill marker
13022 // because there were multiple uses of EFLAGS, and ISel didn't know
13023 // which to mark. Figure out whether SelectItr should have had a
13024 // kill marker, and set it if it should. Returns the correct kill
13025 // marker value.
13026 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13027                                      MachineBasicBlock* BB,
13028                                      const TargetRegisterInfo* TRI) {
13029   // Scan forward through BB for a use/def of EFLAGS.
13030   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13031   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13032     const MachineInstr& mi = *miI;
13033     if (mi.readsRegister(X86::EFLAGS))
13034       return false;
13035     if (mi.definesRegister(X86::EFLAGS))
13036       break; // Should have kill-flag - update below.
13037   }
13038
13039   // If we hit the end of the block, check whether EFLAGS is live into a
13040   // successor.
13041   if (miI == BB->end()) {
13042     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13043                                           sEnd = BB->succ_end();
13044          sItr != sEnd; ++sItr) {
13045       MachineBasicBlock* succ = *sItr;
13046       if (succ->isLiveIn(X86::EFLAGS))
13047         return false;
13048     }
13049   }
13050
13051   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13052   // out. SelectMI should have a kill flag on EFLAGS.
13053   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13054   return true;
13055 }
13056
13057 MachineBasicBlock *
13058 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13059                                      MachineBasicBlock *BB) const {
13060   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13061   DebugLoc DL = MI->getDebugLoc();
13062
13063   // To "insert" a SELECT_CC instruction, we actually have to insert the
13064   // diamond control-flow pattern.  The incoming instruction knows the
13065   // destination vreg to set, the condition code register to branch on, the
13066   // true/false values to select between, and a branch opcode to use.
13067   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13068   MachineFunction::iterator It = BB;
13069   ++It;
13070
13071   //  thisMBB:
13072   //  ...
13073   //   TrueVal = ...
13074   //   cmpTY ccX, r1, r2
13075   //   bCC copy1MBB
13076   //   fallthrough --> copy0MBB
13077   MachineBasicBlock *thisMBB = BB;
13078   MachineFunction *F = BB->getParent();
13079   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13080   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13081   F->insert(It, copy0MBB);
13082   F->insert(It, sinkMBB);
13083
13084   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13085   // live into the sink and copy blocks.
13086   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13087   if (!MI->killsRegister(X86::EFLAGS) &&
13088       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13089     copy0MBB->addLiveIn(X86::EFLAGS);
13090     sinkMBB->addLiveIn(X86::EFLAGS);
13091   }
13092
13093   // Transfer the remainder of BB and its successor edges to sinkMBB.
13094   sinkMBB->splice(sinkMBB->begin(), BB,
13095                   llvm::next(MachineBasicBlock::iterator(MI)),
13096                   BB->end());
13097   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13098
13099   // Add the true and fallthrough blocks as its successors.
13100   BB->addSuccessor(copy0MBB);
13101   BB->addSuccessor(sinkMBB);
13102
13103   // Create the conditional branch instruction.
13104   unsigned Opc =
13105     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13106   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13107
13108   //  copy0MBB:
13109   //   %FalseValue = ...
13110   //   # fallthrough to sinkMBB
13111   copy0MBB->addSuccessor(sinkMBB);
13112
13113   //  sinkMBB:
13114   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13115   //  ...
13116   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13117           TII->get(X86::PHI), MI->getOperand(0).getReg())
13118     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13119     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13120
13121   MI->eraseFromParent();   // The pseudo instruction is gone now.
13122   return sinkMBB;
13123 }
13124
13125 MachineBasicBlock *
13126 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13127                                         bool Is64Bit) const {
13128   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13129   DebugLoc DL = MI->getDebugLoc();
13130   MachineFunction *MF = BB->getParent();
13131   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13132
13133   assert(getTargetMachine().Options.EnableSegmentedStacks);
13134
13135   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13136   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13137
13138   // BB:
13139   //  ... [Till the alloca]
13140   // If stacklet is not large enough, jump to mallocMBB
13141   //
13142   // bumpMBB:
13143   //  Allocate by subtracting from RSP
13144   //  Jump to continueMBB
13145   //
13146   // mallocMBB:
13147   //  Allocate by call to runtime
13148   //
13149   // continueMBB:
13150   //  ...
13151   //  [rest of original BB]
13152   //
13153
13154   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13155   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13156   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13157
13158   MachineRegisterInfo &MRI = MF->getRegInfo();
13159   const TargetRegisterClass *AddrRegClass =
13160     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13161
13162   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13163     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13164     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13165     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13166     sizeVReg = MI->getOperand(1).getReg(),
13167     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13168
13169   MachineFunction::iterator MBBIter = BB;
13170   ++MBBIter;
13171
13172   MF->insert(MBBIter, bumpMBB);
13173   MF->insert(MBBIter, mallocMBB);
13174   MF->insert(MBBIter, continueMBB);
13175
13176   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13177                       (MachineBasicBlock::iterator(MI)), BB->end());
13178   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13179
13180   // Add code to the main basic block to check if the stack limit has been hit,
13181   // and if so, jump to mallocMBB otherwise to bumpMBB.
13182   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13183   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13184     .addReg(tmpSPVReg).addReg(sizeVReg);
13185   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13186     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13187     .addReg(SPLimitVReg);
13188   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13189
13190   // bumpMBB simply decreases the stack pointer, since we know the current
13191   // stacklet has enough space.
13192   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13193     .addReg(SPLimitVReg);
13194   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13195     .addReg(SPLimitVReg);
13196   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13197
13198   // Calls into a routine in libgcc to allocate more space from the heap.
13199   const uint32_t *RegMask =
13200     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13201   if (Is64Bit) {
13202     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13203       .addReg(sizeVReg);
13204     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13205       .addExternalSymbol("__morestack_allocate_stack_space")
13206       .addRegMask(RegMask)
13207       .addReg(X86::RDI, RegState::Implicit)
13208       .addReg(X86::RAX, RegState::ImplicitDefine);
13209   } else {
13210     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13211       .addImm(12);
13212     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13213     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13214       .addExternalSymbol("__morestack_allocate_stack_space")
13215       .addRegMask(RegMask)
13216       .addReg(X86::EAX, RegState::ImplicitDefine);
13217   }
13218
13219   if (!Is64Bit)
13220     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13221       .addImm(16);
13222
13223   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13224     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13225   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13226
13227   // Set up the CFG correctly.
13228   BB->addSuccessor(bumpMBB);
13229   BB->addSuccessor(mallocMBB);
13230   mallocMBB->addSuccessor(continueMBB);
13231   bumpMBB->addSuccessor(continueMBB);
13232
13233   // Take care of the PHI nodes.
13234   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13235           MI->getOperand(0).getReg())
13236     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13237     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13238
13239   // Delete the original pseudo instruction.
13240   MI->eraseFromParent();
13241
13242   // And we're done.
13243   return continueMBB;
13244 }
13245
13246 MachineBasicBlock *
13247 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13248                                           MachineBasicBlock *BB) const {
13249   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13250   DebugLoc DL = MI->getDebugLoc();
13251
13252   assert(!Subtarget->isTargetEnvMacho());
13253
13254   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13255   // non-trivial part is impdef of ESP.
13256
13257   if (Subtarget->isTargetWin64()) {
13258     if (Subtarget->isTargetCygMing()) {
13259       // ___chkstk(Mingw64):
13260       // Clobbers R10, R11, RAX and EFLAGS.
13261       // Updates RSP.
13262       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13263         .addExternalSymbol("___chkstk")
13264         .addReg(X86::RAX, RegState::Implicit)
13265         .addReg(X86::RSP, RegState::Implicit)
13266         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13267         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13268         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13269     } else {
13270       // __chkstk(MSVCRT): does not update stack pointer.
13271       // Clobbers R10, R11 and EFLAGS.
13272       // FIXME: RAX(allocated size) might be reused and not killed.
13273       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13274         .addExternalSymbol("__chkstk")
13275         .addReg(X86::RAX, RegState::Implicit)
13276         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13277       // RAX has the offset to subtracted from RSP.
13278       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13279         .addReg(X86::RSP)
13280         .addReg(X86::RAX);
13281     }
13282   } else {
13283     const char *StackProbeSymbol =
13284       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13285
13286     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13287       .addExternalSymbol(StackProbeSymbol)
13288       .addReg(X86::EAX, RegState::Implicit)
13289       .addReg(X86::ESP, RegState::Implicit)
13290       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13291       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13292       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13293   }
13294
13295   MI->eraseFromParent();   // The pseudo instruction is gone now.
13296   return BB;
13297 }
13298
13299 MachineBasicBlock *
13300 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13301                                       MachineBasicBlock *BB) const {
13302   // This is pretty easy.  We're taking the value that we received from
13303   // our load from the relocation, sticking it in either RDI (x86-64)
13304   // or EAX and doing an indirect call.  The return value will then
13305   // be in the normal return register.
13306   const X86InstrInfo *TII
13307     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13308   DebugLoc DL = MI->getDebugLoc();
13309   MachineFunction *F = BB->getParent();
13310
13311   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13312   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13313
13314   // Get a register mask for the lowered call.
13315   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13316   // proper register mask.
13317   const uint32_t *RegMask =
13318     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13319   if (Subtarget->is64Bit()) {
13320     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13321                                       TII->get(X86::MOV64rm), X86::RDI)
13322     .addReg(X86::RIP)
13323     .addImm(0).addReg(0)
13324     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13325                       MI->getOperand(3).getTargetFlags())
13326     .addReg(0);
13327     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13328     addDirectMem(MIB, X86::RDI);
13329     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13330   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13331     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13332                                       TII->get(X86::MOV32rm), X86::EAX)
13333     .addReg(0)
13334     .addImm(0).addReg(0)
13335     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13336                       MI->getOperand(3).getTargetFlags())
13337     .addReg(0);
13338     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13339     addDirectMem(MIB, X86::EAX);
13340     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13341   } else {
13342     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13343                                       TII->get(X86::MOV32rm), X86::EAX)
13344     .addReg(TII->getGlobalBaseReg(F))
13345     .addImm(0).addReg(0)
13346     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13347                       MI->getOperand(3).getTargetFlags())
13348     .addReg(0);
13349     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13350     addDirectMem(MIB, X86::EAX);
13351     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13352   }
13353
13354   MI->eraseFromParent(); // The pseudo instruction is gone now.
13355   return BB;
13356 }
13357
13358 MachineBasicBlock *
13359 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13360                                     MachineBasicBlock *MBB) const {
13361   DebugLoc DL = MI->getDebugLoc();
13362   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13363
13364   MachineFunction *MF = MBB->getParent();
13365   MachineRegisterInfo &MRI = MF->getRegInfo();
13366
13367   const BasicBlock *BB = MBB->getBasicBlock();
13368   MachineFunction::iterator I = MBB;
13369   ++I;
13370
13371   // Memory Reference
13372   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13373   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13374
13375   unsigned DstReg;
13376   unsigned MemOpndSlot = 0;
13377
13378   unsigned CurOp = 0;
13379
13380   DstReg = MI->getOperand(CurOp++).getReg();
13381   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13382   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13383   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13384   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13385
13386   MemOpndSlot = CurOp;
13387
13388   MVT PVT = getPointerTy();
13389   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13390          "Invalid Pointer Size!");
13391
13392   // For v = setjmp(buf), we generate
13393   //
13394   // thisMBB:
13395   //  buf[LabelOffset] = restoreMBB
13396   //  SjLjSetup restoreMBB
13397   //
13398   // mainMBB:
13399   //  v_main = 0
13400   //
13401   // sinkMBB:
13402   //  v = phi(main, restore)
13403   //
13404   // restoreMBB:
13405   //  v_restore = 1
13406
13407   MachineBasicBlock *thisMBB = MBB;
13408   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13409   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13410   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13411   MF->insert(I, mainMBB);
13412   MF->insert(I, sinkMBB);
13413   MF->push_back(restoreMBB);
13414
13415   MachineInstrBuilder MIB;
13416
13417   // Transfer the remainder of BB and its successor edges to sinkMBB.
13418   sinkMBB->splice(sinkMBB->begin(), MBB,
13419                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13420   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13421
13422   // thisMBB:
13423   unsigned PtrStoreOpc = 0;
13424   unsigned LabelReg = 0;
13425   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13426   Reloc::Model RM = getTargetMachine().getRelocationModel();
13427   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13428                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13429
13430   // Prepare IP either in reg or imm.
13431   if (!UseImmLabel) {
13432     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13433     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13434     LabelReg = MRI.createVirtualRegister(PtrRC);
13435     if (Subtarget->is64Bit()) {
13436       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13437               .addReg(X86::RIP)
13438               .addImm(0)
13439               .addReg(0)
13440               .addMBB(restoreMBB)
13441               .addReg(0);
13442     } else {
13443       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13444       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13445               .addReg(XII->getGlobalBaseReg(MF))
13446               .addImm(0)
13447               .addReg(0)
13448               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13449               .addReg(0);
13450     }
13451   } else
13452     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13453   // Store IP
13454   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13455   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13456     if (i == X86::AddrDisp)
13457       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13458     else
13459       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13460   }
13461   if (!UseImmLabel)
13462     MIB.addReg(LabelReg);
13463   else
13464     MIB.addMBB(restoreMBB);
13465   MIB.setMemRefs(MMOBegin, MMOEnd);
13466   // Setup
13467   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13468           .addMBB(restoreMBB);
13469   MIB.addRegMask(RegInfo->getNoPreservedMask());
13470   thisMBB->addSuccessor(mainMBB);
13471   thisMBB->addSuccessor(restoreMBB);
13472
13473   // mainMBB:
13474   //  EAX = 0
13475   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13476   mainMBB->addSuccessor(sinkMBB);
13477
13478   // sinkMBB:
13479   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13480           TII->get(X86::PHI), DstReg)
13481     .addReg(mainDstReg).addMBB(mainMBB)
13482     .addReg(restoreDstReg).addMBB(restoreMBB);
13483
13484   // restoreMBB:
13485   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13486   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13487   restoreMBB->addSuccessor(sinkMBB);
13488
13489   MI->eraseFromParent();
13490   return sinkMBB;
13491 }
13492
13493 MachineBasicBlock *
13494 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13495                                      MachineBasicBlock *MBB) const {
13496   DebugLoc DL = MI->getDebugLoc();
13497   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13498
13499   MachineFunction *MF = MBB->getParent();
13500   MachineRegisterInfo &MRI = MF->getRegInfo();
13501
13502   // Memory Reference
13503   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13504   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13505
13506   MVT PVT = getPointerTy();
13507   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13508          "Invalid Pointer Size!");
13509
13510   const TargetRegisterClass *RC =
13511     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13512   unsigned Tmp = MRI.createVirtualRegister(RC);
13513   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13514   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13515   unsigned SP = RegInfo->getStackRegister();
13516
13517   MachineInstrBuilder MIB;
13518
13519   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13520   const int64_t SPOffset = 2 * PVT.getStoreSize();
13521
13522   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13523   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13524
13525   // Reload FP
13526   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13527   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13528     MIB.addOperand(MI->getOperand(i));
13529   MIB.setMemRefs(MMOBegin, MMOEnd);
13530   // Reload IP
13531   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13532   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13533     if (i == X86::AddrDisp)
13534       MIB.addDisp(MI->getOperand(i), LabelOffset);
13535     else
13536       MIB.addOperand(MI->getOperand(i));
13537   }
13538   MIB.setMemRefs(MMOBegin, MMOEnd);
13539   // Reload SP
13540   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13541   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13542     if (i == X86::AddrDisp)
13543       MIB.addDisp(MI->getOperand(i), SPOffset);
13544     else
13545       MIB.addOperand(MI->getOperand(i));
13546   }
13547   MIB.setMemRefs(MMOBegin, MMOEnd);
13548   // Jump
13549   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13550
13551   MI->eraseFromParent();
13552   return MBB;
13553 }
13554
13555 MachineBasicBlock *
13556 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13557                                                MachineBasicBlock *BB) const {
13558   switch (MI->getOpcode()) {
13559   default: llvm_unreachable("Unexpected instr type to insert");
13560   case X86::TAILJMPd64:
13561   case X86::TAILJMPr64:
13562   case X86::TAILJMPm64:
13563     llvm_unreachable("TAILJMP64 would not be touched here.");
13564   case X86::TCRETURNdi64:
13565   case X86::TCRETURNri64:
13566   case X86::TCRETURNmi64:
13567     return BB;
13568   case X86::WIN_ALLOCA:
13569     return EmitLoweredWinAlloca(MI, BB);
13570   case X86::SEG_ALLOCA_32:
13571     return EmitLoweredSegAlloca(MI, BB, false);
13572   case X86::SEG_ALLOCA_64:
13573     return EmitLoweredSegAlloca(MI, BB, true);
13574   case X86::TLSCall_32:
13575   case X86::TLSCall_64:
13576     return EmitLoweredTLSCall(MI, BB);
13577   case X86::CMOV_GR8:
13578   case X86::CMOV_FR32:
13579   case X86::CMOV_FR64:
13580   case X86::CMOV_V4F32:
13581   case X86::CMOV_V2F64:
13582   case X86::CMOV_V2I64:
13583   case X86::CMOV_V8F32:
13584   case X86::CMOV_V4F64:
13585   case X86::CMOV_V4I64:
13586   case X86::CMOV_GR16:
13587   case X86::CMOV_GR32:
13588   case X86::CMOV_RFP32:
13589   case X86::CMOV_RFP64:
13590   case X86::CMOV_RFP80:
13591     return EmitLoweredSelect(MI, BB);
13592
13593   case X86::FP32_TO_INT16_IN_MEM:
13594   case X86::FP32_TO_INT32_IN_MEM:
13595   case X86::FP32_TO_INT64_IN_MEM:
13596   case X86::FP64_TO_INT16_IN_MEM:
13597   case X86::FP64_TO_INT32_IN_MEM:
13598   case X86::FP64_TO_INT64_IN_MEM:
13599   case X86::FP80_TO_INT16_IN_MEM:
13600   case X86::FP80_TO_INT32_IN_MEM:
13601   case X86::FP80_TO_INT64_IN_MEM: {
13602     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13603     DebugLoc DL = MI->getDebugLoc();
13604
13605     // Change the floating point control register to use "round towards zero"
13606     // mode when truncating to an integer value.
13607     MachineFunction *F = BB->getParent();
13608     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13609     addFrameReference(BuildMI(*BB, MI, DL,
13610                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13611
13612     // Load the old value of the high byte of the control word...
13613     unsigned OldCW =
13614       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13615     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13616                       CWFrameIdx);
13617
13618     // Set the high part to be round to zero...
13619     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13620       .addImm(0xC7F);
13621
13622     // Reload the modified control word now...
13623     addFrameReference(BuildMI(*BB, MI, DL,
13624                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13625
13626     // Restore the memory image of control word to original value
13627     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13628       .addReg(OldCW);
13629
13630     // Get the X86 opcode to use.
13631     unsigned Opc;
13632     switch (MI->getOpcode()) {
13633     default: llvm_unreachable("illegal opcode!");
13634     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13635     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13636     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13637     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13638     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13639     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13640     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13641     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13642     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13643     }
13644
13645     X86AddressMode AM;
13646     MachineOperand &Op = MI->getOperand(0);
13647     if (Op.isReg()) {
13648       AM.BaseType = X86AddressMode::RegBase;
13649       AM.Base.Reg = Op.getReg();
13650     } else {
13651       AM.BaseType = X86AddressMode::FrameIndexBase;
13652       AM.Base.FrameIndex = Op.getIndex();
13653     }
13654     Op = MI->getOperand(1);
13655     if (Op.isImm())
13656       AM.Scale = Op.getImm();
13657     Op = MI->getOperand(2);
13658     if (Op.isImm())
13659       AM.IndexReg = Op.getImm();
13660     Op = MI->getOperand(3);
13661     if (Op.isGlobal()) {
13662       AM.GV = Op.getGlobal();
13663     } else {
13664       AM.Disp = Op.getImm();
13665     }
13666     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13667                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13668
13669     // Reload the original control word now.
13670     addFrameReference(BuildMI(*BB, MI, DL,
13671                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13672
13673     MI->eraseFromParent();   // The pseudo instruction is gone now.
13674     return BB;
13675   }
13676     // String/text processing lowering.
13677   case X86::PCMPISTRM128REG:
13678   case X86::VPCMPISTRM128REG:
13679   case X86::PCMPISTRM128MEM:
13680   case X86::VPCMPISTRM128MEM:
13681   case X86::PCMPESTRM128REG:
13682   case X86::VPCMPESTRM128REG:
13683   case X86::PCMPESTRM128MEM:
13684   case X86::VPCMPESTRM128MEM: {
13685     unsigned NumArgs;
13686     bool MemArg;
13687     switch (MI->getOpcode()) {
13688     default: llvm_unreachable("illegal opcode!");
13689     case X86::PCMPISTRM128REG:
13690     case X86::VPCMPISTRM128REG:
13691       NumArgs = 3; MemArg = false; break;
13692     case X86::PCMPISTRM128MEM:
13693     case X86::VPCMPISTRM128MEM:
13694       NumArgs = 3; MemArg = true; break;
13695     case X86::PCMPESTRM128REG:
13696     case X86::VPCMPESTRM128REG:
13697       NumArgs = 5; MemArg = false; break;
13698     case X86::PCMPESTRM128MEM:
13699     case X86::VPCMPESTRM128MEM:
13700       NumArgs = 5; MemArg = true; break;
13701     }
13702     return EmitPCMP(MI, BB, NumArgs, MemArg);
13703   }
13704
13705     // Thread synchronization.
13706   case X86::MONITOR:
13707     return EmitMonitor(MI, BB);
13708
13709     // Atomic Lowering.
13710   case X86::ATOMAND8:
13711   case X86::ATOMAND16:
13712   case X86::ATOMAND32:
13713   case X86::ATOMAND64:
13714     // Fall through
13715   case X86::ATOMOR8:
13716   case X86::ATOMOR16:
13717   case X86::ATOMOR32:
13718   case X86::ATOMOR64:
13719     // Fall through
13720   case X86::ATOMXOR16:
13721   case X86::ATOMXOR8:
13722   case X86::ATOMXOR32:
13723   case X86::ATOMXOR64:
13724     // Fall through
13725   case X86::ATOMNAND8:
13726   case X86::ATOMNAND16:
13727   case X86::ATOMNAND32:
13728   case X86::ATOMNAND64:
13729     // Fall through
13730   case X86::ATOMMAX8:
13731   case X86::ATOMMAX16:
13732   case X86::ATOMMAX32:
13733   case X86::ATOMMAX64:
13734     // Fall through
13735   case X86::ATOMMIN8:
13736   case X86::ATOMMIN16:
13737   case X86::ATOMMIN32:
13738   case X86::ATOMMIN64:
13739     // Fall through
13740   case X86::ATOMUMAX8:
13741   case X86::ATOMUMAX16:
13742   case X86::ATOMUMAX32:
13743   case X86::ATOMUMAX64:
13744     // Fall through
13745   case X86::ATOMUMIN8:
13746   case X86::ATOMUMIN16:
13747   case X86::ATOMUMIN32:
13748   case X86::ATOMUMIN64:
13749     return EmitAtomicLoadArith(MI, BB);
13750
13751   // This group does 64-bit operations on a 32-bit host.
13752   case X86::ATOMAND6432:
13753   case X86::ATOMOR6432:
13754   case X86::ATOMXOR6432:
13755   case X86::ATOMNAND6432:
13756   case X86::ATOMADD6432:
13757   case X86::ATOMSUB6432:
13758   case X86::ATOMMAX6432:
13759   case X86::ATOMMIN6432:
13760   case X86::ATOMUMAX6432:
13761   case X86::ATOMUMIN6432:
13762   case X86::ATOMSWAP6432:
13763     return EmitAtomicLoadArith6432(MI, BB);
13764
13765   case X86::VASTART_SAVE_XMM_REGS:
13766     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13767
13768   case X86::VAARG_64:
13769     return EmitVAARG64WithCustomInserter(MI, BB);
13770
13771   case X86::EH_SjLj_SetJmp32:
13772   case X86::EH_SjLj_SetJmp64:
13773     return emitEHSjLjSetJmp(MI, BB);
13774
13775   case X86::EH_SjLj_LongJmp32:
13776   case X86::EH_SjLj_LongJmp64:
13777     return emitEHSjLjLongJmp(MI, BB);
13778   }
13779 }
13780
13781 //===----------------------------------------------------------------------===//
13782 //                           X86 Optimization Hooks
13783 //===----------------------------------------------------------------------===//
13784
13785 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13786                                                        APInt &KnownZero,
13787                                                        APInt &KnownOne,
13788                                                        const SelectionDAG &DAG,
13789                                                        unsigned Depth) const {
13790   unsigned BitWidth = KnownZero.getBitWidth();
13791   unsigned Opc = Op.getOpcode();
13792   assert((Opc >= ISD::BUILTIN_OP_END ||
13793           Opc == ISD::INTRINSIC_WO_CHAIN ||
13794           Opc == ISD::INTRINSIC_W_CHAIN ||
13795           Opc == ISD::INTRINSIC_VOID) &&
13796          "Should use MaskedValueIsZero if you don't know whether Op"
13797          " is a target node!");
13798
13799   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13800   switch (Opc) {
13801   default: break;
13802   case X86ISD::ADD:
13803   case X86ISD::SUB:
13804   case X86ISD::ADC:
13805   case X86ISD::SBB:
13806   case X86ISD::SMUL:
13807   case X86ISD::UMUL:
13808   case X86ISD::INC:
13809   case X86ISD::DEC:
13810   case X86ISD::OR:
13811   case X86ISD::XOR:
13812   case X86ISD::AND:
13813     // These nodes' second result is a boolean.
13814     if (Op.getResNo() == 0)
13815       break;
13816     // Fallthrough
13817   case X86ISD::SETCC:
13818     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13819     break;
13820   case ISD::INTRINSIC_WO_CHAIN: {
13821     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13822     unsigned NumLoBits = 0;
13823     switch (IntId) {
13824     default: break;
13825     case Intrinsic::x86_sse_movmsk_ps:
13826     case Intrinsic::x86_avx_movmsk_ps_256:
13827     case Intrinsic::x86_sse2_movmsk_pd:
13828     case Intrinsic::x86_avx_movmsk_pd_256:
13829     case Intrinsic::x86_mmx_pmovmskb:
13830     case Intrinsic::x86_sse2_pmovmskb_128:
13831     case Intrinsic::x86_avx2_pmovmskb: {
13832       // High bits of movmskp{s|d}, pmovmskb are known zero.
13833       switch (IntId) {
13834         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13835         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13836         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13837         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13838         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13839         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13840         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13841         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13842       }
13843       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13844       break;
13845     }
13846     }
13847     break;
13848   }
13849   }
13850 }
13851
13852 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13853                                                          unsigned Depth) const {
13854   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13855   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13856     return Op.getValueType().getScalarType().getSizeInBits();
13857
13858   // Fallback case.
13859   return 1;
13860 }
13861
13862 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13863 /// node is a GlobalAddress + offset.
13864 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13865                                        const GlobalValue* &GA,
13866                                        int64_t &Offset) const {
13867   if (N->getOpcode() == X86ISD::Wrapper) {
13868     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13869       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13870       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13871       return true;
13872     }
13873   }
13874   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13875 }
13876
13877 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13878 /// same as extracting the high 128-bit part of 256-bit vector and then
13879 /// inserting the result into the low part of a new 256-bit vector
13880 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13881   EVT VT = SVOp->getValueType(0);
13882   unsigned NumElems = VT.getVectorNumElements();
13883
13884   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13885   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13886     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13887         SVOp->getMaskElt(j) >= 0)
13888       return false;
13889
13890   return true;
13891 }
13892
13893 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13894 /// same as extracting the low 128-bit part of 256-bit vector and then
13895 /// inserting the result into the high part of a new 256-bit vector
13896 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13897   EVT VT = SVOp->getValueType(0);
13898   unsigned NumElems = VT.getVectorNumElements();
13899
13900   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13901   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13902     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13903         SVOp->getMaskElt(j) >= 0)
13904       return false;
13905
13906   return true;
13907 }
13908
13909 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13910 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13911                                         TargetLowering::DAGCombinerInfo &DCI,
13912                                         const X86Subtarget* Subtarget) {
13913   DebugLoc dl = N->getDebugLoc();
13914   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13915   SDValue V1 = SVOp->getOperand(0);
13916   SDValue V2 = SVOp->getOperand(1);
13917   EVT VT = SVOp->getValueType(0);
13918   unsigned NumElems = VT.getVectorNumElements();
13919
13920   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13921       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13922     //
13923     //                   0,0,0,...
13924     //                      |
13925     //    V      UNDEF    BUILD_VECTOR    UNDEF
13926     //     \      /           \           /
13927     //  CONCAT_VECTOR         CONCAT_VECTOR
13928     //         \                  /
13929     //          \                /
13930     //          RESULT: V + zero extended
13931     //
13932     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13933         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13934         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13935       return SDValue();
13936
13937     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13938       return SDValue();
13939
13940     // To match the shuffle mask, the first half of the mask should
13941     // be exactly the first vector, and all the rest a splat with the
13942     // first element of the second one.
13943     for (unsigned i = 0; i != NumElems/2; ++i)
13944       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13945           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13946         return SDValue();
13947
13948     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13949     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13950       if (Ld->hasNUsesOfValue(1, 0)) {
13951         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13952         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13953         SDValue ResNode =
13954           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13955                                   Ld->getMemoryVT(),
13956                                   Ld->getPointerInfo(),
13957                                   Ld->getAlignment(),
13958                                   false/*isVolatile*/, true/*ReadMem*/,
13959                                   false/*WriteMem*/);
13960         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13961       }
13962     }
13963
13964     // Emit a zeroed vector and insert the desired subvector on its
13965     // first half.
13966     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13967     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13968     return DCI.CombineTo(N, InsV);
13969   }
13970
13971   //===--------------------------------------------------------------------===//
13972   // Combine some shuffles into subvector extracts and inserts:
13973   //
13974
13975   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13976   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13977     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13978     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13979     return DCI.CombineTo(N, InsV);
13980   }
13981
13982   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13983   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13984     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13985     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13986     return DCI.CombineTo(N, InsV);
13987   }
13988
13989   return SDValue();
13990 }
13991
13992 /// PerformShuffleCombine - Performs several different shuffle combines.
13993 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13994                                      TargetLowering::DAGCombinerInfo &DCI,
13995                                      const X86Subtarget *Subtarget) {
13996   DebugLoc dl = N->getDebugLoc();
13997   EVT VT = N->getValueType(0);
13998
13999   // Don't create instructions with illegal types after legalize types has run.
14000   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14001   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14002     return SDValue();
14003
14004   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14005   if (Subtarget->hasAVX() && VT.is256BitVector() &&
14006       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14007     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14008
14009   // Only handle 128 wide vector from here on.
14010   if (!VT.is128BitVector())
14011     return SDValue();
14012
14013   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14014   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14015   // consecutive, non-overlapping, and in the right order.
14016   SmallVector<SDValue, 16> Elts;
14017   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14018     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14019
14020   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14021 }
14022
14023
14024 /// PerformTruncateCombine - Converts truncate operation to
14025 /// a sequence of vector shuffle operations.
14026 /// It is possible when we truncate 256-bit vector to 128-bit vector
14027 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14028                                       TargetLowering::DAGCombinerInfo &DCI,
14029                                       const X86Subtarget *Subtarget)  {
14030   if (!DCI.isBeforeLegalizeOps())
14031     return SDValue();
14032
14033   if (!Subtarget->hasAVX())
14034     return SDValue();
14035
14036   EVT VT = N->getValueType(0);
14037   SDValue Op = N->getOperand(0);
14038   EVT OpVT = Op.getValueType();
14039   DebugLoc dl = N->getDebugLoc();
14040
14041   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14042
14043     if (Subtarget->hasAVX2()) {
14044       // AVX2: v4i64 -> v4i32
14045
14046       // VPERMD
14047       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14048
14049       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14050       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14051                                 ShufMask);
14052
14053       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14054                          DAG.getIntPtrConstant(0));
14055     }
14056
14057     // AVX: v4i64 -> v4i32
14058     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14059                                DAG.getIntPtrConstant(0));
14060
14061     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14062                                DAG.getIntPtrConstant(2));
14063
14064     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14065     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14066
14067     // PSHUFD
14068     static const int ShufMask1[] = {0, 2, 0, 0};
14069
14070     SDValue Undef = DAG.getUNDEF(VT);
14071     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14072     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14073
14074     // MOVLHPS
14075     static const int ShufMask2[] = {0, 1, 4, 5};
14076
14077     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14078   }
14079
14080   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14081
14082     if (Subtarget->hasAVX2()) {
14083       // AVX2: v8i32 -> v8i16
14084
14085       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14086
14087       // PSHUFB
14088       SmallVector<SDValue,32> pshufbMask;
14089       for (unsigned i = 0; i < 2; ++i) {
14090         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14091         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14092         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14093         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14094         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14095         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14096         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14097         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14098         for (unsigned j = 0; j < 8; ++j)
14099           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14100       }
14101       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14102                                &pshufbMask[0], 32);
14103       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14104
14105       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14106
14107       static const int ShufMask[] = {0,  2,  -1,  -1};
14108       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14109                                 &ShufMask[0]);
14110
14111       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14112                        DAG.getIntPtrConstant(0));
14113
14114       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14115     }
14116
14117     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14118                                DAG.getIntPtrConstant(0));
14119
14120     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14121                                DAG.getIntPtrConstant(4));
14122
14123     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14124     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14125
14126     // PSHUFB
14127     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14128                                    -1, -1, -1, -1, -1, -1, -1, -1};
14129
14130     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14131     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14132     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14133
14134     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14135     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14136
14137     // MOVLHPS
14138     static const int ShufMask2[] = {0, 1, 4, 5};
14139
14140     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14141     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14142   }
14143
14144   return SDValue();
14145 }
14146
14147 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14148 /// specific shuffle of a load can be folded into a single element load.
14149 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14150 /// shuffles have been customed lowered so we need to handle those here.
14151 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14152                                          TargetLowering::DAGCombinerInfo &DCI) {
14153   if (DCI.isBeforeLegalizeOps())
14154     return SDValue();
14155
14156   SDValue InVec = N->getOperand(0);
14157   SDValue EltNo = N->getOperand(1);
14158
14159   if (!isa<ConstantSDNode>(EltNo))
14160     return SDValue();
14161
14162   EVT VT = InVec.getValueType();
14163
14164   bool HasShuffleIntoBitcast = false;
14165   if (InVec.getOpcode() == ISD::BITCAST) {
14166     // Don't duplicate a load with other uses.
14167     if (!InVec.hasOneUse())
14168       return SDValue();
14169     EVT BCVT = InVec.getOperand(0).getValueType();
14170     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14171       return SDValue();
14172     InVec = InVec.getOperand(0);
14173     HasShuffleIntoBitcast = true;
14174   }
14175
14176   if (!isTargetShuffle(InVec.getOpcode()))
14177     return SDValue();
14178
14179   // Don't duplicate a load with other uses.
14180   if (!InVec.hasOneUse())
14181     return SDValue();
14182
14183   SmallVector<int, 16> ShuffleMask;
14184   bool UnaryShuffle;
14185   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14186                             UnaryShuffle))
14187     return SDValue();
14188
14189   // Select the input vector, guarding against out of range extract vector.
14190   unsigned NumElems = VT.getVectorNumElements();
14191   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14192   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14193   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14194                                          : InVec.getOperand(1);
14195
14196   // If inputs to shuffle are the same for both ops, then allow 2 uses
14197   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14198
14199   if (LdNode.getOpcode() == ISD::BITCAST) {
14200     // Don't duplicate a load with other uses.
14201     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14202       return SDValue();
14203
14204     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14205     LdNode = LdNode.getOperand(0);
14206   }
14207
14208   if (!ISD::isNormalLoad(LdNode.getNode()))
14209     return SDValue();
14210
14211   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14212
14213   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14214     return SDValue();
14215
14216   if (HasShuffleIntoBitcast) {
14217     // If there's a bitcast before the shuffle, check if the load type and
14218     // alignment is valid.
14219     unsigned Align = LN0->getAlignment();
14220     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14221     unsigned NewAlign = TLI.getDataLayout()->
14222       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14223
14224     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14225       return SDValue();
14226   }
14227
14228   // All checks match so transform back to vector_shuffle so that DAG combiner
14229   // can finish the job
14230   DebugLoc dl = N->getDebugLoc();
14231
14232   // Create shuffle node taking into account the case that its a unary shuffle
14233   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14234   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14235                                  InVec.getOperand(0), Shuffle,
14236                                  &ShuffleMask[0]);
14237   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14238   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14239                      EltNo);
14240 }
14241
14242 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14243 /// generation and convert it from being a bunch of shuffles and extracts
14244 /// to a simple store and scalar loads to extract the elements.
14245 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14246                                          TargetLowering::DAGCombinerInfo &DCI) {
14247   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14248   if (NewOp.getNode())
14249     return NewOp;
14250
14251   SDValue InputVector = N->getOperand(0);
14252
14253   // Only operate on vectors of 4 elements, where the alternative shuffling
14254   // gets to be more expensive.
14255   if (InputVector.getValueType() != MVT::v4i32)
14256     return SDValue();
14257
14258   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14259   // single use which is a sign-extend or zero-extend, and all elements are
14260   // used.
14261   SmallVector<SDNode *, 4> Uses;
14262   unsigned ExtractedElements = 0;
14263   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14264        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14265     if (UI.getUse().getResNo() != InputVector.getResNo())
14266       return SDValue();
14267
14268     SDNode *Extract = *UI;
14269     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14270       return SDValue();
14271
14272     if (Extract->getValueType(0) != MVT::i32)
14273       return SDValue();
14274     if (!Extract->hasOneUse())
14275       return SDValue();
14276     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14277         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14278       return SDValue();
14279     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14280       return SDValue();
14281
14282     // Record which element was extracted.
14283     ExtractedElements |=
14284       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14285
14286     Uses.push_back(Extract);
14287   }
14288
14289   // If not all the elements were used, this may not be worthwhile.
14290   if (ExtractedElements != 15)
14291     return SDValue();
14292
14293   // Ok, we've now decided to do the transformation.
14294   DebugLoc dl = InputVector.getDebugLoc();
14295
14296   // Store the value to a temporary stack slot.
14297   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14298   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14299                             MachinePointerInfo(), false, false, 0);
14300
14301   // Replace each use (extract) with a load of the appropriate element.
14302   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14303        UE = Uses.end(); UI != UE; ++UI) {
14304     SDNode *Extract = *UI;
14305
14306     // cOMpute the element's address.
14307     SDValue Idx = Extract->getOperand(1);
14308     unsigned EltSize =
14309         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14310     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14311     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14313
14314     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14315                                      StackPtr, OffsetVal);
14316
14317     // Load the scalar.
14318     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14319                                      ScalarAddr, MachinePointerInfo(),
14320                                      false, false, false, 0);
14321
14322     // Replace the exact with the load.
14323     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14324   }
14325
14326   // The replacement was made in place; don't return anything.
14327   return SDValue();
14328 }
14329
14330 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14331 /// nodes.
14332 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14333                                     TargetLowering::DAGCombinerInfo &DCI,
14334                                     const X86Subtarget *Subtarget) {
14335   DebugLoc DL = N->getDebugLoc();
14336   SDValue Cond = N->getOperand(0);
14337   // Get the LHS/RHS of the select.
14338   SDValue LHS = N->getOperand(1);
14339   SDValue RHS = N->getOperand(2);
14340   EVT VT = LHS.getValueType();
14341
14342   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14343   // instructions match the semantics of the common C idiom x<y?x:y but not
14344   // x<=y?x:y, because of how they handle negative zero (which can be
14345   // ignored in unsafe-math mode).
14346   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14347       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14348       (Subtarget->hasSSE2() ||
14349        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14350     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14351
14352     unsigned Opcode = 0;
14353     // Check for x CC y ? x : y.
14354     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14355         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14356       switch (CC) {
14357       default: break;
14358       case ISD::SETULT:
14359         // Converting this to a min would handle NaNs incorrectly, and swapping
14360         // the operands would cause it to handle comparisons between positive
14361         // and negative zero incorrectly.
14362         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14363           if (!DAG.getTarget().Options.UnsafeFPMath &&
14364               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14365             break;
14366           std::swap(LHS, RHS);
14367         }
14368         Opcode = X86ISD::FMIN;
14369         break;
14370       case ISD::SETOLE:
14371         // Converting this to a min would handle comparisons between positive
14372         // and negative zero incorrectly.
14373         if (!DAG.getTarget().Options.UnsafeFPMath &&
14374             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14375           break;
14376         Opcode = X86ISD::FMIN;
14377         break;
14378       case ISD::SETULE:
14379         // Converting this to a min would handle both negative zeros and NaNs
14380         // incorrectly, but we can swap the operands to fix both.
14381         std::swap(LHS, RHS);
14382       case ISD::SETOLT:
14383       case ISD::SETLT:
14384       case ISD::SETLE:
14385         Opcode = X86ISD::FMIN;
14386         break;
14387
14388       case ISD::SETOGE:
14389         // Converting this to a max would handle comparisons between positive
14390         // and negative zero incorrectly.
14391         if (!DAG.getTarget().Options.UnsafeFPMath &&
14392             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14393           break;
14394         Opcode = X86ISD::FMAX;
14395         break;
14396       case ISD::SETUGT:
14397         // Converting this to a max would handle NaNs incorrectly, and swapping
14398         // the operands would cause it to handle comparisons between positive
14399         // and negative zero incorrectly.
14400         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14401           if (!DAG.getTarget().Options.UnsafeFPMath &&
14402               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14403             break;
14404           std::swap(LHS, RHS);
14405         }
14406         Opcode = X86ISD::FMAX;
14407         break;
14408       case ISD::SETUGE:
14409         // Converting this to a max would handle both negative zeros and NaNs
14410         // incorrectly, but we can swap the operands to fix both.
14411         std::swap(LHS, RHS);
14412       case ISD::SETOGT:
14413       case ISD::SETGT:
14414       case ISD::SETGE:
14415         Opcode = X86ISD::FMAX;
14416         break;
14417       }
14418     // Check for x CC y ? y : x -- a min/max with reversed arms.
14419     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14420                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14421       switch (CC) {
14422       default: break;
14423       case ISD::SETOGE:
14424         // Converting this to a min would handle comparisons between positive
14425         // and negative zero incorrectly, and swapping the operands would
14426         // cause it to handle NaNs incorrectly.
14427         if (!DAG.getTarget().Options.UnsafeFPMath &&
14428             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14429           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14430             break;
14431           std::swap(LHS, RHS);
14432         }
14433         Opcode = X86ISD::FMIN;
14434         break;
14435       case ISD::SETUGT:
14436         // Converting this to a min would handle NaNs incorrectly.
14437         if (!DAG.getTarget().Options.UnsafeFPMath &&
14438             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14439           break;
14440         Opcode = X86ISD::FMIN;
14441         break;
14442       case ISD::SETUGE:
14443         // Converting this to a min would handle both negative zeros and NaNs
14444         // incorrectly, but we can swap the operands to fix both.
14445         std::swap(LHS, RHS);
14446       case ISD::SETOGT:
14447       case ISD::SETGT:
14448       case ISD::SETGE:
14449         Opcode = X86ISD::FMIN;
14450         break;
14451
14452       case ISD::SETULT:
14453         // Converting this to a max would handle NaNs incorrectly.
14454         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14455           break;
14456         Opcode = X86ISD::FMAX;
14457         break;
14458       case ISD::SETOLE:
14459         // Converting this to a max would handle comparisons between positive
14460         // and negative zero incorrectly, and swapping the operands would
14461         // cause it to handle NaNs incorrectly.
14462         if (!DAG.getTarget().Options.UnsafeFPMath &&
14463             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14464           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14465             break;
14466           std::swap(LHS, RHS);
14467         }
14468         Opcode = X86ISD::FMAX;
14469         break;
14470       case ISD::SETULE:
14471         // Converting this to a max would handle both negative zeros and NaNs
14472         // incorrectly, but we can swap the operands to fix both.
14473         std::swap(LHS, RHS);
14474       case ISD::SETOLT:
14475       case ISD::SETLT:
14476       case ISD::SETLE:
14477         Opcode = X86ISD::FMAX;
14478         break;
14479       }
14480     }
14481
14482     if (Opcode)
14483       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14484   }
14485
14486   // If this is a select between two integer constants, try to do some
14487   // optimizations.
14488   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14489     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14490       // Don't do this for crazy integer types.
14491       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14492         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14493         // so that TrueC (the true value) is larger than FalseC.
14494         bool NeedsCondInvert = false;
14495
14496         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14497             // Efficiently invertible.
14498             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14499              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14500               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14501           NeedsCondInvert = true;
14502           std::swap(TrueC, FalseC);
14503         }
14504
14505         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14506         if (FalseC->getAPIntValue() == 0 &&
14507             TrueC->getAPIntValue().isPowerOf2()) {
14508           if (NeedsCondInvert) // Invert the condition if needed.
14509             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14510                                DAG.getConstant(1, Cond.getValueType()));
14511
14512           // Zero extend the condition if needed.
14513           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14514
14515           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14516           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14517                              DAG.getConstant(ShAmt, MVT::i8));
14518         }
14519
14520         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14521         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14522           if (NeedsCondInvert) // Invert the condition if needed.
14523             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14524                                DAG.getConstant(1, Cond.getValueType()));
14525
14526           // Zero extend the condition if needed.
14527           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14528                              FalseC->getValueType(0), Cond);
14529           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14530                              SDValue(FalseC, 0));
14531         }
14532
14533         // Optimize cases that will turn into an LEA instruction.  This requires
14534         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14535         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14536           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14537           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14538
14539           bool isFastMultiplier = false;
14540           if (Diff < 10) {
14541             switch ((unsigned char)Diff) {
14542               default: break;
14543               case 1:  // result = add base, cond
14544               case 2:  // result = lea base(    , cond*2)
14545               case 3:  // result = lea base(cond, cond*2)
14546               case 4:  // result = lea base(    , cond*4)
14547               case 5:  // result = lea base(cond, cond*4)
14548               case 8:  // result = lea base(    , cond*8)
14549               case 9:  // result = lea base(cond, cond*8)
14550                 isFastMultiplier = true;
14551                 break;
14552             }
14553           }
14554
14555           if (isFastMultiplier) {
14556             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14557             if (NeedsCondInvert) // Invert the condition if needed.
14558               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14559                                  DAG.getConstant(1, Cond.getValueType()));
14560
14561             // Zero extend the condition if needed.
14562             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14563                                Cond);
14564             // Scale the condition by the difference.
14565             if (Diff != 1)
14566               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14567                                  DAG.getConstant(Diff, Cond.getValueType()));
14568
14569             // Add the base if non-zero.
14570             if (FalseC->getAPIntValue() != 0)
14571               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14572                                  SDValue(FalseC, 0));
14573             return Cond;
14574           }
14575         }
14576       }
14577   }
14578
14579   // Canonicalize max and min:
14580   // (x > y) ? x : y -> (x >= y) ? x : y
14581   // (x < y) ? x : y -> (x <= y) ? x : y
14582   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14583   // the need for an extra compare
14584   // against zero. e.g.
14585   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14586   // subl   %esi, %edi
14587   // testl  %edi, %edi
14588   // movl   $0, %eax
14589   // cmovgl %edi, %eax
14590   // =>
14591   // xorl   %eax, %eax
14592   // subl   %esi, $edi
14593   // cmovsl %eax, %edi
14594   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14595       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14596       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14597     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14598     switch (CC) {
14599     default: break;
14600     case ISD::SETLT:
14601     case ISD::SETGT: {
14602       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14603       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14604                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14605       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14606     }
14607     }
14608   }
14609
14610   // If we know that this node is legal then we know that it is going to be
14611   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14612   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14613   // to simplify previous instructions.
14614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14615   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14616       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14617     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14618
14619     // Don't optimize vector selects that map to mask-registers.
14620     if (BitWidth == 1)
14621       return SDValue();
14622
14623     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14624     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14625
14626     APInt KnownZero, KnownOne;
14627     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14628                                           DCI.isBeforeLegalizeOps());
14629     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14630         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14631       DCI.CommitTargetLoweringOpt(TLO);
14632   }
14633
14634   return SDValue();
14635 }
14636
14637 // Check whether a boolean test is testing a boolean value generated by
14638 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14639 // code.
14640 //
14641 // Simplify the following patterns:
14642 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14643 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14644 // to (Op EFLAGS Cond)
14645 //
14646 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14647 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14648 // to (Op EFLAGS !Cond)
14649 //
14650 // where Op could be BRCOND or CMOV.
14651 //
14652 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14653   // Quit if not CMP and SUB with its value result used.
14654   if (Cmp.getOpcode() != X86ISD::CMP &&
14655       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14656       return SDValue();
14657
14658   // Quit if not used as a boolean value.
14659   if (CC != X86::COND_E && CC != X86::COND_NE)
14660     return SDValue();
14661
14662   // Check CMP operands. One of them should be 0 or 1 and the other should be
14663   // an SetCC or extended from it.
14664   SDValue Op1 = Cmp.getOperand(0);
14665   SDValue Op2 = Cmp.getOperand(1);
14666
14667   SDValue SetCC;
14668   const ConstantSDNode* C = 0;
14669   bool needOppositeCond = (CC == X86::COND_E);
14670
14671   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14672     SetCC = Op2;
14673   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14674     SetCC = Op1;
14675   else // Quit if all operands are not constants.
14676     return SDValue();
14677
14678   if (C->getZExtValue() == 1)
14679     needOppositeCond = !needOppositeCond;
14680   else if (C->getZExtValue() != 0)
14681     // Quit if the constant is neither 0 or 1.
14682     return SDValue();
14683
14684   // Skip 'zext' node.
14685   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14686     SetCC = SetCC.getOperand(0);
14687
14688   switch (SetCC.getOpcode()) {
14689   case X86ISD::SETCC:
14690     // Set the condition code or opposite one if necessary.
14691     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14692     if (needOppositeCond)
14693       CC = X86::GetOppositeBranchCondition(CC);
14694     return SetCC.getOperand(1);
14695   case X86ISD::CMOV: {
14696     // Check whether false/true value has canonical one, i.e. 0 or 1.
14697     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14698     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14699     // Quit if true value is not a constant.
14700     if (!TVal)
14701       return SDValue();
14702     // Quit if false value is not a constant.
14703     if (!FVal) {
14704       // A special case for rdrand, where 0 is set if false cond is found.
14705       SDValue Op = SetCC.getOperand(0);
14706       if (Op.getOpcode() != X86ISD::RDRAND)
14707         return SDValue();
14708     }
14709     // Quit if false value is not the constant 0 or 1.
14710     bool FValIsFalse = true;
14711     if (FVal && FVal->getZExtValue() != 0) {
14712       if (FVal->getZExtValue() != 1)
14713         return SDValue();
14714       // If FVal is 1, opposite cond is needed.
14715       needOppositeCond = !needOppositeCond;
14716       FValIsFalse = false;
14717     }
14718     // Quit if TVal is not the constant opposite of FVal.
14719     if (FValIsFalse && TVal->getZExtValue() != 1)
14720       return SDValue();
14721     if (!FValIsFalse && TVal->getZExtValue() != 0)
14722       return SDValue();
14723     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14724     if (needOppositeCond)
14725       CC = X86::GetOppositeBranchCondition(CC);
14726     return SetCC.getOperand(3);
14727   }
14728   }
14729
14730   return SDValue();
14731 }
14732
14733 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14734 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14735                                   TargetLowering::DAGCombinerInfo &DCI,
14736                                   const X86Subtarget *Subtarget) {
14737   DebugLoc DL = N->getDebugLoc();
14738
14739   // If the flag operand isn't dead, don't touch this CMOV.
14740   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14741     return SDValue();
14742
14743   SDValue FalseOp = N->getOperand(0);
14744   SDValue TrueOp = N->getOperand(1);
14745   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14746   SDValue Cond = N->getOperand(3);
14747
14748   if (CC == X86::COND_E || CC == X86::COND_NE) {
14749     switch (Cond.getOpcode()) {
14750     default: break;
14751     case X86ISD::BSR:
14752     case X86ISD::BSF:
14753       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14754       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14755         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14756     }
14757   }
14758
14759   SDValue Flags;
14760
14761   Flags = checkBoolTestSetCCCombine(Cond, CC);
14762   if (Flags.getNode() &&
14763       // Extra check as FCMOV only supports a subset of X86 cond.
14764       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14765     SDValue Ops[] = { FalseOp, TrueOp,
14766                       DAG.getConstant(CC, MVT::i8), Flags };
14767     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14768                        Ops, array_lengthof(Ops));
14769   }
14770
14771   // If this is a select between two integer constants, try to do some
14772   // optimizations.  Note that the operands are ordered the opposite of SELECT
14773   // operands.
14774   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14775     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14776       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14777       // larger than FalseC (the false value).
14778       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14779         CC = X86::GetOppositeBranchCondition(CC);
14780         std::swap(TrueC, FalseC);
14781         std::swap(TrueOp, FalseOp);
14782       }
14783
14784       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14785       // This is efficient for any integer data type (including i8/i16) and
14786       // shift amount.
14787       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14788         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14789                            DAG.getConstant(CC, MVT::i8), Cond);
14790
14791         // Zero extend the condition if needed.
14792         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14793
14794         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14795         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14796                            DAG.getConstant(ShAmt, MVT::i8));
14797         if (N->getNumValues() == 2)  // Dead flag value?
14798           return DCI.CombineTo(N, Cond, SDValue());
14799         return Cond;
14800       }
14801
14802       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14803       // for any integer data type, including i8/i16.
14804       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14805         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14806                            DAG.getConstant(CC, MVT::i8), Cond);
14807
14808         // Zero extend the condition if needed.
14809         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14810                            FalseC->getValueType(0), Cond);
14811         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14812                            SDValue(FalseC, 0));
14813
14814         if (N->getNumValues() == 2)  // Dead flag value?
14815           return DCI.CombineTo(N, Cond, SDValue());
14816         return Cond;
14817       }
14818
14819       // Optimize cases that will turn into an LEA instruction.  This requires
14820       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14821       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14822         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14823         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14824
14825         bool isFastMultiplier = false;
14826         if (Diff < 10) {
14827           switch ((unsigned char)Diff) {
14828           default: break;
14829           case 1:  // result = add base, cond
14830           case 2:  // result = lea base(    , cond*2)
14831           case 3:  // result = lea base(cond, cond*2)
14832           case 4:  // result = lea base(    , cond*4)
14833           case 5:  // result = lea base(cond, cond*4)
14834           case 8:  // result = lea base(    , cond*8)
14835           case 9:  // result = lea base(cond, cond*8)
14836             isFastMultiplier = true;
14837             break;
14838           }
14839         }
14840
14841         if (isFastMultiplier) {
14842           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14843           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14844                              DAG.getConstant(CC, MVT::i8), Cond);
14845           // Zero extend the condition if needed.
14846           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14847                              Cond);
14848           // Scale the condition by the difference.
14849           if (Diff != 1)
14850             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14851                                DAG.getConstant(Diff, Cond.getValueType()));
14852
14853           // Add the base if non-zero.
14854           if (FalseC->getAPIntValue() != 0)
14855             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14856                                SDValue(FalseC, 0));
14857           if (N->getNumValues() == 2)  // Dead flag value?
14858             return DCI.CombineTo(N, Cond, SDValue());
14859           return Cond;
14860         }
14861       }
14862     }
14863   }
14864
14865   // Handle these cases:
14866   //   (select (x != c), e, c) -> select (x != c), e, x),
14867   //   (select (x == c), c, e) -> select (x == c), x, e)
14868   // where the c is an integer constant, and the "select" is the combination
14869   // of CMOV and CMP.
14870   //
14871   // The rationale for this change is that the conditional-move from a constant
14872   // needs two instructions, however, conditional-move from a register needs
14873   // only one instruction.
14874   //
14875   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14876   //  some instruction-combining opportunities. This opt needs to be
14877   //  postponed as late as possible.
14878   //
14879   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14880     // the DCI.xxxx conditions are provided to postpone the optimization as
14881     // late as possible.
14882
14883     ConstantSDNode *CmpAgainst = 0;
14884     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14885         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14886         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14887
14888       if (CC == X86::COND_NE &&
14889           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14890         CC = X86::GetOppositeBranchCondition(CC);
14891         std::swap(TrueOp, FalseOp);
14892       }
14893
14894       if (CC == X86::COND_E &&
14895           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14896         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14897                           DAG.getConstant(CC, MVT::i8), Cond };
14898         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14899                            array_lengthof(Ops));
14900       }
14901     }
14902   }
14903
14904   return SDValue();
14905 }
14906
14907
14908 /// PerformMulCombine - Optimize a single multiply with constant into two
14909 /// in order to implement it with two cheaper instructions, e.g.
14910 /// LEA + SHL, LEA + LEA.
14911 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14912                                  TargetLowering::DAGCombinerInfo &DCI) {
14913   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14914     return SDValue();
14915
14916   EVT VT = N->getValueType(0);
14917   if (VT != MVT::i64)
14918     return SDValue();
14919
14920   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14921   if (!C)
14922     return SDValue();
14923   uint64_t MulAmt = C->getZExtValue();
14924   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14925     return SDValue();
14926
14927   uint64_t MulAmt1 = 0;
14928   uint64_t MulAmt2 = 0;
14929   if ((MulAmt % 9) == 0) {
14930     MulAmt1 = 9;
14931     MulAmt2 = MulAmt / 9;
14932   } else if ((MulAmt % 5) == 0) {
14933     MulAmt1 = 5;
14934     MulAmt2 = MulAmt / 5;
14935   } else if ((MulAmt % 3) == 0) {
14936     MulAmt1 = 3;
14937     MulAmt2 = MulAmt / 3;
14938   }
14939   if (MulAmt2 &&
14940       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14941     DebugLoc DL = N->getDebugLoc();
14942
14943     if (isPowerOf2_64(MulAmt2) &&
14944         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14945       // If second multiplifer is pow2, issue it first. We want the multiply by
14946       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14947       // is an add.
14948       std::swap(MulAmt1, MulAmt2);
14949
14950     SDValue NewMul;
14951     if (isPowerOf2_64(MulAmt1))
14952       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14953                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14954     else
14955       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14956                            DAG.getConstant(MulAmt1, VT));
14957
14958     if (isPowerOf2_64(MulAmt2))
14959       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14960                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14961     else
14962       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14963                            DAG.getConstant(MulAmt2, VT));
14964
14965     // Do not add new nodes to DAG combiner worklist.
14966     DCI.CombineTo(N, NewMul, false);
14967   }
14968   return SDValue();
14969 }
14970
14971 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14972   SDValue N0 = N->getOperand(0);
14973   SDValue N1 = N->getOperand(1);
14974   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14975   EVT VT = N0.getValueType();
14976
14977   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14978   // since the result of setcc_c is all zero's or all ones.
14979   if (VT.isInteger() && !VT.isVector() &&
14980       N1C && N0.getOpcode() == ISD::AND &&
14981       N0.getOperand(1).getOpcode() == ISD::Constant) {
14982     SDValue N00 = N0.getOperand(0);
14983     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14984         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14985           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14986          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14987       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14988       APInt ShAmt = N1C->getAPIntValue();
14989       Mask = Mask.shl(ShAmt);
14990       if (Mask != 0)
14991         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14992                            N00, DAG.getConstant(Mask, VT));
14993     }
14994   }
14995
14996
14997   // Hardware support for vector shifts is sparse which makes us scalarize the
14998   // vector operations in many cases. Also, on sandybridge ADD is faster than
14999   // shl.
15000   // (shl V, 1) -> add V,V
15001   if (isSplatVector(N1.getNode())) {
15002     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15003     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15004     // We shift all of the values by one. In many cases we do not have
15005     // hardware support for this operation. This is better expressed as an ADD
15006     // of two values.
15007     if (N1C && (1 == N1C->getZExtValue())) {
15008       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15009     }
15010   }
15011
15012   return SDValue();
15013 }
15014
15015 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15016 ///                       when possible.
15017 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15018                                    TargetLowering::DAGCombinerInfo &DCI,
15019                                    const X86Subtarget *Subtarget) {
15020   EVT VT = N->getValueType(0);
15021   if (N->getOpcode() == ISD::SHL) {
15022     SDValue V = PerformSHLCombine(N, DAG);
15023     if (V.getNode()) return V;
15024   }
15025
15026   // On X86 with SSE2 support, we can transform this to a vector shift if
15027   // all elements are shifted by the same amount.  We can't do this in legalize
15028   // because the a constant vector is typically transformed to a constant pool
15029   // so we have no knowledge of the shift amount.
15030   if (!Subtarget->hasSSE2())
15031     return SDValue();
15032
15033   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15034       (!Subtarget->hasAVX2() ||
15035        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15036     return SDValue();
15037
15038   SDValue ShAmtOp = N->getOperand(1);
15039   EVT EltVT = VT.getVectorElementType();
15040   DebugLoc DL = N->getDebugLoc();
15041   SDValue BaseShAmt = SDValue();
15042   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15043     unsigned NumElts = VT.getVectorNumElements();
15044     unsigned i = 0;
15045     for (; i != NumElts; ++i) {
15046       SDValue Arg = ShAmtOp.getOperand(i);
15047       if (Arg.getOpcode() == ISD::UNDEF) continue;
15048       BaseShAmt = Arg;
15049       break;
15050     }
15051     // Handle the case where the build_vector is all undef
15052     // FIXME: Should DAG allow this?
15053     if (i == NumElts)
15054       return SDValue();
15055
15056     for (; i != NumElts; ++i) {
15057       SDValue Arg = ShAmtOp.getOperand(i);
15058       if (Arg.getOpcode() == ISD::UNDEF) continue;
15059       if (Arg != BaseShAmt) {
15060         return SDValue();
15061       }
15062     }
15063   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15064              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15065     SDValue InVec = ShAmtOp.getOperand(0);
15066     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15067       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15068       unsigned i = 0;
15069       for (; i != NumElts; ++i) {
15070         SDValue Arg = InVec.getOperand(i);
15071         if (Arg.getOpcode() == ISD::UNDEF) continue;
15072         BaseShAmt = Arg;
15073         break;
15074       }
15075     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15076        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15077          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15078          if (C->getZExtValue() == SplatIdx)
15079            BaseShAmt = InVec.getOperand(1);
15080        }
15081     }
15082     if (BaseShAmt.getNode() == 0) {
15083       // Don't create instructions with illegal types after legalize
15084       // types has run.
15085       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15086           !DCI.isBeforeLegalize())
15087         return SDValue();
15088
15089       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15090                               DAG.getIntPtrConstant(0));
15091     }
15092   } else
15093     return SDValue();
15094
15095   // The shift amount is an i32.
15096   if (EltVT.bitsGT(MVT::i32))
15097     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15098   else if (EltVT.bitsLT(MVT::i32))
15099     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15100
15101   // The shift amount is identical so we can do a vector shift.
15102   SDValue  ValOp = N->getOperand(0);
15103   switch (N->getOpcode()) {
15104   default:
15105     llvm_unreachable("Unknown shift opcode!");
15106   case ISD::SHL:
15107     switch (VT.getSimpleVT().SimpleTy) {
15108     default: return SDValue();
15109     case MVT::v2i64:
15110     case MVT::v4i32:
15111     case MVT::v8i16:
15112     case MVT::v4i64:
15113     case MVT::v8i32:
15114     case MVT::v16i16:
15115       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15116     }
15117   case ISD::SRA:
15118     switch (VT.getSimpleVT().SimpleTy) {
15119     default: return SDValue();
15120     case MVT::v4i32:
15121     case MVT::v8i16:
15122     case MVT::v8i32:
15123     case MVT::v16i16:
15124       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15125     }
15126   case ISD::SRL:
15127     switch (VT.getSimpleVT().SimpleTy) {
15128     default: return SDValue();
15129     case MVT::v2i64:
15130     case MVT::v4i32:
15131     case MVT::v8i16:
15132     case MVT::v4i64:
15133     case MVT::v8i32:
15134     case MVT::v16i16:
15135       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15136     }
15137   }
15138 }
15139
15140
15141 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15142 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15143 // and friends.  Likewise for OR -> CMPNEQSS.
15144 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15145                             TargetLowering::DAGCombinerInfo &DCI,
15146                             const X86Subtarget *Subtarget) {
15147   unsigned opcode;
15148
15149   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15150   // we're requiring SSE2 for both.
15151   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15152     SDValue N0 = N->getOperand(0);
15153     SDValue N1 = N->getOperand(1);
15154     SDValue CMP0 = N0->getOperand(1);
15155     SDValue CMP1 = N1->getOperand(1);
15156     DebugLoc DL = N->getDebugLoc();
15157
15158     // The SETCCs should both refer to the same CMP.
15159     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15160       return SDValue();
15161
15162     SDValue CMP00 = CMP0->getOperand(0);
15163     SDValue CMP01 = CMP0->getOperand(1);
15164     EVT     VT    = CMP00.getValueType();
15165
15166     if (VT == MVT::f32 || VT == MVT::f64) {
15167       bool ExpectingFlags = false;
15168       // Check for any users that want flags:
15169       for (SDNode::use_iterator UI = N->use_begin(),
15170              UE = N->use_end();
15171            !ExpectingFlags && UI != UE; ++UI)
15172         switch (UI->getOpcode()) {
15173         default:
15174         case ISD::BR_CC:
15175         case ISD::BRCOND:
15176         case ISD::SELECT:
15177           ExpectingFlags = true;
15178           break;
15179         case ISD::CopyToReg:
15180         case ISD::SIGN_EXTEND:
15181         case ISD::ZERO_EXTEND:
15182         case ISD::ANY_EXTEND:
15183           break;
15184         }
15185
15186       if (!ExpectingFlags) {
15187         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15188         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15189
15190         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15191           X86::CondCode tmp = cc0;
15192           cc0 = cc1;
15193           cc1 = tmp;
15194         }
15195
15196         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15197             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15198           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15199           X86ISD::NodeType NTOperator = is64BitFP ?
15200             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15201           // FIXME: need symbolic constants for these magic numbers.
15202           // See X86ATTInstPrinter.cpp:printSSECC().
15203           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15204           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15205                                               DAG.getConstant(x86cc, MVT::i8));
15206           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15207                                               OnesOrZeroesF);
15208           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15209                                       DAG.getConstant(1, MVT::i32));
15210           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15211           return OneBitOfTruth;
15212         }
15213       }
15214     }
15215   }
15216   return SDValue();
15217 }
15218
15219 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15220 /// so it can be folded inside ANDNP.
15221 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15222   EVT VT = N->getValueType(0);
15223
15224   // Match direct AllOnes for 128 and 256-bit vectors
15225   if (ISD::isBuildVectorAllOnes(N))
15226     return true;
15227
15228   // Look through a bit convert.
15229   if (N->getOpcode() == ISD::BITCAST)
15230     N = N->getOperand(0).getNode();
15231
15232   // Sometimes the operand may come from a insert_subvector building a 256-bit
15233   // allones vector
15234   if (VT.is256BitVector() &&
15235       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15236     SDValue V1 = N->getOperand(0);
15237     SDValue V2 = N->getOperand(1);
15238
15239     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15240         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15241         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15242         ISD::isBuildVectorAllOnes(V2.getNode()))
15243       return true;
15244   }
15245
15246   return false;
15247 }
15248
15249 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15250                                  TargetLowering::DAGCombinerInfo &DCI,
15251                                  const X86Subtarget *Subtarget) {
15252   if (DCI.isBeforeLegalizeOps())
15253     return SDValue();
15254
15255   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15256   if (R.getNode())
15257     return R;
15258
15259   EVT VT = N->getValueType(0);
15260
15261   // Create ANDN, BLSI, and BLSR instructions
15262   // BLSI is X & (-X)
15263   // BLSR is X & (X-1)
15264   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15265     SDValue N0 = N->getOperand(0);
15266     SDValue N1 = N->getOperand(1);
15267     DebugLoc DL = N->getDebugLoc();
15268
15269     // Check LHS for not
15270     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15271       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15272     // Check RHS for not
15273     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15274       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15275
15276     // Check LHS for neg
15277     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15278         isZero(N0.getOperand(0)))
15279       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15280
15281     // Check RHS for neg
15282     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15283         isZero(N1.getOperand(0)))
15284       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15285
15286     // Check LHS for X-1
15287     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15288         isAllOnes(N0.getOperand(1)))
15289       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15290
15291     // Check RHS for X-1
15292     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15293         isAllOnes(N1.getOperand(1)))
15294       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15295
15296     return SDValue();
15297   }
15298
15299   // Want to form ANDNP nodes:
15300   // 1) In the hopes of then easily combining them with OR and AND nodes
15301   //    to form PBLEND/PSIGN.
15302   // 2) To match ANDN packed intrinsics
15303   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15304     return SDValue();
15305
15306   SDValue N0 = N->getOperand(0);
15307   SDValue N1 = N->getOperand(1);
15308   DebugLoc DL = N->getDebugLoc();
15309
15310   // Check LHS for vnot
15311   if (N0.getOpcode() == ISD::XOR &&
15312       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15313       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15314     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15315
15316   // Check RHS for vnot
15317   if (N1.getOpcode() == ISD::XOR &&
15318       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15319       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15320     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15321
15322   return SDValue();
15323 }
15324
15325 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15326                                 TargetLowering::DAGCombinerInfo &DCI,
15327                                 const X86Subtarget *Subtarget) {
15328   if (DCI.isBeforeLegalizeOps())
15329     return SDValue();
15330
15331   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15332   if (R.getNode())
15333     return R;
15334
15335   EVT VT = N->getValueType(0);
15336
15337   SDValue N0 = N->getOperand(0);
15338   SDValue N1 = N->getOperand(1);
15339
15340   // look for psign/blend
15341   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15342     if (!Subtarget->hasSSSE3() ||
15343         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15344       return SDValue();
15345
15346     // Canonicalize pandn to RHS
15347     if (N0.getOpcode() == X86ISD::ANDNP)
15348       std::swap(N0, N1);
15349     // or (and (m, y), (pandn m, x))
15350     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15351       SDValue Mask = N1.getOperand(0);
15352       SDValue X    = N1.getOperand(1);
15353       SDValue Y;
15354       if (N0.getOperand(0) == Mask)
15355         Y = N0.getOperand(1);
15356       if (N0.getOperand(1) == Mask)
15357         Y = N0.getOperand(0);
15358
15359       // Check to see if the mask appeared in both the AND and ANDNP and
15360       if (!Y.getNode())
15361         return SDValue();
15362
15363       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15364       // Look through mask bitcast.
15365       if (Mask.getOpcode() == ISD::BITCAST)
15366         Mask = Mask.getOperand(0);
15367       if (X.getOpcode() == ISD::BITCAST)
15368         X = X.getOperand(0);
15369       if (Y.getOpcode() == ISD::BITCAST)
15370         Y = Y.getOperand(0);
15371
15372       EVT MaskVT = Mask.getValueType();
15373
15374       // Validate that the Mask operand is a vector sra node.
15375       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15376       // there is no psrai.b
15377       if (Mask.getOpcode() != X86ISD::VSRAI)
15378         return SDValue();
15379
15380       // Check that the SRA is all signbits.
15381       SDValue SraC = Mask.getOperand(1);
15382       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15383       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15384       if ((SraAmt + 1) != EltBits)
15385         return SDValue();
15386
15387       DebugLoc DL = N->getDebugLoc();
15388
15389       // Now we know we at least have a plendvb with the mask val.  See if
15390       // we can form a psignb/w/d.
15391       // psign = x.type == y.type == mask.type && y = sub(0, x);
15392       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15393           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15394           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15395         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15396                "Unsupported VT for PSIGN");
15397         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15398         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15399       }
15400       // PBLENDVB only available on SSE 4.1
15401       if (!Subtarget->hasSSE41())
15402         return SDValue();
15403
15404       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15405
15406       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15407       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15408       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15409       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15410       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15411     }
15412   }
15413
15414   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15415     return SDValue();
15416
15417   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15418   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15419     std::swap(N0, N1);
15420   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15421     return SDValue();
15422   if (!N0.hasOneUse() || !N1.hasOneUse())
15423     return SDValue();
15424
15425   SDValue ShAmt0 = N0.getOperand(1);
15426   if (ShAmt0.getValueType() != MVT::i8)
15427     return SDValue();
15428   SDValue ShAmt1 = N1.getOperand(1);
15429   if (ShAmt1.getValueType() != MVT::i8)
15430     return SDValue();
15431   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15432     ShAmt0 = ShAmt0.getOperand(0);
15433   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15434     ShAmt1 = ShAmt1.getOperand(0);
15435
15436   DebugLoc DL = N->getDebugLoc();
15437   unsigned Opc = X86ISD::SHLD;
15438   SDValue Op0 = N0.getOperand(0);
15439   SDValue Op1 = N1.getOperand(0);
15440   if (ShAmt0.getOpcode() == ISD::SUB) {
15441     Opc = X86ISD::SHRD;
15442     std::swap(Op0, Op1);
15443     std::swap(ShAmt0, ShAmt1);
15444   }
15445
15446   unsigned Bits = VT.getSizeInBits();
15447   if (ShAmt1.getOpcode() == ISD::SUB) {
15448     SDValue Sum = ShAmt1.getOperand(0);
15449     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15450       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15451       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15452         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15453       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15454         return DAG.getNode(Opc, DL, VT,
15455                            Op0, Op1,
15456                            DAG.getNode(ISD::TRUNCATE, DL,
15457                                        MVT::i8, ShAmt0));
15458     }
15459   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15460     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15461     if (ShAmt0C &&
15462         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15463       return DAG.getNode(Opc, DL, VT,
15464                          N0.getOperand(0), N1.getOperand(0),
15465                          DAG.getNode(ISD::TRUNCATE, DL,
15466                                        MVT::i8, ShAmt0));
15467   }
15468
15469   return SDValue();
15470 }
15471
15472 // Generate NEG and CMOV for integer abs.
15473 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15474   EVT VT = N->getValueType(0);
15475
15476   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15477   // 8-bit integer abs to NEG and CMOV.
15478   if (VT.isInteger() && VT.getSizeInBits() == 8)
15479     return SDValue();
15480
15481   SDValue N0 = N->getOperand(0);
15482   SDValue N1 = N->getOperand(1);
15483   DebugLoc DL = N->getDebugLoc();
15484
15485   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15486   // and change it to SUB and CMOV.
15487   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15488       N0.getOpcode() == ISD::ADD &&
15489       N0.getOperand(1) == N1 &&
15490       N1.getOpcode() == ISD::SRA &&
15491       N1.getOperand(0) == N0.getOperand(0))
15492     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15493       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15494         // Generate SUB & CMOV.
15495         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15496                                   DAG.getConstant(0, VT), N0.getOperand(0));
15497
15498         SDValue Ops[] = { N0.getOperand(0), Neg,
15499                           DAG.getConstant(X86::COND_GE, MVT::i8),
15500                           SDValue(Neg.getNode(), 1) };
15501         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15502                            Ops, array_lengthof(Ops));
15503       }
15504   return SDValue();
15505 }
15506
15507 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15508 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15509                                  TargetLowering::DAGCombinerInfo &DCI,
15510                                  const X86Subtarget *Subtarget) {
15511   if (DCI.isBeforeLegalizeOps())
15512     return SDValue();
15513
15514   if (Subtarget->hasCMov()) {
15515     SDValue RV = performIntegerAbsCombine(N, DAG);
15516     if (RV.getNode())
15517       return RV;
15518   }
15519
15520   // Try forming BMI if it is available.
15521   if (!Subtarget->hasBMI())
15522     return SDValue();
15523
15524   EVT VT = N->getValueType(0);
15525
15526   if (VT != MVT::i32 && VT != MVT::i64)
15527     return SDValue();
15528
15529   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15530
15531   // Create BLSMSK instructions by finding X ^ (X-1)
15532   SDValue N0 = N->getOperand(0);
15533   SDValue N1 = N->getOperand(1);
15534   DebugLoc DL = N->getDebugLoc();
15535
15536   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15537       isAllOnes(N0.getOperand(1)))
15538     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15539
15540   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15541       isAllOnes(N1.getOperand(1)))
15542     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15543
15544   return SDValue();
15545 }
15546
15547 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15548 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15549                                   TargetLowering::DAGCombinerInfo &DCI,
15550                                   const X86Subtarget *Subtarget) {
15551   LoadSDNode *Ld = cast<LoadSDNode>(N);
15552   EVT RegVT = Ld->getValueType(0);
15553   EVT MemVT = Ld->getMemoryVT();
15554   DebugLoc dl = Ld->getDebugLoc();
15555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15556
15557   ISD::LoadExtType Ext = Ld->getExtensionType();
15558
15559   // If this is a vector EXT Load then attempt to optimize it using a
15560   // shuffle. We need SSSE3 shuffles.
15561   // TODO: It is possible to support ZExt by zeroing the undef values
15562   // during the shuffle phase or after the shuffle.
15563   if (RegVT.isVector() && RegVT.isInteger() &&
15564       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15565     assert(MemVT != RegVT && "Cannot extend to the same type");
15566     assert(MemVT.isVector() && "Must load a vector from memory");
15567
15568     unsigned NumElems = RegVT.getVectorNumElements();
15569     unsigned RegSz = RegVT.getSizeInBits();
15570     unsigned MemSz = MemVT.getSizeInBits();
15571     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15572
15573     // All sizes must be a power of two.
15574     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15575       return SDValue();
15576
15577     // Attempt to load the original value using scalar loads.
15578     // Find the largest scalar type that divides the total loaded size.
15579     MVT SclrLoadTy = MVT::i8;
15580     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15581          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15582       MVT Tp = (MVT::SimpleValueType)tp;
15583       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15584         SclrLoadTy = Tp;
15585       }
15586     }
15587
15588     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15589     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15590         (64 <= MemSz))
15591       SclrLoadTy = MVT::f64;
15592
15593     // Calculate the number of scalar loads that we need to perform
15594     // in order to load our vector from memory.
15595     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15596
15597     // Represent our vector as a sequence of elements which are the
15598     // largest scalar that we can load.
15599     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15600       RegSz/SclrLoadTy.getSizeInBits());
15601
15602     // Represent the data using the same element type that is stored in
15603     // memory. In practice, we ''widen'' MemVT.
15604     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15605                                   RegSz/MemVT.getScalarType().getSizeInBits());
15606
15607     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15608       "Invalid vector type");
15609
15610     // We can't shuffle using an illegal type.
15611     if (!TLI.isTypeLegal(WideVecVT))
15612       return SDValue();
15613
15614     SmallVector<SDValue, 8> Chains;
15615     SDValue Ptr = Ld->getBasePtr();
15616     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15617                                         TLI.getPointerTy());
15618     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15619
15620     for (unsigned i = 0; i < NumLoads; ++i) {
15621       // Perform a single load.
15622       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15623                                        Ptr, Ld->getPointerInfo(),
15624                                        Ld->isVolatile(), Ld->isNonTemporal(),
15625                                        Ld->isInvariant(), Ld->getAlignment());
15626       Chains.push_back(ScalarLoad.getValue(1));
15627       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15628       // another round of DAGCombining.
15629       if (i == 0)
15630         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15631       else
15632         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15633                           ScalarLoad, DAG.getIntPtrConstant(i));
15634
15635       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15636     }
15637
15638     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15639                                Chains.size());
15640
15641     // Bitcast the loaded value to a vector of the original element type, in
15642     // the size of the target vector type.
15643     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15644     unsigned SizeRatio = RegSz/MemSz;
15645
15646     // Redistribute the loaded elements into the different locations.
15647     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15648     for (unsigned i = 0; i != NumElems; ++i)
15649       ShuffleVec[i*SizeRatio] = i;
15650
15651     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15652                                          DAG.getUNDEF(WideVecVT),
15653                                          &ShuffleVec[0]);
15654
15655     // Bitcast to the requested type.
15656     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15657     // Replace the original load with the new sequence
15658     // and return the new chain.
15659     return DCI.CombineTo(N, Shuff, TF, true);
15660   }
15661
15662   return SDValue();
15663 }
15664
15665 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15666 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15667                                    const X86Subtarget *Subtarget) {
15668   StoreSDNode *St = cast<StoreSDNode>(N);
15669   EVT VT = St->getValue().getValueType();
15670   EVT StVT = St->getMemoryVT();
15671   DebugLoc dl = St->getDebugLoc();
15672   SDValue StoredVal = St->getOperand(1);
15673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15674
15675   // If we are saving a concatenation of two XMM registers, perform two stores.
15676   // On Sandy Bridge, 256-bit memory operations are executed by two
15677   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15678   // memory  operation.
15679   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15680       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15681       StoredVal.getNumOperands() == 2) {
15682     SDValue Value0 = StoredVal.getOperand(0);
15683     SDValue Value1 = StoredVal.getOperand(1);
15684
15685     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15686     SDValue Ptr0 = St->getBasePtr();
15687     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15688
15689     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15690                                 St->getPointerInfo(), St->isVolatile(),
15691                                 St->isNonTemporal(), St->getAlignment());
15692     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15693                                 St->getPointerInfo(), St->isVolatile(),
15694                                 St->isNonTemporal(), St->getAlignment());
15695     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15696   }
15697
15698   // Optimize trunc store (of multiple scalars) to shuffle and store.
15699   // First, pack all of the elements in one place. Next, store to memory
15700   // in fewer chunks.
15701   if (St->isTruncatingStore() && VT.isVector()) {
15702     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15703     unsigned NumElems = VT.getVectorNumElements();
15704     assert(StVT != VT && "Cannot truncate to the same type");
15705     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15706     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15707
15708     // From, To sizes and ElemCount must be pow of two
15709     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15710     // We are going to use the original vector elt for storing.
15711     // Accumulated smaller vector elements must be a multiple of the store size.
15712     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15713
15714     unsigned SizeRatio  = FromSz / ToSz;
15715
15716     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15717
15718     // Create a type on which we perform the shuffle
15719     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15720             StVT.getScalarType(), NumElems*SizeRatio);
15721
15722     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15723
15724     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15725     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15726     for (unsigned i = 0; i != NumElems; ++i)
15727       ShuffleVec[i] = i * SizeRatio;
15728
15729     // Can't shuffle using an illegal type.
15730     if (!TLI.isTypeLegal(WideVecVT))
15731       return SDValue();
15732
15733     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15734                                          DAG.getUNDEF(WideVecVT),
15735                                          &ShuffleVec[0]);
15736     // At this point all of the data is stored at the bottom of the
15737     // register. We now need to save it to mem.
15738
15739     // Find the largest store unit
15740     MVT StoreType = MVT::i8;
15741     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15742          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15743       MVT Tp = (MVT::SimpleValueType)tp;
15744       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15745         StoreType = Tp;
15746     }
15747
15748     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15749     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15750         (64 <= NumElems * ToSz))
15751       StoreType = MVT::f64;
15752
15753     // Bitcast the original vector into a vector of store-size units
15754     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15755             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15756     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15757     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15758     SmallVector<SDValue, 8> Chains;
15759     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15760                                         TLI.getPointerTy());
15761     SDValue Ptr = St->getBasePtr();
15762
15763     // Perform one or more big stores into memory.
15764     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15765       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15766                                    StoreType, ShuffWide,
15767                                    DAG.getIntPtrConstant(i));
15768       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15769                                 St->getPointerInfo(), St->isVolatile(),
15770                                 St->isNonTemporal(), St->getAlignment());
15771       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15772       Chains.push_back(Ch);
15773     }
15774
15775     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15776                                Chains.size());
15777   }
15778
15779
15780   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15781   // the FP state in cases where an emms may be missing.
15782   // A preferable solution to the general problem is to figure out the right
15783   // places to insert EMMS.  This qualifies as a quick hack.
15784
15785   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15786   if (VT.getSizeInBits() != 64)
15787     return SDValue();
15788
15789   const Function *F = DAG.getMachineFunction().getFunction();
15790   bool NoImplicitFloatOps = F->getFnAttributes().
15791     hasAttribute(Attributes::NoImplicitFloat);
15792   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15793                      && Subtarget->hasSSE2();
15794   if ((VT.isVector() ||
15795        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15796       isa<LoadSDNode>(St->getValue()) &&
15797       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15798       St->getChain().hasOneUse() && !St->isVolatile()) {
15799     SDNode* LdVal = St->getValue().getNode();
15800     LoadSDNode *Ld = 0;
15801     int TokenFactorIndex = -1;
15802     SmallVector<SDValue, 8> Ops;
15803     SDNode* ChainVal = St->getChain().getNode();
15804     // Must be a store of a load.  We currently handle two cases:  the load
15805     // is a direct child, and it's under an intervening TokenFactor.  It is
15806     // possible to dig deeper under nested TokenFactors.
15807     if (ChainVal == LdVal)
15808       Ld = cast<LoadSDNode>(St->getChain());
15809     else if (St->getValue().hasOneUse() &&
15810              ChainVal->getOpcode() == ISD::TokenFactor) {
15811       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15812         if (ChainVal->getOperand(i).getNode() == LdVal) {
15813           TokenFactorIndex = i;
15814           Ld = cast<LoadSDNode>(St->getValue());
15815         } else
15816           Ops.push_back(ChainVal->getOperand(i));
15817       }
15818     }
15819
15820     if (!Ld || !ISD::isNormalLoad(Ld))
15821       return SDValue();
15822
15823     // If this is not the MMX case, i.e. we are just turning i64 load/store
15824     // into f64 load/store, avoid the transformation if there are multiple
15825     // uses of the loaded value.
15826     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15827       return SDValue();
15828
15829     DebugLoc LdDL = Ld->getDebugLoc();
15830     DebugLoc StDL = N->getDebugLoc();
15831     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15832     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15833     // pair instead.
15834     if (Subtarget->is64Bit() || F64IsLegal) {
15835       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15836       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15837                                   Ld->getPointerInfo(), Ld->isVolatile(),
15838                                   Ld->isNonTemporal(), Ld->isInvariant(),
15839                                   Ld->getAlignment());
15840       SDValue NewChain = NewLd.getValue(1);
15841       if (TokenFactorIndex != -1) {
15842         Ops.push_back(NewChain);
15843         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15844                                Ops.size());
15845       }
15846       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15847                           St->getPointerInfo(),
15848                           St->isVolatile(), St->isNonTemporal(),
15849                           St->getAlignment());
15850     }
15851
15852     // Otherwise, lower to two pairs of 32-bit loads / stores.
15853     SDValue LoAddr = Ld->getBasePtr();
15854     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15855                                  DAG.getConstant(4, MVT::i32));
15856
15857     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15858                                Ld->getPointerInfo(),
15859                                Ld->isVolatile(), Ld->isNonTemporal(),
15860                                Ld->isInvariant(), Ld->getAlignment());
15861     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15862                                Ld->getPointerInfo().getWithOffset(4),
15863                                Ld->isVolatile(), Ld->isNonTemporal(),
15864                                Ld->isInvariant(),
15865                                MinAlign(Ld->getAlignment(), 4));
15866
15867     SDValue NewChain = LoLd.getValue(1);
15868     if (TokenFactorIndex != -1) {
15869       Ops.push_back(LoLd);
15870       Ops.push_back(HiLd);
15871       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15872                              Ops.size());
15873     }
15874
15875     LoAddr = St->getBasePtr();
15876     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15877                          DAG.getConstant(4, MVT::i32));
15878
15879     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15880                                 St->getPointerInfo(),
15881                                 St->isVolatile(), St->isNonTemporal(),
15882                                 St->getAlignment());
15883     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15884                                 St->getPointerInfo().getWithOffset(4),
15885                                 St->isVolatile(),
15886                                 St->isNonTemporal(),
15887                                 MinAlign(St->getAlignment(), 4));
15888     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15889   }
15890   return SDValue();
15891 }
15892
15893 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15894 /// and return the operands for the horizontal operation in LHS and RHS.  A
15895 /// horizontal operation performs the binary operation on successive elements
15896 /// of its first operand, then on successive elements of its second operand,
15897 /// returning the resulting values in a vector.  For example, if
15898 ///   A = < float a0, float a1, float a2, float a3 >
15899 /// and
15900 ///   B = < float b0, float b1, float b2, float b3 >
15901 /// then the result of doing a horizontal operation on A and B is
15902 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15903 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15904 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15905 /// set to A, RHS to B, and the routine returns 'true'.
15906 /// Note that the binary operation should have the property that if one of the
15907 /// operands is UNDEF then the result is UNDEF.
15908 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15909   // Look for the following pattern: if
15910   //   A = < float a0, float a1, float a2, float a3 >
15911   //   B = < float b0, float b1, float b2, float b3 >
15912   // and
15913   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15914   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15915   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15916   // which is A horizontal-op B.
15917
15918   // At least one of the operands should be a vector shuffle.
15919   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15920       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15921     return false;
15922
15923   EVT VT = LHS.getValueType();
15924
15925   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15926          "Unsupported vector type for horizontal add/sub");
15927
15928   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15929   // operate independently on 128-bit lanes.
15930   unsigned NumElts = VT.getVectorNumElements();
15931   unsigned NumLanes = VT.getSizeInBits()/128;
15932   unsigned NumLaneElts = NumElts / NumLanes;
15933   assert((NumLaneElts % 2 == 0) &&
15934          "Vector type should have an even number of elements in each lane");
15935   unsigned HalfLaneElts = NumLaneElts/2;
15936
15937   // View LHS in the form
15938   //   LHS = VECTOR_SHUFFLE A, B, LMask
15939   // If LHS is not a shuffle then pretend it is the shuffle
15940   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15941   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15942   // type VT.
15943   SDValue A, B;
15944   SmallVector<int, 16> LMask(NumElts);
15945   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15946     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15947       A = LHS.getOperand(0);
15948     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15949       B = LHS.getOperand(1);
15950     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15951     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15952   } else {
15953     if (LHS.getOpcode() != ISD::UNDEF)
15954       A = LHS;
15955     for (unsigned i = 0; i != NumElts; ++i)
15956       LMask[i] = i;
15957   }
15958
15959   // Likewise, view RHS in the form
15960   //   RHS = VECTOR_SHUFFLE C, D, RMask
15961   SDValue C, D;
15962   SmallVector<int, 16> RMask(NumElts);
15963   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15964     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15965       C = RHS.getOperand(0);
15966     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15967       D = RHS.getOperand(1);
15968     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15969     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15970   } else {
15971     if (RHS.getOpcode() != ISD::UNDEF)
15972       C = RHS;
15973     for (unsigned i = 0; i != NumElts; ++i)
15974       RMask[i] = i;
15975   }
15976
15977   // Check that the shuffles are both shuffling the same vectors.
15978   if (!(A == C && B == D) && !(A == D && B == C))
15979     return false;
15980
15981   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15982   if (!A.getNode() && !B.getNode())
15983     return false;
15984
15985   // If A and B occur in reverse order in RHS, then "swap" them (which means
15986   // rewriting the mask).
15987   if (A != C)
15988     CommuteVectorShuffleMask(RMask, NumElts);
15989
15990   // At this point LHS and RHS are equivalent to
15991   //   LHS = VECTOR_SHUFFLE A, B, LMask
15992   //   RHS = VECTOR_SHUFFLE A, B, RMask
15993   // Check that the masks correspond to performing a horizontal operation.
15994   for (unsigned i = 0; i != NumElts; ++i) {
15995     int LIdx = LMask[i], RIdx = RMask[i];
15996
15997     // Ignore any UNDEF components.
15998     if (LIdx < 0 || RIdx < 0 ||
15999         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16000         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16001       continue;
16002
16003     // Check that successive elements are being operated on.  If not, this is
16004     // not a horizontal operation.
16005     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16006     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16007     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16008     if (!(LIdx == Index && RIdx == Index + 1) &&
16009         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16010       return false;
16011   }
16012
16013   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16014   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16015   return true;
16016 }
16017
16018 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16019 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16020                                   const X86Subtarget *Subtarget) {
16021   EVT VT = N->getValueType(0);
16022   SDValue LHS = N->getOperand(0);
16023   SDValue RHS = N->getOperand(1);
16024
16025   // Try to synthesize horizontal adds from adds of shuffles.
16026   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16027        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16028       isHorizontalBinOp(LHS, RHS, true))
16029     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16030   return SDValue();
16031 }
16032
16033 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16034 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16035                                   const X86Subtarget *Subtarget) {
16036   EVT VT = N->getValueType(0);
16037   SDValue LHS = N->getOperand(0);
16038   SDValue RHS = N->getOperand(1);
16039
16040   // Try to synthesize horizontal subs from subs of shuffles.
16041   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16042        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16043       isHorizontalBinOp(LHS, RHS, false))
16044     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16045   return SDValue();
16046 }
16047
16048 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16049 /// X86ISD::FXOR nodes.
16050 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16051   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16052   // F[X]OR(0.0, x) -> x
16053   // F[X]OR(x, 0.0) -> x
16054   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16055     if (C->getValueAPF().isPosZero())
16056       return N->getOperand(1);
16057   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16058     if (C->getValueAPF().isPosZero())
16059       return N->getOperand(0);
16060   return SDValue();
16061 }
16062
16063 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16064 /// X86ISD::FMAX nodes.
16065 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16066   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16067
16068   // Only perform optimizations if UnsafeMath is used.
16069   if (!DAG.getTarget().Options.UnsafeFPMath)
16070     return SDValue();
16071
16072   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16073   // into FMINC and FMAXC, which are Commutative operations.
16074   unsigned NewOp = 0;
16075   switch (N->getOpcode()) {
16076     default: llvm_unreachable("unknown opcode");
16077     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16078     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16079   }
16080
16081   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16082                      N->getOperand(0), N->getOperand(1));
16083 }
16084
16085
16086 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16087 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16088   // FAND(0.0, x) -> 0.0
16089   // FAND(x, 0.0) -> 0.0
16090   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16091     if (C->getValueAPF().isPosZero())
16092       return N->getOperand(0);
16093   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16094     if (C->getValueAPF().isPosZero())
16095       return N->getOperand(1);
16096   return SDValue();
16097 }
16098
16099 static SDValue PerformBTCombine(SDNode *N,
16100                                 SelectionDAG &DAG,
16101                                 TargetLowering::DAGCombinerInfo &DCI) {
16102   // BT ignores high bits in the bit index operand.
16103   SDValue Op1 = N->getOperand(1);
16104   if (Op1.hasOneUse()) {
16105     unsigned BitWidth = Op1.getValueSizeInBits();
16106     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16107     APInt KnownZero, KnownOne;
16108     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16109                                           !DCI.isBeforeLegalizeOps());
16110     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16111     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16112         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16113       DCI.CommitTargetLoweringOpt(TLO);
16114   }
16115   return SDValue();
16116 }
16117
16118 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16119   SDValue Op = N->getOperand(0);
16120   if (Op.getOpcode() == ISD::BITCAST)
16121     Op = Op.getOperand(0);
16122   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16123   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16124       VT.getVectorElementType().getSizeInBits() ==
16125       OpVT.getVectorElementType().getSizeInBits()) {
16126     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16127   }
16128   return SDValue();
16129 }
16130
16131 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16132                                   TargetLowering::DAGCombinerInfo &DCI,
16133                                   const X86Subtarget *Subtarget) {
16134   if (!DCI.isBeforeLegalizeOps())
16135     return SDValue();
16136
16137   if (!Subtarget->hasAVX())
16138     return SDValue();
16139
16140   EVT VT = N->getValueType(0);
16141   SDValue Op = N->getOperand(0);
16142   EVT OpVT = Op.getValueType();
16143   DebugLoc dl = N->getDebugLoc();
16144
16145   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16146       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16147
16148     if (Subtarget->hasAVX2())
16149       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16150
16151     // Optimize vectors in AVX mode
16152     // Sign extend  v8i16 to v8i32 and
16153     //              v4i32 to v4i64
16154     //
16155     // Divide input vector into two parts
16156     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16157     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16158     // concat the vectors to original VT
16159
16160     unsigned NumElems = OpVT.getVectorNumElements();
16161     SDValue Undef = DAG.getUNDEF(OpVT);
16162
16163     SmallVector<int,8> ShufMask1(NumElems, -1);
16164     for (unsigned i = 0; i != NumElems/2; ++i)
16165       ShufMask1[i] = i;
16166
16167     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16168
16169     SmallVector<int,8> ShufMask2(NumElems, -1);
16170     for (unsigned i = 0; i != NumElems/2; ++i)
16171       ShufMask2[i] = i + NumElems/2;
16172
16173     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16174
16175     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16176                                   VT.getVectorNumElements()/2);
16177
16178     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16179     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16180
16181     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16182   }
16183   return SDValue();
16184 }
16185
16186 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16187                                  const X86Subtarget* Subtarget) {
16188   DebugLoc dl = N->getDebugLoc();
16189   EVT VT = N->getValueType(0);
16190
16191   // Let legalize expand this if it isn't a legal type yet.
16192   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16193     return SDValue();
16194
16195   EVT ScalarVT = VT.getScalarType();
16196   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16197       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16198     return SDValue();
16199
16200   SDValue A = N->getOperand(0);
16201   SDValue B = N->getOperand(1);
16202   SDValue C = N->getOperand(2);
16203
16204   bool NegA = (A.getOpcode() == ISD::FNEG);
16205   bool NegB = (B.getOpcode() == ISD::FNEG);
16206   bool NegC = (C.getOpcode() == ISD::FNEG);
16207
16208   // Negative multiplication when NegA xor NegB
16209   bool NegMul = (NegA != NegB);
16210   if (NegA)
16211     A = A.getOperand(0);
16212   if (NegB)
16213     B = B.getOperand(0);
16214   if (NegC)
16215     C = C.getOperand(0);
16216
16217   unsigned Opcode;
16218   if (!NegMul)
16219     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16220   else
16221     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16222
16223   return DAG.getNode(Opcode, dl, VT, A, B, C);
16224 }
16225
16226 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16227                                   TargetLowering::DAGCombinerInfo &DCI,
16228                                   const X86Subtarget *Subtarget) {
16229   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16230   //           (and (i32 x86isd::setcc_carry), 1)
16231   // This eliminates the zext. This transformation is necessary because
16232   // ISD::SETCC is always legalized to i8.
16233   DebugLoc dl = N->getDebugLoc();
16234   SDValue N0 = N->getOperand(0);
16235   EVT VT = N->getValueType(0);
16236   EVT OpVT = N0.getValueType();
16237
16238   if (N0.getOpcode() == ISD::AND &&
16239       N0.hasOneUse() &&
16240       N0.getOperand(0).hasOneUse()) {
16241     SDValue N00 = N0.getOperand(0);
16242     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16243       return SDValue();
16244     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16245     if (!C || C->getZExtValue() != 1)
16246       return SDValue();
16247     return DAG.getNode(ISD::AND, dl, VT,
16248                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16249                                    N00.getOperand(0), N00.getOperand(1)),
16250                        DAG.getConstant(1, VT));
16251   }
16252
16253   // Optimize vectors in AVX mode:
16254   //
16255   //   v8i16 -> v8i32
16256   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16257   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16258   //   Concat upper and lower parts.
16259   //
16260   //   v4i32 -> v4i64
16261   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16262   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16263   //   Concat upper and lower parts.
16264   //
16265   if (!DCI.isBeforeLegalizeOps())
16266     return SDValue();
16267
16268   if (!Subtarget->hasAVX())
16269     return SDValue();
16270
16271   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16272       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16273
16274     if (Subtarget->hasAVX2())
16275       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16276
16277     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16278     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16279     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16280
16281     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16282                                VT.getVectorNumElements()/2);
16283
16284     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16285     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16286
16287     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16288   }
16289
16290   return SDValue();
16291 }
16292
16293 // Optimize x == -y --> x+y == 0
16294 //          x != -y --> x+y != 0
16295 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16296   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16297   SDValue LHS = N->getOperand(0);
16298   SDValue RHS = N->getOperand(1);
16299
16300   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16302       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16303         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16304                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16305         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16306                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16307       }
16308   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16309     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16310       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16311         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16312                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16313         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16314                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16315       }
16316   return SDValue();
16317 }
16318
16319 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16320 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16321                                    TargetLowering::DAGCombinerInfo &DCI,
16322                                    const X86Subtarget *Subtarget) {
16323   DebugLoc DL = N->getDebugLoc();
16324   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16325   SDValue EFLAGS = N->getOperand(1);
16326
16327   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16328   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16329   // cases.
16330   if (CC == X86::COND_B)
16331     return DAG.getNode(ISD::AND, DL, MVT::i8,
16332                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16333                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16334                        DAG.getConstant(1, MVT::i8));
16335
16336   SDValue Flags;
16337
16338   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16339   if (Flags.getNode()) {
16340     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16341     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16342   }
16343
16344   return SDValue();
16345 }
16346
16347 // Optimize branch condition evaluation.
16348 //
16349 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16350                                     TargetLowering::DAGCombinerInfo &DCI,
16351                                     const X86Subtarget *Subtarget) {
16352   DebugLoc DL = N->getDebugLoc();
16353   SDValue Chain = N->getOperand(0);
16354   SDValue Dest = N->getOperand(1);
16355   SDValue EFLAGS = N->getOperand(3);
16356   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16357
16358   SDValue Flags;
16359
16360   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16361   if (Flags.getNode()) {
16362     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16363     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16364                        Flags);
16365   }
16366
16367   return SDValue();
16368 }
16369
16370 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16371   SDValue Op0 = N->getOperand(0);
16372   EVT InVT = Op0->getValueType(0);
16373
16374   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16375   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16376     DebugLoc dl = N->getDebugLoc();
16377     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16378     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16379     // Notice that we use SINT_TO_FP because we know that the high bits
16380     // are zero and SINT_TO_FP is better supported by the hardware.
16381     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16382   }
16383
16384   return SDValue();
16385 }
16386
16387 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16388                                         const X86TargetLowering *XTLI) {
16389   SDValue Op0 = N->getOperand(0);
16390   EVT InVT = Op0->getValueType(0);
16391
16392   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16393   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16394     DebugLoc dl = N->getDebugLoc();
16395     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16396     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16397     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16398   }
16399
16400   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16401   // a 32-bit target where SSE doesn't support i64->FP operations.
16402   if (Op0.getOpcode() == ISD::LOAD) {
16403     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16404     EVT VT = Ld->getValueType(0);
16405     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16406         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16407         !XTLI->getSubtarget()->is64Bit() &&
16408         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16409       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16410                                           Ld->getChain(), Op0, DAG);
16411       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16412       return FILDChain;
16413     }
16414   }
16415   return SDValue();
16416 }
16417
16418 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16419 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16420                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16421   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16422   // the result is either zero or one (depending on the input carry bit).
16423   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16424   if (X86::isZeroNode(N->getOperand(0)) &&
16425       X86::isZeroNode(N->getOperand(1)) &&
16426       // We don't have a good way to replace an EFLAGS use, so only do this when
16427       // dead right now.
16428       SDValue(N, 1).use_empty()) {
16429     DebugLoc DL = N->getDebugLoc();
16430     EVT VT = N->getValueType(0);
16431     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16432     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16433                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16434                                            DAG.getConstant(X86::COND_B,MVT::i8),
16435                                            N->getOperand(2)),
16436                                DAG.getConstant(1, VT));
16437     return DCI.CombineTo(N, Res1, CarryOut);
16438   }
16439
16440   return SDValue();
16441 }
16442
16443 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16444 //      (add Y, (setne X, 0)) -> sbb -1, Y
16445 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16446 //      (sub (setne X, 0), Y) -> adc -1, Y
16447 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16448   DebugLoc DL = N->getDebugLoc();
16449
16450   // Look through ZExts.
16451   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16452   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16453     return SDValue();
16454
16455   SDValue SetCC = Ext.getOperand(0);
16456   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16457     return SDValue();
16458
16459   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16460   if (CC != X86::COND_E && CC != X86::COND_NE)
16461     return SDValue();
16462
16463   SDValue Cmp = SetCC.getOperand(1);
16464   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16465       !X86::isZeroNode(Cmp.getOperand(1)) ||
16466       !Cmp.getOperand(0).getValueType().isInteger())
16467     return SDValue();
16468
16469   SDValue CmpOp0 = Cmp.getOperand(0);
16470   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16471                                DAG.getConstant(1, CmpOp0.getValueType()));
16472
16473   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16474   if (CC == X86::COND_NE)
16475     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16476                        DL, OtherVal.getValueType(), OtherVal,
16477                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16478   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16479                      DL, OtherVal.getValueType(), OtherVal,
16480                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16481 }
16482
16483 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16484 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16485                                  const X86Subtarget *Subtarget) {
16486   EVT VT = N->getValueType(0);
16487   SDValue Op0 = N->getOperand(0);
16488   SDValue Op1 = N->getOperand(1);
16489
16490   // Try to synthesize horizontal adds from adds of shuffles.
16491   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16492        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16493       isHorizontalBinOp(Op0, Op1, true))
16494     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16495
16496   return OptimizeConditionalInDecrement(N, DAG);
16497 }
16498
16499 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16500                                  const X86Subtarget *Subtarget) {
16501   SDValue Op0 = N->getOperand(0);
16502   SDValue Op1 = N->getOperand(1);
16503
16504   // X86 can't encode an immediate LHS of a sub. See if we can push the
16505   // negation into a preceding instruction.
16506   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16507     // If the RHS of the sub is a XOR with one use and a constant, invert the
16508     // immediate. Then add one to the LHS of the sub so we can turn
16509     // X-Y -> X+~Y+1, saving one register.
16510     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16511         isa<ConstantSDNode>(Op1.getOperand(1))) {
16512       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16513       EVT VT = Op0.getValueType();
16514       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16515                                    Op1.getOperand(0),
16516                                    DAG.getConstant(~XorC, VT));
16517       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16518                          DAG.getConstant(C->getAPIntValue()+1, VT));
16519     }
16520   }
16521
16522   // Try to synthesize horizontal adds from adds of shuffles.
16523   EVT VT = N->getValueType(0);
16524   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16525        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16526       isHorizontalBinOp(Op0, Op1, true))
16527     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16528
16529   return OptimizeConditionalInDecrement(N, DAG);
16530 }
16531
16532 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16533                                              DAGCombinerInfo &DCI) const {
16534   SelectionDAG &DAG = DCI.DAG;
16535   switch (N->getOpcode()) {
16536   default: break;
16537   case ISD::EXTRACT_VECTOR_ELT:
16538     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16539   case ISD::VSELECT:
16540   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16541   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16542   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16543   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16544   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16545   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16546   case ISD::SHL:
16547   case ISD::SRA:
16548   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16549   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16550   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16551   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16552   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16553   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16554   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16555   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16556   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16557   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16558   case X86ISD::FXOR:
16559   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16560   case X86ISD::FMIN:
16561   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16562   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16563   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16564   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16565   case ISD::ANY_EXTEND:
16566   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16567   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16568   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16569   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16570   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16571   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16572   case X86ISD::SHUFP:       // Handle all target specific shuffles
16573   case X86ISD::PALIGN:
16574   case X86ISD::UNPCKH:
16575   case X86ISD::UNPCKL:
16576   case X86ISD::MOVHLPS:
16577   case X86ISD::MOVLHPS:
16578   case X86ISD::PSHUFD:
16579   case X86ISD::PSHUFHW:
16580   case X86ISD::PSHUFLW:
16581   case X86ISD::MOVSS:
16582   case X86ISD::MOVSD:
16583   case X86ISD::VPERMILP:
16584   case X86ISD::VPERM2X128:
16585   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16586   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16587   }
16588
16589   return SDValue();
16590 }
16591
16592 /// isTypeDesirableForOp - Return true if the target has native support for
16593 /// the specified value type and it is 'desirable' to use the type for the
16594 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16595 /// instruction encodings are longer and some i16 instructions are slow.
16596 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16597   if (!isTypeLegal(VT))
16598     return false;
16599   if (VT != MVT::i16)
16600     return true;
16601
16602   switch (Opc) {
16603   default:
16604     return true;
16605   case ISD::LOAD:
16606   case ISD::SIGN_EXTEND:
16607   case ISD::ZERO_EXTEND:
16608   case ISD::ANY_EXTEND:
16609   case ISD::SHL:
16610   case ISD::SRL:
16611   case ISD::SUB:
16612   case ISD::ADD:
16613   case ISD::MUL:
16614   case ISD::AND:
16615   case ISD::OR:
16616   case ISD::XOR:
16617     return false;
16618   }
16619 }
16620
16621 /// IsDesirableToPromoteOp - This method query the target whether it is
16622 /// beneficial for dag combiner to promote the specified node. If true, it
16623 /// should return the desired promotion type by reference.
16624 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16625   EVT VT = Op.getValueType();
16626   if (VT != MVT::i16)
16627     return false;
16628
16629   bool Promote = false;
16630   bool Commute = false;
16631   switch (Op.getOpcode()) {
16632   default: break;
16633   case ISD::LOAD: {
16634     LoadSDNode *LD = cast<LoadSDNode>(Op);
16635     // If the non-extending load has a single use and it's not live out, then it
16636     // might be folded.
16637     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16638                                                      Op.hasOneUse()*/) {
16639       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16640              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16641         // The only case where we'd want to promote LOAD (rather then it being
16642         // promoted as an operand is when it's only use is liveout.
16643         if (UI->getOpcode() != ISD::CopyToReg)
16644           return false;
16645       }
16646     }
16647     Promote = true;
16648     break;
16649   }
16650   case ISD::SIGN_EXTEND:
16651   case ISD::ZERO_EXTEND:
16652   case ISD::ANY_EXTEND:
16653     Promote = true;
16654     break;
16655   case ISD::SHL:
16656   case ISD::SRL: {
16657     SDValue N0 = Op.getOperand(0);
16658     // Look out for (store (shl (load), x)).
16659     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16660       return false;
16661     Promote = true;
16662     break;
16663   }
16664   case ISD::ADD:
16665   case ISD::MUL:
16666   case ISD::AND:
16667   case ISD::OR:
16668   case ISD::XOR:
16669     Commute = true;
16670     // fallthrough
16671   case ISD::SUB: {
16672     SDValue N0 = Op.getOperand(0);
16673     SDValue N1 = Op.getOperand(1);
16674     if (!Commute && MayFoldLoad(N1))
16675       return false;
16676     // Avoid disabling potential load folding opportunities.
16677     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16678       return false;
16679     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16680       return false;
16681     Promote = true;
16682   }
16683   }
16684
16685   PVT = MVT::i32;
16686   return Promote;
16687 }
16688
16689 //===----------------------------------------------------------------------===//
16690 //                           X86 Inline Assembly Support
16691 //===----------------------------------------------------------------------===//
16692
16693 namespace {
16694   // Helper to match a string separated by whitespace.
16695   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16696     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16697
16698     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16699       StringRef piece(*args[i]);
16700       if (!s.startswith(piece)) // Check if the piece matches.
16701         return false;
16702
16703       s = s.substr(piece.size());
16704       StringRef::size_type pos = s.find_first_not_of(" \t");
16705       if (pos == 0) // We matched a prefix.
16706         return false;
16707
16708       s = s.substr(pos);
16709     }
16710
16711     return s.empty();
16712   }
16713   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16714 }
16715
16716 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16717   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16718
16719   std::string AsmStr = IA->getAsmString();
16720
16721   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16722   if (!Ty || Ty->getBitWidth() % 16 != 0)
16723     return false;
16724
16725   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16726   SmallVector<StringRef, 4> AsmPieces;
16727   SplitString(AsmStr, AsmPieces, ";\n");
16728
16729   switch (AsmPieces.size()) {
16730   default: return false;
16731   case 1:
16732     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16733     // we will turn this bswap into something that will be lowered to logical
16734     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16735     // lower so don't worry about this.
16736     // bswap $0
16737     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16738         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16739         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16740         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16741         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16742         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16743       // No need to check constraints, nothing other than the equivalent of
16744       // "=r,0" would be valid here.
16745       return IntrinsicLowering::LowerToByteSwap(CI);
16746     }
16747
16748     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16749     if (CI->getType()->isIntegerTy(16) &&
16750         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16751         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16752          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16753       AsmPieces.clear();
16754       const std::string &ConstraintsStr = IA->getConstraintString();
16755       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16756       std::sort(AsmPieces.begin(), AsmPieces.end());
16757       if (AsmPieces.size() == 4 &&
16758           AsmPieces[0] == "~{cc}" &&
16759           AsmPieces[1] == "~{dirflag}" &&
16760           AsmPieces[2] == "~{flags}" &&
16761           AsmPieces[3] == "~{fpsr}")
16762       return IntrinsicLowering::LowerToByteSwap(CI);
16763     }
16764     break;
16765   case 3:
16766     if (CI->getType()->isIntegerTy(32) &&
16767         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16768         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16769         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16770         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16771       AsmPieces.clear();
16772       const std::string &ConstraintsStr = IA->getConstraintString();
16773       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16774       std::sort(AsmPieces.begin(), AsmPieces.end());
16775       if (AsmPieces.size() == 4 &&
16776           AsmPieces[0] == "~{cc}" &&
16777           AsmPieces[1] == "~{dirflag}" &&
16778           AsmPieces[2] == "~{flags}" &&
16779           AsmPieces[3] == "~{fpsr}")
16780         return IntrinsicLowering::LowerToByteSwap(CI);
16781     }
16782
16783     if (CI->getType()->isIntegerTy(64)) {
16784       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16785       if (Constraints.size() >= 2 &&
16786           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16787           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16788         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16789         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16790             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16791             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16792           return IntrinsicLowering::LowerToByteSwap(CI);
16793       }
16794     }
16795     break;
16796   }
16797   return false;
16798 }
16799
16800
16801
16802 /// getConstraintType - Given a constraint letter, return the type of
16803 /// constraint it is for this target.
16804 X86TargetLowering::ConstraintType
16805 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16806   if (Constraint.size() == 1) {
16807     switch (Constraint[0]) {
16808     case 'R':
16809     case 'q':
16810     case 'Q':
16811     case 'f':
16812     case 't':
16813     case 'u':
16814     case 'y':
16815     case 'x':
16816     case 'Y':
16817     case 'l':
16818       return C_RegisterClass;
16819     case 'a':
16820     case 'b':
16821     case 'c':
16822     case 'd':
16823     case 'S':
16824     case 'D':
16825     case 'A':
16826       return C_Register;
16827     case 'I':
16828     case 'J':
16829     case 'K':
16830     case 'L':
16831     case 'M':
16832     case 'N':
16833     case 'G':
16834     case 'C':
16835     case 'e':
16836     case 'Z':
16837       return C_Other;
16838     default:
16839       break;
16840     }
16841   }
16842   return TargetLowering::getConstraintType(Constraint);
16843 }
16844
16845 /// Examine constraint type and operand type and determine a weight value.
16846 /// This object must already have been set up with the operand type
16847 /// and the current alternative constraint selected.
16848 TargetLowering::ConstraintWeight
16849   X86TargetLowering::getSingleConstraintMatchWeight(
16850     AsmOperandInfo &info, const char *constraint) const {
16851   ConstraintWeight weight = CW_Invalid;
16852   Value *CallOperandVal = info.CallOperandVal;
16853     // If we don't have a value, we can't do a match,
16854     // but allow it at the lowest weight.
16855   if (CallOperandVal == NULL)
16856     return CW_Default;
16857   Type *type = CallOperandVal->getType();
16858   // Look at the constraint type.
16859   switch (*constraint) {
16860   default:
16861     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16862   case 'R':
16863   case 'q':
16864   case 'Q':
16865   case 'a':
16866   case 'b':
16867   case 'c':
16868   case 'd':
16869   case 'S':
16870   case 'D':
16871   case 'A':
16872     if (CallOperandVal->getType()->isIntegerTy())
16873       weight = CW_SpecificReg;
16874     break;
16875   case 'f':
16876   case 't':
16877   case 'u':
16878       if (type->isFloatingPointTy())
16879         weight = CW_SpecificReg;
16880       break;
16881   case 'y':
16882       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16883         weight = CW_SpecificReg;
16884       break;
16885   case 'x':
16886   case 'Y':
16887     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16888         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16889       weight = CW_Register;
16890     break;
16891   case 'I':
16892     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16893       if (C->getZExtValue() <= 31)
16894         weight = CW_Constant;
16895     }
16896     break;
16897   case 'J':
16898     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16899       if (C->getZExtValue() <= 63)
16900         weight = CW_Constant;
16901     }
16902     break;
16903   case 'K':
16904     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16905       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16906         weight = CW_Constant;
16907     }
16908     break;
16909   case 'L':
16910     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16911       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16912         weight = CW_Constant;
16913     }
16914     break;
16915   case 'M':
16916     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16917       if (C->getZExtValue() <= 3)
16918         weight = CW_Constant;
16919     }
16920     break;
16921   case 'N':
16922     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16923       if (C->getZExtValue() <= 0xff)
16924         weight = CW_Constant;
16925     }
16926     break;
16927   case 'G':
16928   case 'C':
16929     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16930       weight = CW_Constant;
16931     }
16932     break;
16933   case 'e':
16934     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16935       if ((C->getSExtValue() >= -0x80000000LL) &&
16936           (C->getSExtValue() <= 0x7fffffffLL))
16937         weight = CW_Constant;
16938     }
16939     break;
16940   case 'Z':
16941     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16942       if (C->getZExtValue() <= 0xffffffff)
16943         weight = CW_Constant;
16944     }
16945     break;
16946   }
16947   return weight;
16948 }
16949
16950 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16951 /// with another that has more specific requirements based on the type of the
16952 /// corresponding operand.
16953 const char *X86TargetLowering::
16954 LowerXConstraint(EVT ConstraintVT) const {
16955   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16956   // 'f' like normal targets.
16957   if (ConstraintVT.isFloatingPoint()) {
16958     if (Subtarget->hasSSE2())
16959       return "Y";
16960     if (Subtarget->hasSSE1())
16961       return "x";
16962   }
16963
16964   return TargetLowering::LowerXConstraint(ConstraintVT);
16965 }
16966
16967 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16968 /// vector.  If it is invalid, don't add anything to Ops.
16969 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16970                                                      std::string &Constraint,
16971                                                      std::vector<SDValue>&Ops,
16972                                                      SelectionDAG &DAG) const {
16973   SDValue Result(0, 0);
16974
16975   // Only support length 1 constraints for now.
16976   if (Constraint.length() > 1) return;
16977
16978   char ConstraintLetter = Constraint[0];
16979   switch (ConstraintLetter) {
16980   default: break;
16981   case 'I':
16982     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16983       if (C->getZExtValue() <= 31) {
16984         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16985         break;
16986       }
16987     }
16988     return;
16989   case 'J':
16990     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16991       if (C->getZExtValue() <= 63) {
16992         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16993         break;
16994       }
16995     }
16996     return;
16997   case 'K':
16998     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16999       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17000         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17001         break;
17002       }
17003     }
17004     return;
17005   case 'N':
17006     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17007       if (C->getZExtValue() <= 255) {
17008         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17009         break;
17010       }
17011     }
17012     return;
17013   case 'e': {
17014     // 32-bit signed value
17015     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17016       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17017                                            C->getSExtValue())) {
17018         // Widen to 64 bits here to get it sign extended.
17019         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17020         break;
17021       }
17022     // FIXME gcc accepts some relocatable values here too, but only in certain
17023     // memory models; it's complicated.
17024     }
17025     return;
17026   }
17027   case 'Z': {
17028     // 32-bit unsigned value
17029     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17030       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17031                                            C->getZExtValue())) {
17032         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17033         break;
17034       }
17035     }
17036     // FIXME gcc accepts some relocatable values here too, but only in certain
17037     // memory models; it's complicated.
17038     return;
17039   }
17040   case 'i': {
17041     // Literal immediates are always ok.
17042     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17043       // Widen to 64 bits here to get it sign extended.
17044       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17045       break;
17046     }
17047
17048     // In any sort of PIC mode addresses need to be computed at runtime by
17049     // adding in a register or some sort of table lookup.  These can't
17050     // be used as immediates.
17051     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17052       return;
17053
17054     // If we are in non-pic codegen mode, we allow the address of a global (with
17055     // an optional displacement) to be used with 'i'.
17056     GlobalAddressSDNode *GA = 0;
17057     int64_t Offset = 0;
17058
17059     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17060     while (1) {
17061       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17062         Offset += GA->getOffset();
17063         break;
17064       } else if (Op.getOpcode() == ISD::ADD) {
17065         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17066           Offset += C->getZExtValue();
17067           Op = Op.getOperand(0);
17068           continue;
17069         }
17070       } else if (Op.getOpcode() == ISD::SUB) {
17071         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17072           Offset += -C->getZExtValue();
17073           Op = Op.getOperand(0);
17074           continue;
17075         }
17076       }
17077
17078       // Otherwise, this isn't something we can handle, reject it.
17079       return;
17080     }
17081
17082     const GlobalValue *GV = GA->getGlobal();
17083     // If we require an extra load to get this address, as in PIC mode, we
17084     // can't accept it.
17085     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17086                                                         getTargetMachine())))
17087       return;
17088
17089     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17090                                         GA->getValueType(0), Offset);
17091     break;
17092   }
17093   }
17094
17095   if (Result.getNode()) {
17096     Ops.push_back(Result);
17097     return;
17098   }
17099   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17100 }
17101
17102 std::pair<unsigned, const TargetRegisterClass*>
17103 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17104                                                 EVT VT) const {
17105   // First, see if this is a constraint that directly corresponds to an LLVM
17106   // register class.
17107   if (Constraint.size() == 1) {
17108     // GCC Constraint Letters
17109     switch (Constraint[0]) {
17110     default: break;
17111       // TODO: Slight differences here in allocation order and leaving
17112       // RIP in the class. Do they matter any more here than they do
17113       // in the normal allocation?
17114     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17115       if (Subtarget->is64Bit()) {
17116         if (VT == MVT::i32 || VT == MVT::f32)
17117           return std::make_pair(0U, &X86::GR32RegClass);
17118         if (VT == MVT::i16)
17119           return std::make_pair(0U, &X86::GR16RegClass);
17120         if (VT == MVT::i8 || VT == MVT::i1)
17121           return std::make_pair(0U, &X86::GR8RegClass);
17122         if (VT == MVT::i64 || VT == MVT::f64)
17123           return std::make_pair(0U, &X86::GR64RegClass);
17124         break;
17125       }
17126       // 32-bit fallthrough
17127     case 'Q':   // Q_REGS
17128       if (VT == MVT::i32 || VT == MVT::f32)
17129         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17130       if (VT == MVT::i16)
17131         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17132       if (VT == MVT::i8 || VT == MVT::i1)
17133         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17134       if (VT == MVT::i64)
17135         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17136       break;
17137     case 'r':   // GENERAL_REGS
17138     case 'l':   // INDEX_REGS
17139       if (VT == MVT::i8 || VT == MVT::i1)
17140         return std::make_pair(0U, &X86::GR8RegClass);
17141       if (VT == MVT::i16)
17142         return std::make_pair(0U, &X86::GR16RegClass);
17143       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17144         return std::make_pair(0U, &X86::GR32RegClass);
17145       return std::make_pair(0U, &X86::GR64RegClass);
17146     case 'R':   // LEGACY_REGS
17147       if (VT == MVT::i8 || VT == MVT::i1)
17148         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17149       if (VT == MVT::i16)
17150         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17151       if (VT == MVT::i32 || !Subtarget->is64Bit())
17152         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17153       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17154     case 'f':  // FP Stack registers.
17155       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17156       // value to the correct fpstack register class.
17157       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17158         return std::make_pair(0U, &X86::RFP32RegClass);
17159       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17160         return std::make_pair(0U, &X86::RFP64RegClass);
17161       return std::make_pair(0U, &X86::RFP80RegClass);
17162     case 'y':   // MMX_REGS if MMX allowed.
17163       if (!Subtarget->hasMMX()) break;
17164       return std::make_pair(0U, &X86::VR64RegClass);
17165     case 'Y':   // SSE_REGS if SSE2 allowed
17166       if (!Subtarget->hasSSE2()) break;
17167       // FALL THROUGH.
17168     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17169       if (!Subtarget->hasSSE1()) break;
17170
17171       switch (VT.getSimpleVT().SimpleTy) {
17172       default: break;
17173       // Scalar SSE types.
17174       case MVT::f32:
17175       case MVT::i32:
17176         return std::make_pair(0U, &X86::FR32RegClass);
17177       case MVT::f64:
17178       case MVT::i64:
17179         return std::make_pair(0U, &X86::FR64RegClass);
17180       // Vector types.
17181       case MVT::v16i8:
17182       case MVT::v8i16:
17183       case MVT::v4i32:
17184       case MVT::v2i64:
17185       case MVT::v4f32:
17186       case MVT::v2f64:
17187         return std::make_pair(0U, &X86::VR128RegClass);
17188       // AVX types.
17189       case MVT::v32i8:
17190       case MVT::v16i16:
17191       case MVT::v8i32:
17192       case MVT::v4i64:
17193       case MVT::v8f32:
17194       case MVT::v4f64:
17195         return std::make_pair(0U, &X86::VR256RegClass);
17196       }
17197       break;
17198     }
17199   }
17200
17201   // Use the default implementation in TargetLowering to convert the register
17202   // constraint into a member of a register class.
17203   std::pair<unsigned, const TargetRegisterClass*> Res;
17204   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17205
17206   // Not found as a standard register?
17207   if (Res.second == 0) {
17208     // Map st(0) -> st(7) -> ST0
17209     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17210         tolower(Constraint[1]) == 's' &&
17211         tolower(Constraint[2]) == 't' &&
17212         Constraint[3] == '(' &&
17213         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17214         Constraint[5] == ')' &&
17215         Constraint[6] == '}') {
17216
17217       Res.first = X86::ST0+Constraint[4]-'0';
17218       Res.second = &X86::RFP80RegClass;
17219       return Res;
17220     }
17221
17222     // GCC allows "st(0)" to be called just plain "st".
17223     if (StringRef("{st}").equals_lower(Constraint)) {
17224       Res.first = X86::ST0;
17225       Res.second = &X86::RFP80RegClass;
17226       return Res;
17227     }
17228
17229     // flags -> EFLAGS
17230     if (StringRef("{flags}").equals_lower(Constraint)) {
17231       Res.first = X86::EFLAGS;
17232       Res.second = &X86::CCRRegClass;
17233       return Res;
17234     }
17235
17236     // 'A' means EAX + EDX.
17237     if (Constraint == "A") {
17238       Res.first = X86::EAX;
17239       Res.second = &X86::GR32_ADRegClass;
17240       return Res;
17241     }
17242     return Res;
17243   }
17244
17245   // Otherwise, check to see if this is a register class of the wrong value
17246   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17247   // turn into {ax},{dx}.
17248   if (Res.second->hasType(VT))
17249     return Res;   // Correct type already, nothing to do.
17250
17251   // All of the single-register GCC register classes map their values onto
17252   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17253   // really want an 8-bit or 32-bit register, map to the appropriate register
17254   // class and return the appropriate register.
17255   if (Res.second == &X86::GR16RegClass) {
17256     if (VT == MVT::i8) {
17257       unsigned DestReg = 0;
17258       switch (Res.first) {
17259       default: break;
17260       case X86::AX: DestReg = X86::AL; break;
17261       case X86::DX: DestReg = X86::DL; break;
17262       case X86::CX: DestReg = X86::CL; break;
17263       case X86::BX: DestReg = X86::BL; break;
17264       }
17265       if (DestReg) {
17266         Res.first = DestReg;
17267         Res.second = &X86::GR8RegClass;
17268       }
17269     } else if (VT == MVT::i32) {
17270       unsigned DestReg = 0;
17271       switch (Res.first) {
17272       default: break;
17273       case X86::AX: DestReg = X86::EAX; break;
17274       case X86::DX: DestReg = X86::EDX; break;
17275       case X86::CX: DestReg = X86::ECX; break;
17276       case X86::BX: DestReg = X86::EBX; break;
17277       case X86::SI: DestReg = X86::ESI; break;
17278       case X86::DI: DestReg = X86::EDI; break;
17279       case X86::BP: DestReg = X86::EBP; break;
17280       case X86::SP: DestReg = X86::ESP; break;
17281       }
17282       if (DestReg) {
17283         Res.first = DestReg;
17284         Res.second = &X86::GR32RegClass;
17285       }
17286     } else if (VT == MVT::i64) {
17287       unsigned DestReg = 0;
17288       switch (Res.first) {
17289       default: break;
17290       case X86::AX: DestReg = X86::RAX; break;
17291       case X86::DX: DestReg = X86::RDX; break;
17292       case X86::CX: DestReg = X86::RCX; break;
17293       case X86::BX: DestReg = X86::RBX; break;
17294       case X86::SI: DestReg = X86::RSI; break;
17295       case X86::DI: DestReg = X86::RDI; break;
17296       case X86::BP: DestReg = X86::RBP; break;
17297       case X86::SP: DestReg = X86::RSP; break;
17298       }
17299       if (DestReg) {
17300         Res.first = DestReg;
17301         Res.second = &X86::GR64RegClass;
17302       }
17303     }
17304   } else if (Res.second == &X86::FR32RegClass ||
17305              Res.second == &X86::FR64RegClass ||
17306              Res.second == &X86::VR128RegClass) {
17307     // Handle references to XMM physical registers that got mapped into the
17308     // wrong class.  This can happen with constraints like {xmm0} where the
17309     // target independent register mapper will just pick the first match it can
17310     // find, ignoring the required type.
17311
17312     if (VT == MVT::f32 || VT == MVT::i32)
17313       Res.second = &X86::FR32RegClass;
17314     else if (VT == MVT::f64 || VT == MVT::i64)
17315       Res.second = &X86::FR64RegClass;
17316     else if (X86::VR128RegClass.hasType(VT))
17317       Res.second = &X86::VR128RegClass;
17318     else if (X86::VR256RegClass.hasType(VT))
17319       Res.second = &X86::VR256RegClass;
17320   }
17321
17322   return Res;
17323 }