3667ff91be34db43a72472df65bf7ebd5856f83c
[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 // Reduce a vector shuffle to zext.
6566 SDValue
6567 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6568   // PMOVZX is only available from SSE41.
6569   if (!Subtarget->hasSSE41())
6570     return SDValue();
6571
6572   EVT VT = Op.getValueType();
6573
6574   // Only AVX2 support 256-bit vector integer extending.
6575   if (!Subtarget->hasAVX2() && VT.is256BitVector())
6576     return SDValue();
6577
6578   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6579   DebugLoc DL = Op.getDebugLoc();
6580   SDValue V1 = Op.getOperand(0);
6581   SDValue V2 = Op.getOperand(1);
6582   unsigned NumElems = VT.getVectorNumElements();
6583
6584   // Extending is an unary operation and the element type of the source vector
6585   // won't be equal to or larger than i64.
6586   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6587       VT.getVectorElementType() == MVT::i64)
6588     return SDValue();
6589
6590   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6591   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6592   while ((1 << Shift) < NumElems) {
6593     if (SVOp->getMaskElt(1 << Shift) == 1)
6594       break;
6595     Shift += 1;
6596     // The maximal ratio is 8, i.e. from i8 to i64.
6597     if (Shift > 3)
6598       return SDValue();
6599   }
6600
6601   // Check the shuffle mask.
6602   unsigned Mask = (1U << Shift) - 1;
6603   for (unsigned i = 0; i != NumElems; ++i) {
6604     int EltIdx = SVOp->getMaskElt(i);
6605     if ((i & Mask) != 0 && EltIdx != -1)
6606       return SDValue();
6607     if ((i & Mask) == 0 && EltIdx != (i >> Shift))
6608       return SDValue();
6609   }
6610
6611   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6612   EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6613   EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6614
6615   if (!isTypeLegal(NVT))
6616     return SDValue();
6617
6618   // Simplify the operand as it's prepared to be fed into shuffle.
6619   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6620   if (V1.getOpcode() == ISD::BITCAST &&
6621       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6622       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6623       V1.getOperand(0)
6624         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6625     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6626     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6627     // If it's foldable, i.e. normal load with single use, we will let code
6628     // selection to fold it. Otherwise, we will short the conversion sequence.
6629     if (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())
6630       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6631   }
6632
6633   return DAG.getNode(ISD::BITCAST, DL, VT,
6634                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6635 }
6636
6637 SDValue
6638 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6639   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6640   EVT VT = Op.getValueType();
6641   DebugLoc dl = Op.getDebugLoc();
6642   SDValue V1 = Op.getOperand(0);
6643   SDValue V2 = Op.getOperand(1);
6644
6645   if (isZeroShuffle(SVOp))
6646     return getZeroVector(VT, Subtarget, DAG, dl);
6647
6648   // Handle splat operations
6649   if (SVOp->isSplat()) {
6650     unsigned NumElem = VT.getVectorNumElements();
6651     int Size = VT.getSizeInBits();
6652
6653     // Use vbroadcast whenever the splat comes from a foldable load
6654     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6655     if (Broadcast.getNode())
6656       return Broadcast;
6657
6658     // Handle splats by matching through known shuffle masks
6659     if ((Size == 128 && NumElem <= 4) ||
6660         (Size == 256 && NumElem < 8))
6661       return SDValue();
6662
6663     // All remaning splats are promoted to target supported vector shuffles.
6664     return PromoteSplat(SVOp, DAG);
6665   }
6666
6667   // Check integer expanding shuffles.
6668   SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6669   if (NewOp.getNode())
6670     return NewOp;
6671
6672   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6673   // do it!
6674   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6675       VT == MVT::v16i16 || VT == MVT::v32i8) {
6676     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6677     if (NewOp.getNode())
6678       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6679   } else if ((VT == MVT::v4i32 ||
6680              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6681     // FIXME: Figure out a cleaner way to do this.
6682     // Try to make use of movq to zero out the top part.
6683     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6684       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6685       if (NewOp.getNode()) {
6686         EVT NewVT = NewOp.getValueType();
6687         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6688                                NewVT, true, false))
6689           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6690                               DAG, Subtarget, dl);
6691       }
6692     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6693       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694       if (NewOp.getNode()) {
6695         EVT NewVT = NewOp.getValueType();
6696         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6697           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6698                               DAG, Subtarget, dl);
6699       }
6700     }
6701   }
6702   return SDValue();
6703 }
6704
6705 SDValue
6706 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6707   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6708   SDValue V1 = Op.getOperand(0);
6709   SDValue V2 = Op.getOperand(1);
6710   EVT VT = Op.getValueType();
6711   DebugLoc dl = Op.getDebugLoc();
6712   unsigned NumElems = VT.getVectorNumElements();
6713   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6714   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6715   bool V1IsSplat = false;
6716   bool V2IsSplat = false;
6717   bool HasSSE2 = Subtarget->hasSSE2();
6718   bool HasAVX    = Subtarget->hasAVX();
6719   bool HasAVX2   = Subtarget->hasAVX2();
6720   MachineFunction &MF = DAG.getMachineFunction();
6721   bool OptForSize = MF.getFunction()->getFnAttributes().
6722     hasAttribute(Attributes::OptimizeForSize);
6723
6724   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6725
6726   if (V1IsUndef && V2IsUndef)
6727     return DAG.getUNDEF(VT);
6728
6729   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6730
6731   // Vector shuffle lowering takes 3 steps:
6732   //
6733   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6734   //    narrowing and commutation of operands should be handled.
6735   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6736   //    shuffle nodes.
6737   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6738   //    so the shuffle can be broken into other shuffles and the legalizer can
6739   //    try the lowering again.
6740   //
6741   // The general idea is that no vector_shuffle operation should be left to
6742   // be matched during isel, all of them must be converted to a target specific
6743   // node here.
6744
6745   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6746   // narrowing and commutation of operands should be handled. The actual code
6747   // doesn't include all of those, work in progress...
6748   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6749   if (NewOp.getNode())
6750     return NewOp;
6751
6752   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6753
6754   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6755   // unpckh_undef). Only use pshufd if speed is more important than size.
6756   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6757     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6758   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6759     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6760
6761   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6762       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6763     return getMOVDDup(Op, dl, V1, DAG);
6764
6765   if (isMOVHLPS_v_undef_Mask(M, VT))
6766     return getMOVHighToLow(Op, dl, DAG);
6767
6768   // Use to match splats
6769   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6770       (VT == MVT::v2f64 || VT == MVT::v2i64))
6771     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6772
6773   if (isPSHUFDMask(M, VT)) {
6774     // The actual implementation will match the mask in the if above and then
6775     // during isel it can match several different instructions, not only pshufd
6776     // as its name says, sad but true, emulate the behavior for now...
6777     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6778       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6779
6780     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6781
6782     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6783       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6784
6785     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6786       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6787
6788     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6789                                 TargetMask, DAG);
6790   }
6791
6792   // Check if this can be converted into a logical shift.
6793   bool isLeft = false;
6794   unsigned ShAmt = 0;
6795   SDValue ShVal;
6796   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6797   if (isShift && ShVal.hasOneUse()) {
6798     // If the shifted value has multiple uses, it may be cheaper to use
6799     // v_set0 + movlhps or movhlps, etc.
6800     EVT EltVT = VT.getVectorElementType();
6801     ShAmt *= EltVT.getSizeInBits();
6802     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6803   }
6804
6805   if (isMOVLMask(M, VT)) {
6806     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6807       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6808     if (!isMOVLPMask(M, VT)) {
6809       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6810         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6811
6812       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6813         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6814     }
6815   }
6816
6817   // FIXME: fold these into legal mask.
6818   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6819     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6820
6821   if (isMOVHLPSMask(M, VT))
6822     return getMOVHighToLow(Op, dl, DAG);
6823
6824   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6825     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6826
6827   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6828     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6829
6830   if (isMOVLPMask(M, VT))
6831     return getMOVLP(Op, dl, DAG, HasSSE2);
6832
6833   if (ShouldXformToMOVHLPS(M, VT) ||
6834       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6835     return CommuteVectorShuffle(SVOp, DAG);
6836
6837   if (isShift) {
6838     // No better options. Use a vshldq / vsrldq.
6839     EVT EltVT = VT.getVectorElementType();
6840     ShAmt *= EltVT.getSizeInBits();
6841     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6842   }
6843
6844   bool Commuted = false;
6845   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6846   // 1,1,1,1 -> v8i16 though.
6847   V1IsSplat = isSplatVector(V1.getNode());
6848   V2IsSplat = isSplatVector(V2.getNode());
6849
6850   // Canonicalize the splat or undef, if present, to be on the RHS.
6851   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6852     CommuteVectorShuffleMask(M, NumElems);
6853     std::swap(V1, V2);
6854     std::swap(V1IsSplat, V2IsSplat);
6855     Commuted = true;
6856   }
6857
6858   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6859     // Shuffling low element of v1 into undef, just return v1.
6860     if (V2IsUndef)
6861       return V1;
6862     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6863     // the instruction selector will not match, so get a canonical MOVL with
6864     // swapped operands to undo the commute.
6865     return getMOVL(DAG, dl, VT, V2, V1);
6866   }
6867
6868   if (isUNPCKLMask(M, VT, HasAVX2))
6869     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6870
6871   if (isUNPCKHMask(M, VT, HasAVX2))
6872     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6873
6874   if (V2IsSplat) {
6875     // Normalize mask so all entries that point to V2 points to its first
6876     // element then try to match unpck{h|l} again. If match, return a
6877     // new vector_shuffle with the corrected mask.p
6878     SmallVector<int, 8> NewMask(M.begin(), M.end());
6879     NormalizeMask(NewMask, NumElems);
6880     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6881       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6882     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6883       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6884   }
6885
6886   if (Commuted) {
6887     // Commute is back and try unpck* again.
6888     // FIXME: this seems wrong.
6889     CommuteVectorShuffleMask(M, NumElems);
6890     std::swap(V1, V2);
6891     std::swap(V1IsSplat, V2IsSplat);
6892     Commuted = false;
6893
6894     if (isUNPCKLMask(M, VT, HasAVX2))
6895       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6896
6897     if (isUNPCKHMask(M, VT, HasAVX2))
6898       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6899   }
6900
6901   // Normalize the node to match x86 shuffle ops if needed
6902   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6903     return CommuteVectorShuffle(SVOp, DAG);
6904
6905   // The checks below are all present in isShuffleMaskLegal, but they are
6906   // inlined here right now to enable us to directly emit target specific
6907   // nodes, and remove one by one until they don't return Op anymore.
6908
6909   if (isPALIGNRMask(M, VT, Subtarget))
6910     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6911                                 getShufflePALIGNRImmediate(SVOp),
6912                                 DAG);
6913
6914   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6915       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6916     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6917       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6918   }
6919
6920   if (isPSHUFHWMask(M, VT, HasAVX2))
6921     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6922                                 getShufflePSHUFHWImmediate(SVOp),
6923                                 DAG);
6924
6925   if (isPSHUFLWMask(M, VT, HasAVX2))
6926     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6927                                 getShufflePSHUFLWImmediate(SVOp),
6928                                 DAG);
6929
6930   if (isSHUFPMask(M, VT, HasAVX))
6931     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6932                                 getShuffleSHUFImmediate(SVOp), DAG);
6933
6934   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6935     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6936   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6937     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6938
6939   //===--------------------------------------------------------------------===//
6940   // Generate target specific nodes for 128 or 256-bit shuffles only
6941   // supported in the AVX instruction set.
6942   //
6943
6944   // Handle VMOVDDUPY permutations
6945   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6946     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6947
6948   // Handle VPERMILPS/D* permutations
6949   if (isVPERMILPMask(M, VT, HasAVX)) {
6950     if (HasAVX2 && VT == MVT::v8i32)
6951       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6952                                   getShuffleSHUFImmediate(SVOp), DAG);
6953     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6954                                 getShuffleSHUFImmediate(SVOp), DAG);
6955   }
6956
6957   // Handle VPERM2F128/VPERM2I128 permutations
6958   if (isVPERM2X128Mask(M, VT, HasAVX))
6959     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6960                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6961
6962   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6963   if (BlendOp.getNode())
6964     return BlendOp;
6965
6966   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6967     SmallVector<SDValue, 8> permclMask;
6968     for (unsigned i = 0; i != 8; ++i) {
6969       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6970     }
6971     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6972                                &permclMask[0], 8);
6973     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6974     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6975                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6976   }
6977
6978   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6979     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6980                                 getShuffleCLImmediate(SVOp), DAG);
6981
6982
6983   //===--------------------------------------------------------------------===//
6984   // Since no target specific shuffle was selected for this generic one,
6985   // lower it into other known shuffles. FIXME: this isn't true yet, but
6986   // this is the plan.
6987   //
6988
6989   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6990   if (VT == MVT::v8i16) {
6991     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6992     if (NewOp.getNode())
6993       return NewOp;
6994   }
6995
6996   if (VT == MVT::v16i8) {
6997     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6998     if (NewOp.getNode())
6999       return NewOp;
7000   }
7001
7002   if (VT == MVT::v32i8) {
7003     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7004     if (NewOp.getNode())
7005       return NewOp;
7006   }
7007
7008   // Handle all 128-bit wide vectors with 4 elements, and match them with
7009   // several different shuffle types.
7010   if (NumElems == 4 && VT.is128BitVector())
7011     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7012
7013   // Handle general 256-bit shuffles
7014   if (VT.is256BitVector())
7015     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7016
7017   return SDValue();
7018 }
7019
7020 SDValue
7021 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7022                                                 SelectionDAG &DAG) const {
7023   EVT VT = Op.getValueType();
7024   DebugLoc dl = Op.getDebugLoc();
7025
7026   if (!Op.getOperand(0).getValueType().is128BitVector())
7027     return SDValue();
7028
7029   if (VT.getSizeInBits() == 8) {
7030     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7031                                   Op.getOperand(0), Op.getOperand(1));
7032     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7033                                   DAG.getValueType(VT));
7034     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7035   }
7036
7037   if (VT.getSizeInBits() == 16) {
7038     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7039     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7040     if (Idx == 0)
7041       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7042                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7043                                      DAG.getNode(ISD::BITCAST, dl,
7044                                                  MVT::v4i32,
7045                                                  Op.getOperand(0)),
7046                                      Op.getOperand(1)));
7047     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7048                                   Op.getOperand(0), Op.getOperand(1));
7049     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7050                                   DAG.getValueType(VT));
7051     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7052   }
7053
7054   if (VT == MVT::f32) {
7055     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7056     // the result back to FR32 register. It's only worth matching if the
7057     // result has a single use which is a store or a bitcast to i32.  And in
7058     // the case of a store, it's not worth it if the index is a constant 0,
7059     // because a MOVSSmr can be used instead, which is smaller and faster.
7060     if (!Op.hasOneUse())
7061       return SDValue();
7062     SDNode *User = *Op.getNode()->use_begin();
7063     if ((User->getOpcode() != ISD::STORE ||
7064          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7065           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7066         (User->getOpcode() != ISD::BITCAST ||
7067          User->getValueType(0) != MVT::i32))
7068       return SDValue();
7069     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7070                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7071                                               Op.getOperand(0)),
7072                                               Op.getOperand(1));
7073     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7074   }
7075
7076   if (VT == MVT::i32 || VT == MVT::i64) {
7077     // ExtractPS/pextrq works with constant index.
7078     if (isa<ConstantSDNode>(Op.getOperand(1)))
7079       return Op;
7080   }
7081   return SDValue();
7082 }
7083
7084
7085 SDValue
7086 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7087                                            SelectionDAG &DAG) const {
7088   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7089     return SDValue();
7090
7091   SDValue Vec = Op.getOperand(0);
7092   EVT VecVT = Vec.getValueType();
7093
7094   // If this is a 256-bit vector result, first extract the 128-bit vector and
7095   // then extract the element from the 128-bit vector.
7096   if (VecVT.is256BitVector()) {
7097     DebugLoc dl = Op.getNode()->getDebugLoc();
7098     unsigned NumElems = VecVT.getVectorNumElements();
7099     SDValue Idx = Op.getOperand(1);
7100     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7101
7102     // Get the 128-bit vector.
7103     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7104
7105     if (IdxVal >= NumElems/2)
7106       IdxVal -= NumElems/2;
7107     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7108                        DAG.getConstant(IdxVal, MVT::i32));
7109   }
7110
7111   assert(VecVT.is128BitVector() && "Unexpected vector length");
7112
7113   if (Subtarget->hasSSE41()) {
7114     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7115     if (Res.getNode())
7116       return Res;
7117   }
7118
7119   EVT VT = Op.getValueType();
7120   DebugLoc dl = Op.getDebugLoc();
7121   // TODO: handle v16i8.
7122   if (VT.getSizeInBits() == 16) {
7123     SDValue Vec = Op.getOperand(0);
7124     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7125     if (Idx == 0)
7126       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7127                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7128                                      DAG.getNode(ISD::BITCAST, dl,
7129                                                  MVT::v4i32, Vec),
7130                                      Op.getOperand(1)));
7131     // Transform it so it match pextrw which produces a 32-bit result.
7132     EVT EltVT = MVT::i32;
7133     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7134                                   Op.getOperand(0), Op.getOperand(1));
7135     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7136                                   DAG.getValueType(VT));
7137     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7138   }
7139
7140   if (VT.getSizeInBits() == 32) {
7141     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7142     if (Idx == 0)
7143       return Op;
7144
7145     // SHUFPS the element to the lowest double word, then movss.
7146     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7147     EVT VVT = Op.getOperand(0).getValueType();
7148     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7149                                        DAG.getUNDEF(VVT), Mask);
7150     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7151                        DAG.getIntPtrConstant(0));
7152   }
7153
7154   if (VT.getSizeInBits() == 64) {
7155     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7156     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7157     //        to match extract_elt for f64.
7158     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7159     if (Idx == 0)
7160       return Op;
7161
7162     // UNPCKHPD the element to the lowest double word, then movsd.
7163     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7164     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7165     int Mask[2] = { 1, -1 };
7166     EVT VVT = Op.getOperand(0).getValueType();
7167     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7168                                        DAG.getUNDEF(VVT), Mask);
7169     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7170                        DAG.getIntPtrConstant(0));
7171   }
7172
7173   return SDValue();
7174 }
7175
7176 SDValue
7177 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7178                                                SelectionDAG &DAG) const {
7179   EVT VT = Op.getValueType();
7180   EVT EltVT = VT.getVectorElementType();
7181   DebugLoc dl = Op.getDebugLoc();
7182
7183   SDValue N0 = Op.getOperand(0);
7184   SDValue N1 = Op.getOperand(1);
7185   SDValue N2 = Op.getOperand(2);
7186
7187   if (!VT.is128BitVector())
7188     return SDValue();
7189
7190   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7191       isa<ConstantSDNode>(N2)) {
7192     unsigned Opc;
7193     if (VT == MVT::v8i16)
7194       Opc = X86ISD::PINSRW;
7195     else if (VT == MVT::v16i8)
7196       Opc = X86ISD::PINSRB;
7197     else
7198       Opc = X86ISD::PINSRB;
7199
7200     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7201     // argument.
7202     if (N1.getValueType() != MVT::i32)
7203       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7204     if (N2.getValueType() != MVT::i32)
7205       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7206     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7207   }
7208
7209   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7210     // Bits [7:6] of the constant are the source select.  This will always be
7211     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7212     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7213     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7214     // Bits [5:4] of the constant are the destination select.  This is the
7215     //  value of the incoming immediate.
7216     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7217     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7218     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7219     // Create this as a scalar to vector..
7220     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7221     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7222   }
7223
7224   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7225     // PINSR* works with constant index.
7226     return Op;
7227   }
7228   return SDValue();
7229 }
7230
7231 SDValue
7232 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7233   EVT VT = Op.getValueType();
7234   EVT EltVT = VT.getVectorElementType();
7235
7236   DebugLoc dl = Op.getDebugLoc();
7237   SDValue N0 = Op.getOperand(0);
7238   SDValue N1 = Op.getOperand(1);
7239   SDValue N2 = Op.getOperand(2);
7240
7241   // If this is a 256-bit vector result, first extract the 128-bit vector,
7242   // insert the element into the extracted half and then place it back.
7243   if (VT.is256BitVector()) {
7244     if (!isa<ConstantSDNode>(N2))
7245       return SDValue();
7246
7247     // Get the desired 128-bit vector half.
7248     unsigned NumElems = VT.getVectorNumElements();
7249     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7250     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7251
7252     // Insert the element into the desired half.
7253     bool Upper = IdxVal >= NumElems/2;
7254     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7255                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7256
7257     // Insert the changed part back to the 256-bit vector
7258     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7259   }
7260
7261   if (Subtarget->hasSSE41())
7262     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7263
7264   if (EltVT == MVT::i8)
7265     return SDValue();
7266
7267   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7268     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7269     // as its second argument.
7270     if (N1.getValueType() != MVT::i32)
7271       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7272     if (N2.getValueType() != MVT::i32)
7273       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7274     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7275   }
7276   return SDValue();
7277 }
7278
7279 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7280   LLVMContext *Context = DAG.getContext();
7281   DebugLoc dl = Op.getDebugLoc();
7282   EVT OpVT = Op.getValueType();
7283
7284   // If this is a 256-bit vector result, first insert into a 128-bit
7285   // vector and then insert into the 256-bit vector.
7286   if (!OpVT.is128BitVector()) {
7287     // Insert into a 128-bit vector.
7288     EVT VT128 = EVT::getVectorVT(*Context,
7289                                  OpVT.getVectorElementType(),
7290                                  OpVT.getVectorNumElements() / 2);
7291
7292     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7293
7294     // Insert the 128-bit vector.
7295     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7296   }
7297
7298   if (OpVT == MVT::v1i64 &&
7299       Op.getOperand(0).getValueType() == MVT::i64)
7300     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7301
7302   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7303   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7304   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7305                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7306 }
7307
7308 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7309 // a simple subregister reference or explicit instructions to grab
7310 // upper bits of a vector.
7311 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7312                                       SelectionDAG &DAG) {
7313   if (Subtarget->hasAVX()) {
7314     DebugLoc dl = Op.getNode()->getDebugLoc();
7315     SDValue Vec = Op.getNode()->getOperand(0);
7316     SDValue Idx = Op.getNode()->getOperand(1);
7317
7318     if (Op.getNode()->getValueType(0).is128BitVector() &&
7319         Vec.getNode()->getValueType(0).is256BitVector() &&
7320         isa<ConstantSDNode>(Idx)) {
7321       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7322       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7323     }
7324   }
7325   return SDValue();
7326 }
7327
7328 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7329 // simple superregister reference or explicit instructions to insert
7330 // the upper bits of a vector.
7331 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7332                                      SelectionDAG &DAG) {
7333   if (Subtarget->hasAVX()) {
7334     DebugLoc dl = Op.getNode()->getDebugLoc();
7335     SDValue Vec = Op.getNode()->getOperand(0);
7336     SDValue SubVec = Op.getNode()->getOperand(1);
7337     SDValue Idx = Op.getNode()->getOperand(2);
7338
7339     if (Op.getNode()->getValueType(0).is256BitVector() &&
7340         SubVec.getNode()->getValueType(0).is128BitVector() &&
7341         isa<ConstantSDNode>(Idx)) {
7342       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7343       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7344     }
7345   }
7346   return SDValue();
7347 }
7348
7349 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7350 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7351 // one of the above mentioned nodes. It has to be wrapped because otherwise
7352 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7353 // be used to form addressing mode. These wrapped nodes will be selected
7354 // into MOV32ri.
7355 SDValue
7356 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7357   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7358
7359   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7360   // global base reg.
7361   unsigned char OpFlag = 0;
7362   unsigned WrapperKind = X86ISD::Wrapper;
7363   CodeModel::Model M = getTargetMachine().getCodeModel();
7364
7365   if (Subtarget->isPICStyleRIPRel() &&
7366       (M == CodeModel::Small || M == CodeModel::Kernel))
7367     WrapperKind = X86ISD::WrapperRIP;
7368   else if (Subtarget->isPICStyleGOT())
7369     OpFlag = X86II::MO_GOTOFF;
7370   else if (Subtarget->isPICStyleStubPIC())
7371     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7372
7373   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7374                                              CP->getAlignment(),
7375                                              CP->getOffset(), OpFlag);
7376   DebugLoc DL = CP->getDebugLoc();
7377   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7378   // With PIC, the address is actually $g + Offset.
7379   if (OpFlag) {
7380     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7381                          DAG.getNode(X86ISD::GlobalBaseReg,
7382                                      DebugLoc(), getPointerTy()),
7383                          Result);
7384   }
7385
7386   return Result;
7387 }
7388
7389 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7390   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7391
7392   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7393   // global base reg.
7394   unsigned char OpFlag = 0;
7395   unsigned WrapperKind = X86ISD::Wrapper;
7396   CodeModel::Model M = getTargetMachine().getCodeModel();
7397
7398   if (Subtarget->isPICStyleRIPRel() &&
7399       (M == CodeModel::Small || M == CodeModel::Kernel))
7400     WrapperKind = X86ISD::WrapperRIP;
7401   else if (Subtarget->isPICStyleGOT())
7402     OpFlag = X86II::MO_GOTOFF;
7403   else if (Subtarget->isPICStyleStubPIC())
7404     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7405
7406   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7407                                           OpFlag);
7408   DebugLoc DL = JT->getDebugLoc();
7409   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7410
7411   // With PIC, the address is actually $g + Offset.
7412   if (OpFlag)
7413     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7414                          DAG.getNode(X86ISD::GlobalBaseReg,
7415                                      DebugLoc(), getPointerTy()),
7416                          Result);
7417
7418   return Result;
7419 }
7420
7421 SDValue
7422 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7423   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7424
7425   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7426   // global base reg.
7427   unsigned char OpFlag = 0;
7428   unsigned WrapperKind = X86ISD::Wrapper;
7429   CodeModel::Model M = getTargetMachine().getCodeModel();
7430
7431   if (Subtarget->isPICStyleRIPRel() &&
7432       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7433     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7434       OpFlag = X86II::MO_GOTPCREL;
7435     WrapperKind = X86ISD::WrapperRIP;
7436   } else if (Subtarget->isPICStyleGOT()) {
7437     OpFlag = X86II::MO_GOT;
7438   } else if (Subtarget->isPICStyleStubPIC()) {
7439     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7440   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7441     OpFlag = X86II::MO_DARWIN_NONLAZY;
7442   }
7443
7444   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7445
7446   DebugLoc DL = Op.getDebugLoc();
7447   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7448
7449
7450   // With PIC, the address is actually $g + Offset.
7451   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7452       !Subtarget->is64Bit()) {
7453     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7454                          DAG.getNode(X86ISD::GlobalBaseReg,
7455                                      DebugLoc(), getPointerTy()),
7456                          Result);
7457   }
7458
7459   // For symbols that require a load from a stub to get the address, emit the
7460   // load.
7461   if (isGlobalStubReference(OpFlag))
7462     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7463                          MachinePointerInfo::getGOT(), false, false, false, 0);
7464
7465   return Result;
7466 }
7467
7468 SDValue
7469 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7470   // Create the TargetBlockAddressAddress node.
7471   unsigned char OpFlags =
7472     Subtarget->ClassifyBlockAddressReference();
7473   CodeModel::Model M = getTargetMachine().getCodeModel();
7474   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7475   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7476   DebugLoc dl = Op.getDebugLoc();
7477   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7478                                              OpFlags);
7479
7480   if (Subtarget->isPICStyleRIPRel() &&
7481       (M == CodeModel::Small || M == CodeModel::Kernel))
7482     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7483   else
7484     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7485
7486   // With PIC, the address is actually $g + Offset.
7487   if (isGlobalRelativeToPICBase(OpFlags)) {
7488     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7489                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7490                          Result);
7491   }
7492
7493   return Result;
7494 }
7495
7496 SDValue
7497 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7498                                       int64_t Offset,
7499                                       SelectionDAG &DAG) const {
7500   // Create the TargetGlobalAddress node, folding in the constant
7501   // offset if it is legal.
7502   unsigned char OpFlags =
7503     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7504   CodeModel::Model M = getTargetMachine().getCodeModel();
7505   SDValue Result;
7506   if (OpFlags == X86II::MO_NO_FLAG &&
7507       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7508     // A direct static reference to a global.
7509     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7510     Offset = 0;
7511   } else {
7512     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7513   }
7514
7515   if (Subtarget->isPICStyleRIPRel() &&
7516       (M == CodeModel::Small || M == CodeModel::Kernel))
7517     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7518   else
7519     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7520
7521   // With PIC, the address is actually $g + Offset.
7522   if (isGlobalRelativeToPICBase(OpFlags)) {
7523     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7524                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7525                          Result);
7526   }
7527
7528   // For globals that require a load from a stub to get the address, emit the
7529   // load.
7530   if (isGlobalStubReference(OpFlags))
7531     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7532                          MachinePointerInfo::getGOT(), false, false, false, 0);
7533
7534   // If there was a non-zero offset that we didn't fold, create an explicit
7535   // addition for it.
7536   if (Offset != 0)
7537     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7538                          DAG.getConstant(Offset, getPointerTy()));
7539
7540   return Result;
7541 }
7542
7543 SDValue
7544 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7545   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7546   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7547   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7548 }
7549
7550 static SDValue
7551 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7552            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7553            unsigned char OperandFlags, bool LocalDynamic = false) {
7554   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7555   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7556   DebugLoc dl = GA->getDebugLoc();
7557   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7558                                            GA->getValueType(0),
7559                                            GA->getOffset(),
7560                                            OperandFlags);
7561
7562   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7563                                            : X86ISD::TLSADDR;
7564
7565   if (InFlag) {
7566     SDValue Ops[] = { Chain,  TGA, *InFlag };
7567     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7568   } else {
7569     SDValue Ops[]  = { Chain, TGA };
7570     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7571   }
7572
7573   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7574   MFI->setAdjustsStack(true);
7575
7576   SDValue Flag = Chain.getValue(1);
7577   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7578 }
7579
7580 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7581 static SDValue
7582 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7583                                 const EVT PtrVT) {
7584   SDValue InFlag;
7585   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7586   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7587                                    DAG.getNode(X86ISD::GlobalBaseReg,
7588                                                DebugLoc(), PtrVT), InFlag);
7589   InFlag = Chain.getValue(1);
7590
7591   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7592 }
7593
7594 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7595 static SDValue
7596 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7597                                 const EVT PtrVT) {
7598   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7599                     X86::RAX, X86II::MO_TLSGD);
7600 }
7601
7602 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7603                                            SelectionDAG &DAG,
7604                                            const EVT PtrVT,
7605                                            bool is64Bit) {
7606   DebugLoc dl = GA->getDebugLoc();
7607
7608   // Get the start address of the TLS block for this module.
7609   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7610       .getInfo<X86MachineFunctionInfo>();
7611   MFI->incNumLocalDynamicTLSAccesses();
7612
7613   SDValue Base;
7614   if (is64Bit) {
7615     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7616                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7617   } else {
7618     SDValue InFlag;
7619     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7620         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7621     InFlag = Chain.getValue(1);
7622     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7623                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7624   }
7625
7626   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7627   // of Base.
7628
7629   // Build x@dtpoff.
7630   unsigned char OperandFlags = X86II::MO_DTPOFF;
7631   unsigned WrapperKind = X86ISD::Wrapper;
7632   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7633                                            GA->getValueType(0),
7634                                            GA->getOffset(), OperandFlags);
7635   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7636
7637   // Add x@dtpoff with the base.
7638   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7639 }
7640
7641 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7642 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7643                                    const EVT PtrVT, TLSModel::Model model,
7644                                    bool is64Bit, bool isPIC) {
7645   DebugLoc dl = GA->getDebugLoc();
7646
7647   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7648   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7649                                                          is64Bit ? 257 : 256));
7650
7651   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7652                                       DAG.getIntPtrConstant(0),
7653                                       MachinePointerInfo(Ptr),
7654                                       false, false, false, 0);
7655
7656   unsigned char OperandFlags = 0;
7657   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7658   // initialexec.
7659   unsigned WrapperKind = X86ISD::Wrapper;
7660   if (model == TLSModel::LocalExec) {
7661     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7662   } else if (model == TLSModel::InitialExec) {
7663     if (is64Bit) {
7664       OperandFlags = X86II::MO_GOTTPOFF;
7665       WrapperKind = X86ISD::WrapperRIP;
7666     } else {
7667       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7668     }
7669   } else {
7670     llvm_unreachable("Unexpected model");
7671   }
7672
7673   // emit "addl x@ntpoff,%eax" (local exec)
7674   // or "addl x@indntpoff,%eax" (initial exec)
7675   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7676   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7677                                            GA->getValueType(0),
7678                                            GA->getOffset(), OperandFlags);
7679   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7680
7681   if (model == TLSModel::InitialExec) {
7682     if (isPIC && !is64Bit) {
7683       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7684                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7685                            Offset);
7686     }
7687
7688     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7689                          MachinePointerInfo::getGOT(), false, false, false,
7690                          0);
7691   }
7692
7693   // The address of the thread local variable is the add of the thread
7694   // pointer with the offset of the variable.
7695   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7696 }
7697
7698 SDValue
7699 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7700
7701   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7702   const GlobalValue *GV = GA->getGlobal();
7703
7704   if (Subtarget->isTargetELF()) {
7705     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7706
7707     switch (model) {
7708       case TLSModel::GeneralDynamic:
7709         if (Subtarget->is64Bit())
7710           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7711         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7712       case TLSModel::LocalDynamic:
7713         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7714                                            Subtarget->is64Bit());
7715       case TLSModel::InitialExec:
7716       case TLSModel::LocalExec:
7717         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7718                                    Subtarget->is64Bit(),
7719                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7720     }
7721     llvm_unreachable("Unknown TLS model.");
7722   }
7723
7724   if (Subtarget->isTargetDarwin()) {
7725     // Darwin only has one model of TLS.  Lower to that.
7726     unsigned char OpFlag = 0;
7727     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7728                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7729
7730     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7731     // global base reg.
7732     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7733                   !Subtarget->is64Bit();
7734     if (PIC32)
7735       OpFlag = X86II::MO_TLVP_PIC_BASE;
7736     else
7737       OpFlag = X86II::MO_TLVP;
7738     DebugLoc DL = Op.getDebugLoc();
7739     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7740                                                 GA->getValueType(0),
7741                                                 GA->getOffset(), OpFlag);
7742     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7743
7744     // With PIC32, the address is actually $g + Offset.
7745     if (PIC32)
7746       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7747                            DAG.getNode(X86ISD::GlobalBaseReg,
7748                                        DebugLoc(), getPointerTy()),
7749                            Offset);
7750
7751     // Lowering the machine isd will make sure everything is in the right
7752     // location.
7753     SDValue Chain = DAG.getEntryNode();
7754     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7755     SDValue Args[] = { Chain, Offset };
7756     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7757
7758     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7759     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7760     MFI->setAdjustsStack(true);
7761
7762     // And our return value (tls address) is in the standard call return value
7763     // location.
7764     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7765     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7766                               Chain.getValue(1));
7767   }
7768
7769   if (Subtarget->isTargetWindows()) {
7770     // Just use the implicit TLS architecture
7771     // Need to generate someting similar to:
7772     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7773     //                                  ; from TEB
7774     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7775     //   mov     rcx, qword [rdx+rcx*8]
7776     //   mov     eax, .tls$:tlsvar
7777     //   [rax+rcx] contains the address
7778     // Windows 64bit: gs:0x58
7779     // Windows 32bit: fs:__tls_array
7780
7781     // If GV is an alias then use the aliasee for determining
7782     // thread-localness.
7783     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7784       GV = GA->resolveAliasedGlobal(false);
7785     DebugLoc dl = GA->getDebugLoc();
7786     SDValue Chain = DAG.getEntryNode();
7787
7788     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7789     // %gs:0x58 (64-bit).
7790     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7791                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7792                                                              256)
7793                                         : Type::getInt32PtrTy(*DAG.getContext(),
7794                                                               257));
7795
7796     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7797                                         Subtarget->is64Bit()
7798                                         ? DAG.getIntPtrConstant(0x58)
7799                                         : DAG.getExternalSymbol("_tls_array",
7800                                                                 getPointerTy()),
7801                                         MachinePointerInfo(Ptr),
7802                                         false, false, false, 0);
7803
7804     // Load the _tls_index variable
7805     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7806     if (Subtarget->is64Bit())
7807       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7808                            IDX, MachinePointerInfo(), MVT::i32,
7809                            false, false, 0);
7810     else
7811       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7812                         false, false, false, 0);
7813
7814     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7815                                     getPointerTy());
7816     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7817
7818     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7819     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7820                       false, false, false, 0);
7821
7822     // Get the offset of start of .tls section
7823     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7824                                              GA->getValueType(0),
7825                                              GA->getOffset(), X86II::MO_SECREL);
7826     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7827
7828     // The address of the thread local variable is the add of the thread
7829     // pointer with the offset of the variable.
7830     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7831   }
7832
7833   llvm_unreachable("TLS not implemented for this target.");
7834 }
7835
7836
7837 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7838 /// and take a 2 x i32 value to shift plus a shift amount.
7839 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7840   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7841   EVT VT = Op.getValueType();
7842   unsigned VTBits = VT.getSizeInBits();
7843   DebugLoc dl = Op.getDebugLoc();
7844   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7845   SDValue ShOpLo = Op.getOperand(0);
7846   SDValue ShOpHi = Op.getOperand(1);
7847   SDValue ShAmt  = Op.getOperand(2);
7848   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7849                                      DAG.getConstant(VTBits - 1, MVT::i8))
7850                        : DAG.getConstant(0, VT);
7851
7852   SDValue Tmp2, Tmp3;
7853   if (Op.getOpcode() == ISD::SHL_PARTS) {
7854     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7855     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7856   } else {
7857     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7858     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7859   }
7860
7861   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7862                                 DAG.getConstant(VTBits, MVT::i8));
7863   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7864                              AndNode, DAG.getConstant(0, MVT::i8));
7865
7866   SDValue Hi, Lo;
7867   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7868   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7869   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7870
7871   if (Op.getOpcode() == ISD::SHL_PARTS) {
7872     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7873     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7874   } else {
7875     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7876     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7877   }
7878
7879   SDValue Ops[2] = { Lo, Hi };
7880   return DAG.getMergeValues(Ops, 2, dl);
7881 }
7882
7883 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7884                                            SelectionDAG &DAG) const {
7885   EVT SrcVT = Op.getOperand(0).getValueType();
7886
7887   if (SrcVT.isVector())
7888     return SDValue();
7889
7890   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7891          "Unknown SINT_TO_FP to lower!");
7892
7893   // These are really Legal; return the operand so the caller accepts it as
7894   // Legal.
7895   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7896     return Op;
7897   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7898       Subtarget->is64Bit()) {
7899     return Op;
7900   }
7901
7902   DebugLoc dl = Op.getDebugLoc();
7903   unsigned Size = SrcVT.getSizeInBits()/8;
7904   MachineFunction &MF = DAG.getMachineFunction();
7905   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7906   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7907   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7908                                StackSlot,
7909                                MachinePointerInfo::getFixedStack(SSFI),
7910                                false, false, 0);
7911   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7912 }
7913
7914 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7915                                      SDValue StackSlot,
7916                                      SelectionDAG &DAG) const {
7917   // Build the FILD
7918   DebugLoc DL = Op.getDebugLoc();
7919   SDVTList Tys;
7920   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7921   if (useSSE)
7922     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7923   else
7924     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7925
7926   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7927
7928   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7929   MachineMemOperand *MMO;
7930   if (FI) {
7931     int SSFI = FI->getIndex();
7932     MMO =
7933       DAG.getMachineFunction()
7934       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7935                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7936   } else {
7937     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7938     StackSlot = StackSlot.getOperand(1);
7939   }
7940   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7941   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7942                                            X86ISD::FILD, DL,
7943                                            Tys, Ops, array_lengthof(Ops),
7944                                            SrcVT, MMO);
7945
7946   if (useSSE) {
7947     Chain = Result.getValue(1);
7948     SDValue InFlag = Result.getValue(2);
7949
7950     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7951     // shouldn't be necessary except that RFP cannot be live across
7952     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7953     MachineFunction &MF = DAG.getMachineFunction();
7954     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7955     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7956     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7957     Tys = DAG.getVTList(MVT::Other);
7958     SDValue Ops[] = {
7959       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7960     };
7961     MachineMemOperand *MMO =
7962       DAG.getMachineFunction()
7963       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7964                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7965
7966     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7967                                     Ops, array_lengthof(Ops),
7968                                     Op.getValueType(), MMO);
7969     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7970                          MachinePointerInfo::getFixedStack(SSFI),
7971                          false, false, false, 0);
7972   }
7973
7974   return Result;
7975 }
7976
7977 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7978 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7979                                                SelectionDAG &DAG) const {
7980   // This algorithm is not obvious. Here it is what we're trying to output:
7981   /*
7982      movq       %rax,  %xmm0
7983      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7984      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7985      #ifdef __SSE3__
7986        haddpd   %xmm0, %xmm0
7987      #else
7988        pshufd   $0x4e, %xmm0, %xmm1
7989        addpd    %xmm1, %xmm0
7990      #endif
7991   */
7992
7993   DebugLoc dl = Op.getDebugLoc();
7994   LLVMContext *Context = DAG.getContext();
7995
7996   // Build some magic constants.
7997   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7998   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7999   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8000
8001   SmallVector<Constant*,2> CV1;
8002   CV1.push_back(
8003         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8004   CV1.push_back(
8005         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8006   Constant *C1 = ConstantVector::get(CV1);
8007   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8008
8009   // Load the 64-bit value into an XMM register.
8010   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8011                             Op.getOperand(0));
8012   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8013                               MachinePointerInfo::getConstantPool(),
8014                               false, false, false, 16);
8015   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8016                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8017                               CLod0);
8018
8019   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8020                               MachinePointerInfo::getConstantPool(),
8021                               false, false, false, 16);
8022   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8023   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8024   SDValue Result;
8025
8026   if (Subtarget->hasSSE3()) {
8027     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8028     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8029   } else {
8030     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8031     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8032                                            S2F, 0x4E, DAG);
8033     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8034                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8035                          Sub);
8036   }
8037
8038   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8039                      DAG.getIntPtrConstant(0));
8040 }
8041
8042 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8043 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8044                                                SelectionDAG &DAG) const {
8045   DebugLoc dl = Op.getDebugLoc();
8046   // FP constant to bias correct the final result.
8047   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8048                                    MVT::f64);
8049
8050   // Load the 32-bit value into an XMM register.
8051   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8052                              Op.getOperand(0));
8053
8054   // Zero out the upper parts of the register.
8055   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8056
8057   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8058                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8059                      DAG.getIntPtrConstant(0));
8060
8061   // Or the load with the bias.
8062   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8063                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8064                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8065                                                    MVT::v2f64, Load)),
8066                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8067                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8068                                                    MVT::v2f64, Bias)));
8069   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8070                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8071                    DAG.getIntPtrConstant(0));
8072
8073   // Subtract the bias.
8074   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8075
8076   // Handle final rounding.
8077   EVT DestVT = Op.getValueType();
8078
8079   if (DestVT.bitsLT(MVT::f64))
8080     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8081                        DAG.getIntPtrConstant(0));
8082   if (DestVT.bitsGT(MVT::f64))
8083     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8084
8085   // Handle final rounding.
8086   return Sub;
8087 }
8088
8089 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8090                                            SelectionDAG &DAG) const {
8091   SDValue N0 = Op.getOperand(0);
8092   DebugLoc dl = Op.getDebugLoc();
8093
8094   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8095   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8096   // the optimization here.
8097   if (DAG.SignBitIsZero(N0))
8098     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8099
8100   EVT SrcVT = N0.getValueType();
8101   EVT DstVT = Op.getValueType();
8102   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8103     return LowerUINT_TO_FP_i64(Op, DAG);
8104   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8105     return LowerUINT_TO_FP_i32(Op, DAG);
8106   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8107     return SDValue();
8108
8109   // Make a 64-bit buffer, and use it to build an FILD.
8110   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8111   if (SrcVT == MVT::i32) {
8112     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8113     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8114                                      getPointerTy(), StackSlot, WordOff);
8115     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8116                                   StackSlot, MachinePointerInfo(),
8117                                   false, false, 0);
8118     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8119                                   OffsetSlot, MachinePointerInfo(),
8120                                   false, false, 0);
8121     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8122     return Fild;
8123   }
8124
8125   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8126   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8127                                StackSlot, MachinePointerInfo(),
8128                                false, false, 0);
8129   // For i64 source, we need to add the appropriate power of 2 if the input
8130   // was negative.  This is the same as the optimization in
8131   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8132   // we must be careful to do the computation in x87 extended precision, not
8133   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8134   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8135   MachineMemOperand *MMO =
8136     DAG.getMachineFunction()
8137     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8138                           MachineMemOperand::MOLoad, 8, 8);
8139
8140   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8141   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8142   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8143                                          MVT::i64, MMO);
8144
8145   APInt FF(32, 0x5F800000ULL);
8146
8147   // Check whether the sign bit is set.
8148   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8149                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8150                                  ISD::SETLT);
8151
8152   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8153   SDValue FudgePtr = DAG.getConstantPool(
8154                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8155                                          getPointerTy());
8156
8157   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8158   SDValue Zero = DAG.getIntPtrConstant(0);
8159   SDValue Four = DAG.getIntPtrConstant(4);
8160   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8161                                Zero, Four);
8162   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8163
8164   // Load the value out, extending it from f32 to f80.
8165   // FIXME: Avoid the extend by constructing the right constant pool?
8166   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8167                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8168                                  MVT::f32, false, false, 4);
8169   // Extend everything to 80 bits to force it to be done on x87.
8170   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8171   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8172 }
8173
8174 std::pair<SDValue,SDValue> X86TargetLowering::
8175 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8176   DebugLoc DL = Op.getDebugLoc();
8177
8178   EVT DstTy = Op.getValueType();
8179
8180   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8181     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8182     DstTy = MVT::i64;
8183   }
8184
8185   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8186          DstTy.getSimpleVT() >= MVT::i16 &&
8187          "Unknown FP_TO_INT to lower!");
8188
8189   // These are really Legal.
8190   if (DstTy == MVT::i32 &&
8191       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8192     return std::make_pair(SDValue(), SDValue());
8193   if (Subtarget->is64Bit() &&
8194       DstTy == MVT::i64 &&
8195       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8196     return std::make_pair(SDValue(), SDValue());
8197
8198   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8199   // stack slot, or into the FTOL runtime function.
8200   MachineFunction &MF = DAG.getMachineFunction();
8201   unsigned MemSize = DstTy.getSizeInBits()/8;
8202   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8203   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8204
8205   unsigned Opc;
8206   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8207     Opc = X86ISD::WIN_FTOL;
8208   else
8209     switch (DstTy.getSimpleVT().SimpleTy) {
8210     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8211     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8212     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8213     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8214     }
8215
8216   SDValue Chain = DAG.getEntryNode();
8217   SDValue Value = Op.getOperand(0);
8218   EVT TheVT = Op.getOperand(0).getValueType();
8219   // FIXME This causes a redundant load/store if the SSE-class value is already
8220   // in memory, such as if it is on the callstack.
8221   if (isScalarFPTypeInSSEReg(TheVT)) {
8222     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8223     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8224                          MachinePointerInfo::getFixedStack(SSFI),
8225                          false, false, 0);
8226     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8227     SDValue Ops[] = {
8228       Chain, StackSlot, DAG.getValueType(TheVT)
8229     };
8230
8231     MachineMemOperand *MMO =
8232       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8233                               MachineMemOperand::MOLoad, MemSize, MemSize);
8234     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8235                                     DstTy, MMO);
8236     Chain = Value.getValue(1);
8237     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8238     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8239   }
8240
8241   MachineMemOperand *MMO =
8242     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8243                             MachineMemOperand::MOStore, MemSize, MemSize);
8244
8245   if (Opc != X86ISD::WIN_FTOL) {
8246     // Build the FP_TO_INT*_IN_MEM
8247     SDValue Ops[] = { Chain, Value, StackSlot };
8248     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8249                                            Ops, 3, DstTy, MMO);
8250     return std::make_pair(FIST, StackSlot);
8251   } else {
8252     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8253       DAG.getVTList(MVT::Other, MVT::Glue),
8254       Chain, Value);
8255     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8256       MVT::i32, ftol.getValue(1));
8257     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8258       MVT::i32, eax.getValue(2));
8259     SDValue Ops[] = { eax, edx };
8260     SDValue pair = IsReplace
8261       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8262       : DAG.getMergeValues(Ops, 2, DL);
8263     return std::make_pair(pair, SDValue());
8264   }
8265 }
8266
8267 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8268   DebugLoc DL = Op.getDebugLoc();
8269   EVT VT = Op.getValueType();
8270   EVT SVT = Op.getOperand(0).getValueType();
8271
8272   if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8273       VT.getVectorNumElements() != SVT.getVectorNumElements())
8274     return SDValue();
8275
8276   assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8277
8278   unsigned NumElems = VT.getVectorNumElements();
8279   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8280                              NumElems * 2);
8281
8282   SDValue In = Op.getOperand(0);
8283   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8284   // Prepare truncation shuffle mask
8285   for (unsigned i = 0; i != NumElems; ++i)
8286     MaskVec[i] = i * 2;
8287   SDValue V = DAG.getVectorShuffle(NVT, DL,
8288                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8289                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8290   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8291                      DAG.getIntPtrConstant(0));
8292 }
8293
8294 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8295                                            SelectionDAG &DAG) const {
8296   if (Op.getValueType().isVector()) {
8297     if (Op.getValueType() == MVT::v8i16)
8298       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8299                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8300                                      MVT::v8i32, Op.getOperand(0)));
8301     return SDValue();
8302   }
8303
8304   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8305     /*IsSigned=*/ true, /*IsReplace=*/ false);
8306   SDValue FIST = Vals.first, StackSlot = Vals.second;
8307   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8308   if (FIST.getNode() == 0) return Op;
8309
8310   if (StackSlot.getNode())
8311     // Load the result.
8312     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8313                        FIST, StackSlot, MachinePointerInfo(),
8314                        false, false, false, 0);
8315
8316   // The node is the result.
8317   return FIST;
8318 }
8319
8320 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8321                                            SelectionDAG &DAG) const {
8322   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8323     /*IsSigned=*/ false, /*IsReplace=*/ false);
8324   SDValue FIST = Vals.first, StackSlot = Vals.second;
8325   assert(FIST.getNode() && "Unexpected failure");
8326
8327   if (StackSlot.getNode())
8328     // Load the result.
8329     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8330                        FIST, StackSlot, MachinePointerInfo(),
8331                        false, false, false, 0);
8332
8333   // The node is the result.
8334   return FIST;
8335 }
8336
8337 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8338                                           SelectionDAG &DAG) const {
8339   DebugLoc DL = Op.getDebugLoc();
8340   EVT VT = Op.getValueType();
8341   SDValue In = Op.getOperand(0);
8342   EVT SVT = In.getValueType();
8343
8344   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8345
8346   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8347                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8348                                  In, DAG.getUNDEF(SVT)));
8349 }
8350
8351 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8352   LLVMContext *Context = DAG.getContext();
8353   DebugLoc dl = Op.getDebugLoc();
8354   EVT VT = Op.getValueType();
8355   EVT EltVT = VT;
8356   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8357   if (VT.isVector()) {
8358     EltVT = VT.getVectorElementType();
8359     NumElts = VT.getVectorNumElements();
8360   }
8361   Constant *C;
8362   if (EltVT == MVT::f64)
8363     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8364   else
8365     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8366   C = ConstantVector::getSplat(NumElts, C);
8367   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8368   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8369   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8370                              MachinePointerInfo::getConstantPool(),
8371                              false, false, false, Alignment);
8372   if (VT.isVector()) {
8373     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8374     return DAG.getNode(ISD::BITCAST, dl, VT,
8375                        DAG.getNode(ISD::AND, dl, ANDVT,
8376                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8377                                                Op.getOperand(0)),
8378                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8379   }
8380   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8381 }
8382
8383 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8384   LLVMContext *Context = DAG.getContext();
8385   DebugLoc dl = Op.getDebugLoc();
8386   EVT VT = Op.getValueType();
8387   EVT EltVT = VT;
8388   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8389   if (VT.isVector()) {
8390     EltVT = VT.getVectorElementType();
8391     NumElts = VT.getVectorNumElements();
8392   }
8393   Constant *C;
8394   if (EltVT == MVT::f64)
8395     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8396   else
8397     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8398   C = ConstantVector::getSplat(NumElts, C);
8399   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8400   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8401   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8402                              MachinePointerInfo::getConstantPool(),
8403                              false, false, false, Alignment);
8404   if (VT.isVector()) {
8405     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8406     return DAG.getNode(ISD::BITCAST, dl, VT,
8407                        DAG.getNode(ISD::XOR, dl, XORVT,
8408                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8409                                                Op.getOperand(0)),
8410                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8411   }
8412
8413   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8414 }
8415
8416 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8417   LLVMContext *Context = DAG.getContext();
8418   SDValue Op0 = Op.getOperand(0);
8419   SDValue Op1 = Op.getOperand(1);
8420   DebugLoc dl = Op.getDebugLoc();
8421   EVT VT = Op.getValueType();
8422   EVT SrcVT = Op1.getValueType();
8423
8424   // If second operand is smaller, extend it first.
8425   if (SrcVT.bitsLT(VT)) {
8426     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8427     SrcVT = VT;
8428   }
8429   // And if it is bigger, shrink it first.
8430   if (SrcVT.bitsGT(VT)) {
8431     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8432     SrcVT = VT;
8433   }
8434
8435   // At this point the operands and the result should have the same
8436   // type, and that won't be f80 since that is not custom lowered.
8437
8438   // First get the sign bit of second operand.
8439   SmallVector<Constant*,4> CV;
8440   if (SrcVT == MVT::f64) {
8441     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8442     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8443   } else {
8444     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8445     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8446     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8447     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8448   }
8449   Constant *C = ConstantVector::get(CV);
8450   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8451   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8452                               MachinePointerInfo::getConstantPool(),
8453                               false, false, false, 16);
8454   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8455
8456   // Shift sign bit right or left if the two operands have different types.
8457   if (SrcVT.bitsGT(VT)) {
8458     // Op0 is MVT::f32, Op1 is MVT::f64.
8459     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8460     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8461                           DAG.getConstant(32, MVT::i32));
8462     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8463     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8464                           DAG.getIntPtrConstant(0));
8465   }
8466
8467   // Clear first operand sign bit.
8468   CV.clear();
8469   if (VT == MVT::f64) {
8470     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8471     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8472   } else {
8473     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8474     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8475     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8476     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8477   }
8478   C = ConstantVector::get(CV);
8479   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8480   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8481                               MachinePointerInfo::getConstantPool(),
8482                               false, false, false, 16);
8483   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8484
8485   // Or the value with the sign bit.
8486   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8487 }
8488
8489 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8490   SDValue N0 = Op.getOperand(0);
8491   DebugLoc dl = Op.getDebugLoc();
8492   EVT VT = Op.getValueType();
8493
8494   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8495   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8496                                   DAG.getConstant(1, VT));
8497   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8498 }
8499
8500 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8501 //
8502 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8503   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8504
8505   if (!Subtarget->hasSSE41())
8506     return SDValue();
8507
8508   if (!Op->hasOneUse())
8509     return SDValue();
8510
8511   SDNode *N = Op.getNode();
8512   DebugLoc DL = N->getDebugLoc();
8513
8514   SmallVector<SDValue, 8> Opnds;
8515   DenseMap<SDValue, unsigned> VecInMap;
8516   EVT VT = MVT::Other;
8517
8518   // Recognize a special case where a vector is casted into wide integer to
8519   // test all 0s.
8520   Opnds.push_back(N->getOperand(0));
8521   Opnds.push_back(N->getOperand(1));
8522
8523   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8524     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8525     // BFS traverse all OR'd operands.
8526     if (I->getOpcode() == ISD::OR) {
8527       Opnds.push_back(I->getOperand(0));
8528       Opnds.push_back(I->getOperand(1));
8529       // Re-evaluate the number of nodes to be traversed.
8530       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8531       continue;
8532     }
8533
8534     // Quit if a non-EXTRACT_VECTOR_ELT
8535     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8536       return SDValue();
8537
8538     // Quit if without a constant index.
8539     SDValue Idx = I->getOperand(1);
8540     if (!isa<ConstantSDNode>(Idx))
8541       return SDValue();
8542
8543     SDValue ExtractedFromVec = I->getOperand(0);
8544     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8545     if (M == VecInMap.end()) {
8546       VT = ExtractedFromVec.getValueType();
8547       // Quit if not 128/256-bit vector.
8548       if (!VT.is128BitVector() && !VT.is256BitVector())
8549         return SDValue();
8550       // Quit if not the same type.
8551       if (VecInMap.begin() != VecInMap.end() &&
8552           VT != VecInMap.begin()->first.getValueType())
8553         return SDValue();
8554       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8555     }
8556     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8557   }
8558
8559   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8560          "Not extracted from 128-/256-bit vector.");
8561
8562   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8563   SmallVector<SDValue, 8> VecIns;
8564
8565   for (DenseMap<SDValue, unsigned>::const_iterator
8566         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8567     // Quit if not all elements are used.
8568     if (I->second != FullMask)
8569       return SDValue();
8570     VecIns.push_back(I->first);
8571   }
8572
8573   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8574
8575   // Cast all vectors into TestVT for PTEST.
8576   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8577     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8578
8579   // If more than one full vectors are evaluated, OR them first before PTEST.
8580   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8581     // Each iteration will OR 2 nodes and append the result until there is only
8582     // 1 node left, i.e. the final OR'd value of all vectors.
8583     SDValue LHS = VecIns[Slot];
8584     SDValue RHS = VecIns[Slot + 1];
8585     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8586   }
8587
8588   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8589                      VecIns.back(), VecIns.back());
8590 }
8591
8592 /// Emit nodes that will be selected as "test Op0,Op0", or something
8593 /// equivalent.
8594 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8595                                     SelectionDAG &DAG) const {
8596   DebugLoc dl = Op.getDebugLoc();
8597
8598   // CF and OF aren't always set the way we want. Determine which
8599   // of these we need.
8600   bool NeedCF = false;
8601   bool NeedOF = false;
8602   switch (X86CC) {
8603   default: break;
8604   case X86::COND_A: case X86::COND_AE:
8605   case X86::COND_B: case X86::COND_BE:
8606     NeedCF = true;
8607     break;
8608   case X86::COND_G: case X86::COND_GE:
8609   case X86::COND_L: case X86::COND_LE:
8610   case X86::COND_O: case X86::COND_NO:
8611     NeedOF = true;
8612     break;
8613   }
8614
8615   // See if we can use the EFLAGS value from the operand instead of
8616   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8617   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8618   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8619     // Emit a CMP with 0, which is the TEST pattern.
8620     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8621                        DAG.getConstant(0, Op.getValueType()));
8622
8623   unsigned Opcode = 0;
8624   unsigned NumOperands = 0;
8625
8626   // Truncate operations may prevent the merge of the SETCC instruction
8627   // and the arithmetic intruction before it. Attempt to truncate the operands
8628   // of the arithmetic instruction and use a reduced bit-width instruction.
8629   bool NeedTruncation = false;
8630   SDValue ArithOp = Op;
8631   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8632     SDValue Arith = Op->getOperand(0);
8633     // Both the trunc and the arithmetic op need to have one user each.
8634     if (Arith->hasOneUse())
8635       switch (Arith.getOpcode()) {
8636         default: break;
8637         case ISD::ADD:
8638         case ISD::SUB:
8639         case ISD::AND:
8640         case ISD::OR:
8641         case ISD::XOR: {
8642           NeedTruncation = true;
8643           ArithOp = Arith;
8644         }
8645       }
8646   }
8647
8648   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8649   // which may be the result of a CAST.  We use the variable 'Op', which is the
8650   // non-casted variable when we check for possible users.
8651   switch (ArithOp.getOpcode()) {
8652   case ISD::ADD:
8653     // Due to an isel shortcoming, be conservative if this add is likely to be
8654     // selected as part of a load-modify-store instruction. When the root node
8655     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8656     // uses of other nodes in the match, such as the ADD in this case. This
8657     // leads to the ADD being left around and reselected, with the result being
8658     // two adds in the output.  Alas, even if none our users are stores, that
8659     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8660     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8661     // climbing the DAG back to the root, and it doesn't seem to be worth the
8662     // effort.
8663     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8664          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8665       if (UI->getOpcode() != ISD::CopyToReg &&
8666           UI->getOpcode() != ISD::SETCC &&
8667           UI->getOpcode() != ISD::STORE)
8668         goto default_case;
8669
8670     if (ConstantSDNode *C =
8671         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8672       // An add of one will be selected as an INC.
8673       if (C->getAPIntValue() == 1) {
8674         Opcode = X86ISD::INC;
8675         NumOperands = 1;
8676         break;
8677       }
8678
8679       // An add of negative one (subtract of one) will be selected as a DEC.
8680       if (C->getAPIntValue().isAllOnesValue()) {
8681         Opcode = X86ISD::DEC;
8682         NumOperands = 1;
8683         break;
8684       }
8685     }
8686
8687     // Otherwise use a regular EFLAGS-setting add.
8688     Opcode = X86ISD::ADD;
8689     NumOperands = 2;
8690     break;
8691   case ISD::AND: {
8692     // If the primary and result isn't used, don't bother using X86ISD::AND,
8693     // because a TEST instruction will be better.
8694     bool NonFlagUse = false;
8695     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8696            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8697       SDNode *User = *UI;
8698       unsigned UOpNo = UI.getOperandNo();
8699       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8700         // Look pass truncate.
8701         UOpNo = User->use_begin().getOperandNo();
8702         User = *User->use_begin();
8703       }
8704
8705       if (User->getOpcode() != ISD::BRCOND &&
8706           User->getOpcode() != ISD::SETCC &&
8707           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8708         NonFlagUse = true;
8709         break;
8710       }
8711     }
8712
8713     if (!NonFlagUse)
8714       break;
8715   }
8716     // FALL THROUGH
8717   case ISD::SUB:
8718   case ISD::OR:
8719   case ISD::XOR:
8720     // Due to the ISEL shortcoming noted above, be conservative if this op is
8721     // likely to be selected as part of a load-modify-store instruction.
8722     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8723            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8724       if (UI->getOpcode() == ISD::STORE)
8725         goto default_case;
8726
8727     // Otherwise use a regular EFLAGS-setting instruction.
8728     switch (ArithOp.getOpcode()) {
8729     default: llvm_unreachable("unexpected operator!");
8730     case ISD::SUB: Opcode = X86ISD::SUB; break;
8731     case ISD::XOR: Opcode = X86ISD::XOR; break;
8732     case ISD::AND: Opcode = X86ISD::AND; break;
8733     case ISD::OR: {
8734       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8735         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8736         if (EFLAGS.getNode())
8737           return EFLAGS;
8738       }
8739       Opcode = X86ISD::OR;
8740       break;
8741     }
8742     }
8743
8744     NumOperands = 2;
8745     break;
8746   case X86ISD::ADD:
8747   case X86ISD::SUB:
8748   case X86ISD::INC:
8749   case X86ISD::DEC:
8750   case X86ISD::OR:
8751   case X86ISD::XOR:
8752   case X86ISD::AND:
8753     return SDValue(Op.getNode(), 1);
8754   default:
8755   default_case:
8756     break;
8757   }
8758
8759   // If we found that truncation is beneficial, perform the truncation and
8760   // update 'Op'.
8761   if (NeedTruncation) {
8762     EVT VT = Op.getValueType();
8763     SDValue WideVal = Op->getOperand(0);
8764     EVT WideVT = WideVal.getValueType();
8765     unsigned ConvertedOp = 0;
8766     // Use a target machine opcode to prevent further DAGCombine
8767     // optimizations that may separate the arithmetic operations
8768     // from the setcc node.
8769     switch (WideVal.getOpcode()) {
8770       default: break;
8771       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8772       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8773       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8774       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8775       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8776     }
8777
8778     if (ConvertedOp) {
8779       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8780       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8781         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8782         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8783         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8784       }
8785     }
8786   }
8787
8788   if (Opcode == 0)
8789     // Emit a CMP with 0, which is the TEST pattern.
8790     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8791                        DAG.getConstant(0, Op.getValueType()));
8792
8793   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8794   SmallVector<SDValue, 4> Ops;
8795   for (unsigned i = 0; i != NumOperands; ++i)
8796     Ops.push_back(Op.getOperand(i));
8797
8798   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8799   DAG.ReplaceAllUsesWith(Op, New);
8800   return SDValue(New.getNode(), 1);
8801 }
8802
8803 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8804 /// equivalent.
8805 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8806                                    SelectionDAG &DAG) const {
8807   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8808     if (C->getAPIntValue() == 0)
8809       return EmitTest(Op0, X86CC, DAG);
8810
8811   DebugLoc dl = Op0.getDebugLoc();
8812   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8813        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8814     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8815     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8816     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8817                               Op0, Op1);
8818     return SDValue(Sub.getNode(), 1);
8819   }
8820   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8821 }
8822
8823 /// Convert a comparison if required by the subtarget.
8824 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8825                                                  SelectionDAG &DAG) const {
8826   // If the subtarget does not support the FUCOMI instruction, floating-point
8827   // comparisons have to be converted.
8828   if (Subtarget->hasCMov() ||
8829       Cmp.getOpcode() != X86ISD::CMP ||
8830       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8831       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8832     return Cmp;
8833
8834   // The instruction selector will select an FUCOM instruction instead of
8835   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8836   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8837   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8838   DebugLoc dl = Cmp.getDebugLoc();
8839   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8840   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8841   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8842                             DAG.getConstant(8, MVT::i8));
8843   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8844   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8845 }
8846
8847 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8848 /// if it's possible.
8849 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8850                                      DebugLoc dl, SelectionDAG &DAG) const {
8851   SDValue Op0 = And.getOperand(0);
8852   SDValue Op1 = And.getOperand(1);
8853   if (Op0.getOpcode() == ISD::TRUNCATE)
8854     Op0 = Op0.getOperand(0);
8855   if (Op1.getOpcode() == ISD::TRUNCATE)
8856     Op1 = Op1.getOperand(0);
8857
8858   SDValue LHS, RHS;
8859   if (Op1.getOpcode() == ISD::SHL)
8860     std::swap(Op0, Op1);
8861   if (Op0.getOpcode() == ISD::SHL) {
8862     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8863       if (And00C->getZExtValue() == 1) {
8864         // If we looked past a truncate, check that it's only truncating away
8865         // known zeros.
8866         unsigned BitWidth = Op0.getValueSizeInBits();
8867         unsigned AndBitWidth = And.getValueSizeInBits();
8868         if (BitWidth > AndBitWidth) {
8869           APInt Zeros, Ones;
8870           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8871           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8872             return SDValue();
8873         }
8874         LHS = Op1;
8875         RHS = Op0.getOperand(1);
8876       }
8877   } else if (Op1.getOpcode() == ISD::Constant) {
8878     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8879     uint64_t AndRHSVal = AndRHS->getZExtValue();
8880     SDValue AndLHS = Op0;
8881
8882     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8883       LHS = AndLHS.getOperand(0);
8884       RHS = AndLHS.getOperand(1);
8885     }
8886
8887     // Use BT if the immediate can't be encoded in a TEST instruction.
8888     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8889       LHS = AndLHS;
8890       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8891     }
8892   }
8893
8894   if (LHS.getNode()) {
8895     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8896     // instruction.  Since the shift amount is in-range-or-undefined, we know
8897     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8898     // the encoding for the i16 version is larger than the i32 version.
8899     // Also promote i16 to i32 for performance / code size reason.
8900     if (LHS.getValueType() == MVT::i8 ||
8901         LHS.getValueType() == MVT::i16)
8902       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8903
8904     // If the operand types disagree, extend the shift amount to match.  Since
8905     // BT ignores high bits (like shifts) we can use anyextend.
8906     if (LHS.getValueType() != RHS.getValueType())
8907       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8908
8909     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8910     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8911     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8912                        DAG.getConstant(Cond, MVT::i8), BT);
8913   }
8914
8915   return SDValue();
8916 }
8917
8918 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8919
8920   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8921
8922   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8923   SDValue Op0 = Op.getOperand(0);
8924   SDValue Op1 = Op.getOperand(1);
8925   DebugLoc dl = Op.getDebugLoc();
8926   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8927
8928   // Optimize to BT if possible.
8929   // Lower (X & (1 << N)) == 0 to BT(X, N).
8930   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8931   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8932   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8933       Op1.getOpcode() == ISD::Constant &&
8934       cast<ConstantSDNode>(Op1)->isNullValue() &&
8935       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8936     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8937     if (NewSetCC.getNode())
8938       return NewSetCC;
8939   }
8940
8941   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8942   // these.
8943   if (Op1.getOpcode() == ISD::Constant &&
8944       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8945        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8946       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8947
8948     // If the input is a setcc, then reuse the input setcc or use a new one with
8949     // the inverted condition.
8950     if (Op0.getOpcode() == X86ISD::SETCC) {
8951       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8952       bool Invert = (CC == ISD::SETNE) ^
8953         cast<ConstantSDNode>(Op1)->isNullValue();
8954       if (!Invert) return Op0;
8955
8956       CCode = X86::GetOppositeBranchCondition(CCode);
8957       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8958                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8959     }
8960   }
8961
8962   bool isFP = Op1.getValueType().isFloatingPoint();
8963   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8964   if (X86CC == X86::COND_INVALID)
8965     return SDValue();
8966
8967   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8968   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8969   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8970                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8971 }
8972
8973 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8974 // ones, and then concatenate the result back.
8975 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8976   EVT VT = Op.getValueType();
8977
8978   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8979          "Unsupported value type for operation");
8980
8981   unsigned NumElems = VT.getVectorNumElements();
8982   DebugLoc dl = Op.getDebugLoc();
8983   SDValue CC = Op.getOperand(2);
8984
8985   // Extract the LHS vectors
8986   SDValue LHS = Op.getOperand(0);
8987   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8988   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8989
8990   // Extract the RHS vectors
8991   SDValue RHS = Op.getOperand(1);
8992   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8993   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8994
8995   // Issue the operation on the smaller types and concatenate the result back
8996   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8997   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8998   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8999                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9000                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9001 }
9002
9003
9004 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9005   SDValue Cond;
9006   SDValue Op0 = Op.getOperand(0);
9007   SDValue Op1 = Op.getOperand(1);
9008   SDValue CC = Op.getOperand(2);
9009   EVT VT = Op.getValueType();
9010   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9011   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9012   DebugLoc dl = Op.getDebugLoc();
9013
9014   if (isFP) {
9015 #ifndef NDEBUG
9016     EVT EltVT = Op0.getValueType().getVectorElementType();
9017     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9018 #endif
9019
9020     unsigned SSECC;
9021     bool Swap = false;
9022
9023     // SSE Condition code mapping:
9024     //  0 - EQ
9025     //  1 - LT
9026     //  2 - LE
9027     //  3 - UNORD
9028     //  4 - NEQ
9029     //  5 - NLT
9030     //  6 - NLE
9031     //  7 - ORD
9032     switch (SetCCOpcode) {
9033     default: llvm_unreachable("Unexpected SETCC condition");
9034     case ISD::SETOEQ:
9035     case ISD::SETEQ:  SSECC = 0; break;
9036     case ISD::SETOGT:
9037     case ISD::SETGT: Swap = true; // Fallthrough
9038     case ISD::SETLT:
9039     case ISD::SETOLT: SSECC = 1; break;
9040     case ISD::SETOGE:
9041     case ISD::SETGE: Swap = true; // Fallthrough
9042     case ISD::SETLE:
9043     case ISD::SETOLE: SSECC = 2; break;
9044     case ISD::SETUO:  SSECC = 3; break;
9045     case ISD::SETUNE:
9046     case ISD::SETNE:  SSECC = 4; break;
9047     case ISD::SETULE: Swap = true; // Fallthrough
9048     case ISD::SETUGE: SSECC = 5; break;
9049     case ISD::SETULT: Swap = true; // Fallthrough
9050     case ISD::SETUGT: SSECC = 6; break;
9051     case ISD::SETO:   SSECC = 7; break;
9052     case ISD::SETUEQ:
9053     case ISD::SETONE: SSECC = 8; break;
9054     }
9055     if (Swap)
9056       std::swap(Op0, Op1);
9057
9058     // In the two special cases we can't handle, emit two comparisons.
9059     if (SSECC == 8) {
9060       unsigned CC0, CC1;
9061       unsigned CombineOpc;
9062       if (SetCCOpcode == ISD::SETUEQ) {
9063         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9064       } else {
9065         assert(SetCCOpcode == ISD::SETONE);
9066         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9067       }
9068
9069       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9070                                  DAG.getConstant(CC0, MVT::i8));
9071       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9072                                  DAG.getConstant(CC1, MVT::i8));
9073       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9074     }
9075     // Handle all other FP comparisons here.
9076     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9077                        DAG.getConstant(SSECC, MVT::i8));
9078   }
9079
9080   // Break 256-bit integer vector compare into smaller ones.
9081   if (VT.is256BitVector() && !Subtarget->hasAVX2())
9082     return Lower256IntVSETCC(Op, DAG);
9083
9084   // We are handling one of the integer comparisons here.  Since SSE only has
9085   // GT and EQ comparisons for integer, swapping operands and multiple
9086   // operations may be required for some comparisons.
9087   unsigned Opc;
9088   bool Swap = false, Invert = false, FlipSigns = false;
9089
9090   switch (SetCCOpcode) {
9091   default: llvm_unreachable("Unexpected SETCC condition");
9092   case ISD::SETNE:  Invert = true;
9093   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9094   case ISD::SETLT:  Swap = true;
9095   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9096   case ISD::SETGE:  Swap = true;
9097   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9098   case ISD::SETULT: Swap = true;
9099   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9100   case ISD::SETUGE: Swap = true;
9101   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9102   }
9103   if (Swap)
9104     std::swap(Op0, Op1);
9105
9106   // Check that the operation in question is available (most are plain SSE2,
9107   // but PCMPGTQ and PCMPEQQ have different requirements).
9108   if (VT == MVT::v2i64) {
9109     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9110       return SDValue();
9111     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9112       return SDValue();
9113   }
9114
9115   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9116   // bits of the inputs before performing those operations.
9117   if (FlipSigns) {
9118     EVT EltVT = VT.getVectorElementType();
9119     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9120                                       EltVT);
9121     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9122     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9123                                     SignBits.size());
9124     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9125     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9126   }
9127
9128   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9129
9130   // If the logical-not of the result is required, perform that now.
9131   if (Invert)
9132     Result = DAG.getNOT(dl, Result, VT);
9133
9134   return Result;
9135 }
9136
9137 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9138 static bool isX86LogicalCmp(SDValue Op) {
9139   unsigned Opc = Op.getNode()->getOpcode();
9140   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9141       Opc == X86ISD::SAHF)
9142     return true;
9143   if (Op.getResNo() == 1 &&
9144       (Opc == X86ISD::ADD ||
9145        Opc == X86ISD::SUB ||
9146        Opc == X86ISD::ADC ||
9147        Opc == X86ISD::SBB ||
9148        Opc == X86ISD::SMUL ||
9149        Opc == X86ISD::UMUL ||
9150        Opc == X86ISD::INC ||
9151        Opc == X86ISD::DEC ||
9152        Opc == X86ISD::OR ||
9153        Opc == X86ISD::XOR ||
9154        Opc == X86ISD::AND))
9155     return true;
9156
9157   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9158     return true;
9159
9160   return false;
9161 }
9162
9163 static bool isZero(SDValue V) {
9164   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9165   return C && C->isNullValue();
9166 }
9167
9168 static bool isAllOnes(SDValue V) {
9169   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9170   return C && C->isAllOnesValue();
9171 }
9172
9173 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9174   if (V.getOpcode() != ISD::TRUNCATE)
9175     return false;
9176
9177   SDValue VOp0 = V.getOperand(0);
9178   unsigned InBits = VOp0.getValueSizeInBits();
9179   unsigned Bits = V.getValueSizeInBits();
9180   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9181 }
9182
9183 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9184   bool addTest = true;
9185   SDValue Cond  = Op.getOperand(0);
9186   SDValue Op1 = Op.getOperand(1);
9187   SDValue Op2 = Op.getOperand(2);
9188   DebugLoc DL = Op.getDebugLoc();
9189   SDValue CC;
9190
9191   if (Cond.getOpcode() == ISD::SETCC) {
9192     SDValue NewCond = LowerSETCC(Cond, DAG);
9193     if (NewCond.getNode())
9194       Cond = NewCond;
9195   }
9196
9197   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9198   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9199   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9200   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9201   if (Cond.getOpcode() == X86ISD::SETCC &&
9202       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9203       isZero(Cond.getOperand(1).getOperand(1))) {
9204     SDValue Cmp = Cond.getOperand(1);
9205
9206     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9207
9208     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9209         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9210       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9211
9212       SDValue CmpOp0 = Cmp.getOperand(0);
9213       // Apply further optimizations for special cases
9214       // (select (x != 0), -1, 0) -> neg & sbb
9215       // (select (x == 0), 0, -1) -> neg & sbb
9216       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9217         if (YC->isNullValue() &&
9218             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9219           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9220           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9221                                     DAG.getConstant(0, CmpOp0.getValueType()),
9222                                     CmpOp0);
9223           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9224                                     DAG.getConstant(X86::COND_B, MVT::i8),
9225                                     SDValue(Neg.getNode(), 1));
9226           return Res;
9227         }
9228
9229       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9230                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9231       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9232
9233       SDValue Res =   // Res = 0 or -1.
9234         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9235                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9236
9237       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9238         Res = DAG.getNOT(DL, Res, Res.getValueType());
9239
9240       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9241       if (N2C == 0 || !N2C->isNullValue())
9242         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9243       return Res;
9244     }
9245   }
9246
9247   // Look past (and (setcc_carry (cmp ...)), 1).
9248   if (Cond.getOpcode() == ISD::AND &&
9249       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9250     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9251     if (C && C->getAPIntValue() == 1)
9252       Cond = Cond.getOperand(0);
9253   }
9254
9255   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9256   // setting operand in place of the X86ISD::SETCC.
9257   unsigned CondOpcode = Cond.getOpcode();
9258   if (CondOpcode == X86ISD::SETCC ||
9259       CondOpcode == X86ISD::SETCC_CARRY) {
9260     CC = Cond.getOperand(0);
9261
9262     SDValue Cmp = Cond.getOperand(1);
9263     unsigned Opc = Cmp.getOpcode();
9264     EVT VT = Op.getValueType();
9265
9266     bool IllegalFPCMov = false;
9267     if (VT.isFloatingPoint() && !VT.isVector() &&
9268         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9269       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9270
9271     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9272         Opc == X86ISD::BT) { // FIXME
9273       Cond = Cmp;
9274       addTest = false;
9275     }
9276   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9277              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9278              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9279               Cond.getOperand(0).getValueType() != MVT::i8)) {
9280     SDValue LHS = Cond.getOperand(0);
9281     SDValue RHS = Cond.getOperand(1);
9282     unsigned X86Opcode;
9283     unsigned X86Cond;
9284     SDVTList VTs;
9285     switch (CondOpcode) {
9286     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9287     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9288     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9289     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9290     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9291     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9292     default: llvm_unreachable("unexpected overflowing operator");
9293     }
9294     if (CondOpcode == ISD::UMULO)
9295       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9296                           MVT::i32);
9297     else
9298       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9299
9300     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9301
9302     if (CondOpcode == ISD::UMULO)
9303       Cond = X86Op.getValue(2);
9304     else
9305       Cond = X86Op.getValue(1);
9306
9307     CC = DAG.getConstant(X86Cond, MVT::i8);
9308     addTest = false;
9309   }
9310
9311   if (addTest) {
9312     // Look pass the truncate if the high bits are known zero.
9313     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9314         Cond = Cond.getOperand(0);
9315
9316     // We know the result of AND is compared against zero. Try to match
9317     // it to BT.
9318     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9319       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9320       if (NewSetCC.getNode()) {
9321         CC = NewSetCC.getOperand(0);
9322         Cond = NewSetCC.getOperand(1);
9323         addTest = false;
9324       }
9325     }
9326   }
9327
9328   if (addTest) {
9329     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9330     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9331   }
9332
9333   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9334   // a <  b ?  0 : -1 -> RES = setcc_carry
9335   // a >= b ? -1 :  0 -> RES = setcc_carry
9336   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9337   if (Cond.getOpcode() == X86ISD::SUB) {
9338     Cond = ConvertCmpIfNecessary(Cond, DAG);
9339     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9340
9341     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9342         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9343       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9344                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9345       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9346         return DAG.getNOT(DL, Res, Res.getValueType());
9347       return Res;
9348     }
9349   }
9350
9351   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9352   // widen the cmov and push the truncate through. This avoids introducing a new
9353   // branch during isel and doesn't add any extensions.
9354   if (Op.getValueType() == MVT::i8 &&
9355       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9356     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9357     if (T1.getValueType() == T2.getValueType() &&
9358         // Blacklist CopyFromReg to avoid partial register stalls.
9359         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9360       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9361       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9362       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9363     }
9364   }
9365
9366   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9367   // condition is true.
9368   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9369   SDValue Ops[] = { Op2, Op1, CC, Cond };
9370   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9371 }
9372
9373 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9374 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9375 // from the AND / OR.
9376 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9377   Opc = Op.getOpcode();
9378   if (Opc != ISD::OR && Opc != ISD::AND)
9379     return false;
9380   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9381           Op.getOperand(0).hasOneUse() &&
9382           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9383           Op.getOperand(1).hasOneUse());
9384 }
9385
9386 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9387 // 1 and that the SETCC node has a single use.
9388 static bool isXor1OfSetCC(SDValue Op) {
9389   if (Op.getOpcode() != ISD::XOR)
9390     return false;
9391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9392   if (N1C && N1C->getAPIntValue() == 1) {
9393     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9394       Op.getOperand(0).hasOneUse();
9395   }
9396   return false;
9397 }
9398
9399 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9400   bool addTest = true;
9401   SDValue Chain = Op.getOperand(0);
9402   SDValue Cond  = Op.getOperand(1);
9403   SDValue Dest  = Op.getOperand(2);
9404   DebugLoc dl = Op.getDebugLoc();
9405   SDValue CC;
9406   bool Inverted = false;
9407
9408   if (Cond.getOpcode() == ISD::SETCC) {
9409     // Check for setcc([su]{add,sub,mul}o == 0).
9410     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9411         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9412         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9413         Cond.getOperand(0).getResNo() == 1 &&
9414         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9415          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9416          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9417          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9418          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9419          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9420       Inverted = true;
9421       Cond = Cond.getOperand(0);
9422     } else {
9423       SDValue NewCond = LowerSETCC(Cond, DAG);
9424       if (NewCond.getNode())
9425         Cond = NewCond;
9426     }
9427   }
9428 #if 0
9429   // FIXME: LowerXALUO doesn't handle these!!
9430   else if (Cond.getOpcode() == X86ISD::ADD  ||
9431            Cond.getOpcode() == X86ISD::SUB  ||
9432            Cond.getOpcode() == X86ISD::SMUL ||
9433            Cond.getOpcode() == X86ISD::UMUL)
9434     Cond = LowerXALUO(Cond, DAG);
9435 #endif
9436
9437   // Look pass (and (setcc_carry (cmp ...)), 1).
9438   if (Cond.getOpcode() == ISD::AND &&
9439       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9440     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9441     if (C && C->getAPIntValue() == 1)
9442       Cond = Cond.getOperand(0);
9443   }
9444
9445   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9446   // setting operand in place of the X86ISD::SETCC.
9447   unsigned CondOpcode = Cond.getOpcode();
9448   if (CondOpcode == X86ISD::SETCC ||
9449       CondOpcode == X86ISD::SETCC_CARRY) {
9450     CC = Cond.getOperand(0);
9451
9452     SDValue Cmp = Cond.getOperand(1);
9453     unsigned Opc = Cmp.getOpcode();
9454     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9455     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9456       Cond = Cmp;
9457       addTest = false;
9458     } else {
9459       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9460       default: break;
9461       case X86::COND_O:
9462       case X86::COND_B:
9463         // These can only come from an arithmetic instruction with overflow,
9464         // e.g. SADDO, UADDO.
9465         Cond = Cond.getNode()->getOperand(1);
9466         addTest = false;
9467         break;
9468       }
9469     }
9470   }
9471   CondOpcode = Cond.getOpcode();
9472   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9473       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9474       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9475        Cond.getOperand(0).getValueType() != MVT::i8)) {
9476     SDValue LHS = Cond.getOperand(0);
9477     SDValue RHS = Cond.getOperand(1);
9478     unsigned X86Opcode;
9479     unsigned X86Cond;
9480     SDVTList VTs;
9481     switch (CondOpcode) {
9482     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9483     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9484     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9485     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9486     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9487     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9488     default: llvm_unreachable("unexpected overflowing operator");
9489     }
9490     if (Inverted)
9491       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9492     if (CondOpcode == ISD::UMULO)
9493       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9494                           MVT::i32);
9495     else
9496       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9497
9498     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9499
9500     if (CondOpcode == ISD::UMULO)
9501       Cond = X86Op.getValue(2);
9502     else
9503       Cond = X86Op.getValue(1);
9504
9505     CC = DAG.getConstant(X86Cond, MVT::i8);
9506     addTest = false;
9507   } else {
9508     unsigned CondOpc;
9509     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9510       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9511       if (CondOpc == ISD::OR) {
9512         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9513         // two branches instead of an explicit OR instruction with a
9514         // separate test.
9515         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9516             isX86LogicalCmp(Cmp)) {
9517           CC = Cond.getOperand(0).getOperand(0);
9518           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9519                               Chain, Dest, CC, Cmp);
9520           CC = Cond.getOperand(1).getOperand(0);
9521           Cond = Cmp;
9522           addTest = false;
9523         }
9524       } else { // ISD::AND
9525         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9526         // two branches instead of an explicit AND instruction with a
9527         // separate test. However, we only do this if this block doesn't
9528         // have a fall-through edge, because this requires an explicit
9529         // jmp when the condition is false.
9530         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9531             isX86LogicalCmp(Cmp) &&
9532             Op.getNode()->hasOneUse()) {
9533           X86::CondCode CCode =
9534             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9535           CCode = X86::GetOppositeBranchCondition(CCode);
9536           CC = DAG.getConstant(CCode, MVT::i8);
9537           SDNode *User = *Op.getNode()->use_begin();
9538           // Look for an unconditional branch following this conditional branch.
9539           // We need this because we need to reverse the successors in order
9540           // to implement FCMP_OEQ.
9541           if (User->getOpcode() == ISD::BR) {
9542             SDValue FalseBB = User->getOperand(1);
9543             SDNode *NewBR =
9544               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9545             assert(NewBR == User);
9546             (void)NewBR;
9547             Dest = FalseBB;
9548
9549             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9550                                 Chain, Dest, CC, Cmp);
9551             X86::CondCode CCode =
9552               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9553             CCode = X86::GetOppositeBranchCondition(CCode);
9554             CC = DAG.getConstant(CCode, MVT::i8);
9555             Cond = Cmp;
9556             addTest = false;
9557           }
9558         }
9559       }
9560     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9561       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9562       // It should be transformed during dag combiner except when the condition
9563       // is set by a arithmetics with overflow node.
9564       X86::CondCode CCode =
9565         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9566       CCode = X86::GetOppositeBranchCondition(CCode);
9567       CC = DAG.getConstant(CCode, MVT::i8);
9568       Cond = Cond.getOperand(0).getOperand(1);
9569       addTest = false;
9570     } else if (Cond.getOpcode() == ISD::SETCC &&
9571                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9572       // For FCMP_OEQ, we can emit
9573       // two branches instead of an explicit AND instruction with a
9574       // separate test. However, we only do this if this block doesn't
9575       // have a fall-through edge, because this requires an explicit
9576       // jmp when the condition is false.
9577       if (Op.getNode()->hasOneUse()) {
9578         SDNode *User = *Op.getNode()->use_begin();
9579         // Look for an unconditional branch following this conditional branch.
9580         // We need this because we need to reverse the successors in order
9581         // to implement FCMP_OEQ.
9582         if (User->getOpcode() == ISD::BR) {
9583           SDValue FalseBB = User->getOperand(1);
9584           SDNode *NewBR =
9585             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9586           assert(NewBR == User);
9587           (void)NewBR;
9588           Dest = FalseBB;
9589
9590           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9591                                     Cond.getOperand(0), Cond.getOperand(1));
9592           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9593           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9594           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9595                               Chain, Dest, CC, Cmp);
9596           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9597           Cond = Cmp;
9598           addTest = false;
9599         }
9600       }
9601     } else if (Cond.getOpcode() == ISD::SETCC &&
9602                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9603       // For FCMP_UNE, we can emit
9604       // two branches instead of an explicit AND instruction with a
9605       // separate test. However, we only do this if this block doesn't
9606       // have a fall-through edge, because this requires an explicit
9607       // jmp when the condition is false.
9608       if (Op.getNode()->hasOneUse()) {
9609         SDNode *User = *Op.getNode()->use_begin();
9610         // Look for an unconditional branch following this conditional branch.
9611         // We need this because we need to reverse the successors in order
9612         // to implement FCMP_UNE.
9613         if (User->getOpcode() == ISD::BR) {
9614           SDValue FalseBB = User->getOperand(1);
9615           SDNode *NewBR =
9616             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9617           assert(NewBR == User);
9618           (void)NewBR;
9619
9620           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9621                                     Cond.getOperand(0), Cond.getOperand(1));
9622           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9623           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9624           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9625                               Chain, Dest, CC, Cmp);
9626           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9627           Cond = Cmp;
9628           addTest = false;
9629           Dest = FalseBB;
9630         }
9631       }
9632     }
9633   }
9634
9635   if (addTest) {
9636     // Look pass the truncate if the high bits are known zero.
9637     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9638         Cond = Cond.getOperand(0);
9639
9640     // We know the result of AND is compared against zero. Try to match
9641     // it to BT.
9642     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9643       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9644       if (NewSetCC.getNode()) {
9645         CC = NewSetCC.getOperand(0);
9646         Cond = NewSetCC.getOperand(1);
9647         addTest = false;
9648       }
9649     }
9650   }
9651
9652   if (addTest) {
9653     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9654     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9655   }
9656   Cond = ConvertCmpIfNecessary(Cond, DAG);
9657   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9658                      Chain, Dest, CC, Cond);
9659 }
9660
9661
9662 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9663 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9664 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9665 // that the guard pages used by the OS virtual memory manager are allocated in
9666 // correct sequence.
9667 SDValue
9668 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9669                                            SelectionDAG &DAG) const {
9670   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9671           getTargetMachine().Options.EnableSegmentedStacks) &&
9672          "This should be used only on Windows targets or when segmented stacks "
9673          "are being used");
9674   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9675   DebugLoc dl = Op.getDebugLoc();
9676
9677   // Get the inputs.
9678   SDValue Chain = Op.getOperand(0);
9679   SDValue Size  = Op.getOperand(1);
9680   // FIXME: Ensure alignment here
9681
9682   bool Is64Bit = Subtarget->is64Bit();
9683   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9684
9685   if (getTargetMachine().Options.EnableSegmentedStacks) {
9686     MachineFunction &MF = DAG.getMachineFunction();
9687     MachineRegisterInfo &MRI = MF.getRegInfo();
9688
9689     if (Is64Bit) {
9690       // The 64 bit implementation of segmented stacks needs to clobber both r10
9691       // r11. This makes it impossible to use it along with nested parameters.
9692       const Function *F = MF.getFunction();
9693
9694       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9695            I != E; ++I)
9696         if (I->hasNestAttr())
9697           report_fatal_error("Cannot use segmented stacks with functions that "
9698                              "have nested arguments.");
9699     }
9700
9701     const TargetRegisterClass *AddrRegClass =
9702       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9703     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9704     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9705     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9706                                 DAG.getRegister(Vreg, SPTy));
9707     SDValue Ops1[2] = { Value, Chain };
9708     return DAG.getMergeValues(Ops1, 2, dl);
9709   } else {
9710     SDValue Flag;
9711     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9712
9713     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9714     Flag = Chain.getValue(1);
9715     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9716
9717     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9718     Flag = Chain.getValue(1);
9719
9720     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9721
9722     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9723     return DAG.getMergeValues(Ops1, 2, dl);
9724   }
9725 }
9726
9727 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9728   MachineFunction &MF = DAG.getMachineFunction();
9729   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9730
9731   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9732   DebugLoc DL = Op.getDebugLoc();
9733
9734   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9735     // vastart just stores the address of the VarArgsFrameIndex slot into the
9736     // memory location argument.
9737     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9738                                    getPointerTy());
9739     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9740                         MachinePointerInfo(SV), false, false, 0);
9741   }
9742
9743   // __va_list_tag:
9744   //   gp_offset         (0 - 6 * 8)
9745   //   fp_offset         (48 - 48 + 8 * 16)
9746   //   overflow_arg_area (point to parameters coming in memory).
9747   //   reg_save_area
9748   SmallVector<SDValue, 8> MemOps;
9749   SDValue FIN = Op.getOperand(1);
9750   // Store gp_offset
9751   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9752                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9753                                                MVT::i32),
9754                                FIN, MachinePointerInfo(SV), false, false, 0);
9755   MemOps.push_back(Store);
9756
9757   // Store fp_offset
9758   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9759                     FIN, DAG.getIntPtrConstant(4));
9760   Store = DAG.getStore(Op.getOperand(0), DL,
9761                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9762                                        MVT::i32),
9763                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9764   MemOps.push_back(Store);
9765
9766   // Store ptr to overflow_arg_area
9767   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9768                     FIN, DAG.getIntPtrConstant(4));
9769   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9770                                     getPointerTy());
9771   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9772                        MachinePointerInfo(SV, 8),
9773                        false, false, 0);
9774   MemOps.push_back(Store);
9775
9776   // Store ptr to reg_save_area.
9777   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9778                     FIN, DAG.getIntPtrConstant(8));
9779   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9780                                     getPointerTy());
9781   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9782                        MachinePointerInfo(SV, 16), false, false, 0);
9783   MemOps.push_back(Store);
9784   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9785                      &MemOps[0], MemOps.size());
9786 }
9787
9788 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9789   assert(Subtarget->is64Bit() &&
9790          "LowerVAARG only handles 64-bit va_arg!");
9791   assert((Subtarget->isTargetLinux() ||
9792           Subtarget->isTargetDarwin()) &&
9793           "Unhandled target in LowerVAARG");
9794   assert(Op.getNode()->getNumOperands() == 4);
9795   SDValue Chain = Op.getOperand(0);
9796   SDValue SrcPtr = Op.getOperand(1);
9797   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9798   unsigned Align = Op.getConstantOperandVal(3);
9799   DebugLoc dl = Op.getDebugLoc();
9800
9801   EVT ArgVT = Op.getNode()->getValueType(0);
9802   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9803   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9804   uint8_t ArgMode;
9805
9806   // Decide which area this value should be read from.
9807   // TODO: Implement the AMD64 ABI in its entirety. This simple
9808   // selection mechanism works only for the basic types.
9809   if (ArgVT == MVT::f80) {
9810     llvm_unreachable("va_arg for f80 not yet implemented");
9811   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9812     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9813   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9814     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9815   } else {
9816     llvm_unreachable("Unhandled argument type in LowerVAARG");
9817   }
9818
9819   if (ArgMode == 2) {
9820     // Sanity Check: Make sure using fp_offset makes sense.
9821     assert(!getTargetMachine().Options.UseSoftFloat &&
9822            !(DAG.getMachineFunction()
9823                 .getFunction()->getFnAttributes()
9824                 .hasAttribute(Attributes::NoImplicitFloat)) &&
9825            Subtarget->hasSSE1());
9826   }
9827
9828   // Insert VAARG_64 node into the DAG
9829   // VAARG_64 returns two values: Variable Argument Address, Chain
9830   SmallVector<SDValue, 11> InstOps;
9831   InstOps.push_back(Chain);
9832   InstOps.push_back(SrcPtr);
9833   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9834   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9835   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9836   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9837   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9838                                           VTs, &InstOps[0], InstOps.size(),
9839                                           MVT::i64,
9840                                           MachinePointerInfo(SV),
9841                                           /*Align=*/0,
9842                                           /*Volatile=*/false,
9843                                           /*ReadMem=*/true,
9844                                           /*WriteMem=*/true);
9845   Chain = VAARG.getValue(1);
9846
9847   // Load the next argument and return it
9848   return DAG.getLoad(ArgVT, dl,
9849                      Chain,
9850                      VAARG,
9851                      MachinePointerInfo(),
9852                      false, false, false, 0);
9853 }
9854
9855 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9856                            SelectionDAG &DAG) {
9857   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9858   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9859   SDValue Chain = Op.getOperand(0);
9860   SDValue DstPtr = Op.getOperand(1);
9861   SDValue SrcPtr = Op.getOperand(2);
9862   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9863   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9864   DebugLoc DL = Op.getDebugLoc();
9865
9866   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9867                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9868                        false,
9869                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9870 }
9871
9872 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9873 // may or may not be a constant. Takes immediate version of shift as input.
9874 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9875                                    SDValue SrcOp, SDValue ShAmt,
9876                                    SelectionDAG &DAG) {
9877   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9878
9879   if (isa<ConstantSDNode>(ShAmt)) {
9880     // Constant may be a TargetConstant. Use a regular constant.
9881     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9882     switch (Opc) {
9883       default: llvm_unreachable("Unknown target vector shift node");
9884       case X86ISD::VSHLI:
9885       case X86ISD::VSRLI:
9886       case X86ISD::VSRAI:
9887         return DAG.getNode(Opc, dl, VT, SrcOp,
9888                            DAG.getConstant(ShiftAmt, MVT::i32));
9889     }
9890   }
9891
9892   // Change opcode to non-immediate version
9893   switch (Opc) {
9894     default: llvm_unreachable("Unknown target vector shift node");
9895     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9896     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9897     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9898   }
9899
9900   // Need to build a vector containing shift amount
9901   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9902   SDValue ShOps[4];
9903   ShOps[0] = ShAmt;
9904   ShOps[1] = DAG.getConstant(0, MVT::i32);
9905   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9906   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9907
9908   // The return type has to be a 128-bit type with the same element
9909   // type as the input type.
9910   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9911   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9912
9913   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9914   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9915 }
9916
9917 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9918   DebugLoc dl = Op.getDebugLoc();
9919   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9920   switch (IntNo) {
9921   default: return SDValue();    // Don't custom lower most intrinsics.
9922   // Comparison intrinsics.
9923   case Intrinsic::x86_sse_comieq_ss:
9924   case Intrinsic::x86_sse_comilt_ss:
9925   case Intrinsic::x86_sse_comile_ss:
9926   case Intrinsic::x86_sse_comigt_ss:
9927   case Intrinsic::x86_sse_comige_ss:
9928   case Intrinsic::x86_sse_comineq_ss:
9929   case Intrinsic::x86_sse_ucomieq_ss:
9930   case Intrinsic::x86_sse_ucomilt_ss:
9931   case Intrinsic::x86_sse_ucomile_ss:
9932   case Intrinsic::x86_sse_ucomigt_ss:
9933   case Intrinsic::x86_sse_ucomige_ss:
9934   case Intrinsic::x86_sse_ucomineq_ss:
9935   case Intrinsic::x86_sse2_comieq_sd:
9936   case Intrinsic::x86_sse2_comilt_sd:
9937   case Intrinsic::x86_sse2_comile_sd:
9938   case Intrinsic::x86_sse2_comigt_sd:
9939   case Intrinsic::x86_sse2_comige_sd:
9940   case Intrinsic::x86_sse2_comineq_sd:
9941   case Intrinsic::x86_sse2_ucomieq_sd:
9942   case Intrinsic::x86_sse2_ucomilt_sd:
9943   case Intrinsic::x86_sse2_ucomile_sd:
9944   case Intrinsic::x86_sse2_ucomigt_sd:
9945   case Intrinsic::x86_sse2_ucomige_sd:
9946   case Intrinsic::x86_sse2_ucomineq_sd: {
9947     unsigned Opc;
9948     ISD::CondCode CC;
9949     switch (IntNo) {
9950     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9951     case Intrinsic::x86_sse_comieq_ss:
9952     case Intrinsic::x86_sse2_comieq_sd:
9953       Opc = X86ISD::COMI;
9954       CC = ISD::SETEQ;
9955       break;
9956     case Intrinsic::x86_sse_comilt_ss:
9957     case Intrinsic::x86_sse2_comilt_sd:
9958       Opc = X86ISD::COMI;
9959       CC = ISD::SETLT;
9960       break;
9961     case Intrinsic::x86_sse_comile_ss:
9962     case Intrinsic::x86_sse2_comile_sd:
9963       Opc = X86ISD::COMI;
9964       CC = ISD::SETLE;
9965       break;
9966     case Intrinsic::x86_sse_comigt_ss:
9967     case Intrinsic::x86_sse2_comigt_sd:
9968       Opc = X86ISD::COMI;
9969       CC = ISD::SETGT;
9970       break;
9971     case Intrinsic::x86_sse_comige_ss:
9972     case Intrinsic::x86_sse2_comige_sd:
9973       Opc = X86ISD::COMI;
9974       CC = ISD::SETGE;
9975       break;
9976     case Intrinsic::x86_sse_comineq_ss:
9977     case Intrinsic::x86_sse2_comineq_sd:
9978       Opc = X86ISD::COMI;
9979       CC = ISD::SETNE;
9980       break;
9981     case Intrinsic::x86_sse_ucomieq_ss:
9982     case Intrinsic::x86_sse2_ucomieq_sd:
9983       Opc = X86ISD::UCOMI;
9984       CC = ISD::SETEQ;
9985       break;
9986     case Intrinsic::x86_sse_ucomilt_ss:
9987     case Intrinsic::x86_sse2_ucomilt_sd:
9988       Opc = X86ISD::UCOMI;
9989       CC = ISD::SETLT;
9990       break;
9991     case Intrinsic::x86_sse_ucomile_ss:
9992     case Intrinsic::x86_sse2_ucomile_sd:
9993       Opc = X86ISD::UCOMI;
9994       CC = ISD::SETLE;
9995       break;
9996     case Intrinsic::x86_sse_ucomigt_ss:
9997     case Intrinsic::x86_sse2_ucomigt_sd:
9998       Opc = X86ISD::UCOMI;
9999       CC = ISD::SETGT;
10000       break;
10001     case Intrinsic::x86_sse_ucomige_ss:
10002     case Intrinsic::x86_sse2_ucomige_sd:
10003       Opc = X86ISD::UCOMI;
10004       CC = ISD::SETGE;
10005       break;
10006     case Intrinsic::x86_sse_ucomineq_ss:
10007     case Intrinsic::x86_sse2_ucomineq_sd:
10008       Opc = X86ISD::UCOMI;
10009       CC = ISD::SETNE;
10010       break;
10011     }
10012
10013     SDValue LHS = Op.getOperand(1);
10014     SDValue RHS = Op.getOperand(2);
10015     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10016     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10017     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10018     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10019                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10020     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10021   }
10022
10023   // Arithmetic intrinsics.
10024   case Intrinsic::x86_sse2_pmulu_dq:
10025   case Intrinsic::x86_avx2_pmulu_dq:
10026     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10027                        Op.getOperand(1), Op.getOperand(2));
10028
10029   // SSE3/AVX horizontal add/sub intrinsics
10030   case Intrinsic::x86_sse3_hadd_ps:
10031   case Intrinsic::x86_sse3_hadd_pd:
10032   case Intrinsic::x86_avx_hadd_ps_256:
10033   case Intrinsic::x86_avx_hadd_pd_256:
10034   case Intrinsic::x86_sse3_hsub_ps:
10035   case Intrinsic::x86_sse3_hsub_pd:
10036   case Intrinsic::x86_avx_hsub_ps_256:
10037   case Intrinsic::x86_avx_hsub_pd_256:
10038   case Intrinsic::x86_ssse3_phadd_w_128:
10039   case Intrinsic::x86_ssse3_phadd_d_128:
10040   case Intrinsic::x86_avx2_phadd_w:
10041   case Intrinsic::x86_avx2_phadd_d:
10042   case Intrinsic::x86_ssse3_phsub_w_128:
10043   case Intrinsic::x86_ssse3_phsub_d_128:
10044   case Intrinsic::x86_avx2_phsub_w:
10045   case Intrinsic::x86_avx2_phsub_d: {
10046     unsigned Opcode;
10047     switch (IntNo) {
10048     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10049     case Intrinsic::x86_sse3_hadd_ps:
10050     case Intrinsic::x86_sse3_hadd_pd:
10051     case Intrinsic::x86_avx_hadd_ps_256:
10052     case Intrinsic::x86_avx_hadd_pd_256:
10053       Opcode = X86ISD::FHADD;
10054       break;
10055     case Intrinsic::x86_sse3_hsub_ps:
10056     case Intrinsic::x86_sse3_hsub_pd:
10057     case Intrinsic::x86_avx_hsub_ps_256:
10058     case Intrinsic::x86_avx_hsub_pd_256:
10059       Opcode = X86ISD::FHSUB;
10060       break;
10061     case Intrinsic::x86_ssse3_phadd_w_128:
10062     case Intrinsic::x86_ssse3_phadd_d_128:
10063     case Intrinsic::x86_avx2_phadd_w:
10064     case Intrinsic::x86_avx2_phadd_d:
10065       Opcode = X86ISD::HADD;
10066       break;
10067     case Intrinsic::x86_ssse3_phsub_w_128:
10068     case Intrinsic::x86_ssse3_phsub_d_128:
10069     case Intrinsic::x86_avx2_phsub_w:
10070     case Intrinsic::x86_avx2_phsub_d:
10071       Opcode = X86ISD::HSUB;
10072       break;
10073     }
10074     return DAG.getNode(Opcode, dl, Op.getValueType(),
10075                        Op.getOperand(1), Op.getOperand(2));
10076   }
10077
10078   // AVX2 variable shift intrinsics
10079   case Intrinsic::x86_avx2_psllv_d:
10080   case Intrinsic::x86_avx2_psllv_q:
10081   case Intrinsic::x86_avx2_psllv_d_256:
10082   case Intrinsic::x86_avx2_psllv_q_256:
10083   case Intrinsic::x86_avx2_psrlv_d:
10084   case Intrinsic::x86_avx2_psrlv_q:
10085   case Intrinsic::x86_avx2_psrlv_d_256:
10086   case Intrinsic::x86_avx2_psrlv_q_256:
10087   case Intrinsic::x86_avx2_psrav_d:
10088   case Intrinsic::x86_avx2_psrav_d_256: {
10089     unsigned Opcode;
10090     switch (IntNo) {
10091     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10092     case Intrinsic::x86_avx2_psllv_d:
10093     case Intrinsic::x86_avx2_psllv_q:
10094     case Intrinsic::x86_avx2_psllv_d_256:
10095     case Intrinsic::x86_avx2_psllv_q_256:
10096       Opcode = ISD::SHL;
10097       break;
10098     case Intrinsic::x86_avx2_psrlv_d:
10099     case Intrinsic::x86_avx2_psrlv_q:
10100     case Intrinsic::x86_avx2_psrlv_d_256:
10101     case Intrinsic::x86_avx2_psrlv_q_256:
10102       Opcode = ISD::SRL;
10103       break;
10104     case Intrinsic::x86_avx2_psrav_d:
10105     case Intrinsic::x86_avx2_psrav_d_256:
10106       Opcode = ISD::SRA;
10107       break;
10108     }
10109     return DAG.getNode(Opcode, dl, Op.getValueType(),
10110                        Op.getOperand(1), Op.getOperand(2));
10111   }
10112
10113   case Intrinsic::x86_ssse3_pshuf_b_128:
10114   case Intrinsic::x86_avx2_pshuf_b:
10115     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10116                        Op.getOperand(1), Op.getOperand(2));
10117
10118   case Intrinsic::x86_ssse3_psign_b_128:
10119   case Intrinsic::x86_ssse3_psign_w_128:
10120   case Intrinsic::x86_ssse3_psign_d_128:
10121   case Intrinsic::x86_avx2_psign_b:
10122   case Intrinsic::x86_avx2_psign_w:
10123   case Intrinsic::x86_avx2_psign_d:
10124     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10125                        Op.getOperand(1), Op.getOperand(2));
10126
10127   case Intrinsic::x86_sse41_insertps:
10128     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10129                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10130
10131   case Intrinsic::x86_avx_vperm2f128_ps_256:
10132   case Intrinsic::x86_avx_vperm2f128_pd_256:
10133   case Intrinsic::x86_avx_vperm2f128_si_256:
10134   case Intrinsic::x86_avx2_vperm2i128:
10135     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10136                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10137
10138   case Intrinsic::x86_avx2_permd:
10139   case Intrinsic::x86_avx2_permps:
10140     // Operands intentionally swapped. Mask is last operand to intrinsic,
10141     // but second operand for node/intruction.
10142     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10143                        Op.getOperand(2), Op.getOperand(1));
10144
10145   // ptest and testp intrinsics. The intrinsic these come from are designed to
10146   // return an integer value, not just an instruction so lower it to the ptest
10147   // or testp pattern and a setcc for the result.
10148   case Intrinsic::x86_sse41_ptestz:
10149   case Intrinsic::x86_sse41_ptestc:
10150   case Intrinsic::x86_sse41_ptestnzc:
10151   case Intrinsic::x86_avx_ptestz_256:
10152   case Intrinsic::x86_avx_ptestc_256:
10153   case Intrinsic::x86_avx_ptestnzc_256:
10154   case Intrinsic::x86_avx_vtestz_ps:
10155   case Intrinsic::x86_avx_vtestc_ps:
10156   case Intrinsic::x86_avx_vtestnzc_ps:
10157   case Intrinsic::x86_avx_vtestz_pd:
10158   case Intrinsic::x86_avx_vtestc_pd:
10159   case Intrinsic::x86_avx_vtestnzc_pd:
10160   case Intrinsic::x86_avx_vtestz_ps_256:
10161   case Intrinsic::x86_avx_vtestc_ps_256:
10162   case Intrinsic::x86_avx_vtestnzc_ps_256:
10163   case Intrinsic::x86_avx_vtestz_pd_256:
10164   case Intrinsic::x86_avx_vtestc_pd_256:
10165   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10166     bool IsTestPacked = false;
10167     unsigned X86CC;
10168     switch (IntNo) {
10169     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10170     case Intrinsic::x86_avx_vtestz_ps:
10171     case Intrinsic::x86_avx_vtestz_pd:
10172     case Intrinsic::x86_avx_vtestz_ps_256:
10173     case Intrinsic::x86_avx_vtestz_pd_256:
10174       IsTestPacked = true; // Fallthrough
10175     case Intrinsic::x86_sse41_ptestz:
10176     case Intrinsic::x86_avx_ptestz_256:
10177       // ZF = 1
10178       X86CC = X86::COND_E;
10179       break;
10180     case Intrinsic::x86_avx_vtestc_ps:
10181     case Intrinsic::x86_avx_vtestc_pd:
10182     case Intrinsic::x86_avx_vtestc_ps_256:
10183     case Intrinsic::x86_avx_vtestc_pd_256:
10184       IsTestPacked = true; // Fallthrough
10185     case Intrinsic::x86_sse41_ptestc:
10186     case Intrinsic::x86_avx_ptestc_256:
10187       // CF = 1
10188       X86CC = X86::COND_B;
10189       break;
10190     case Intrinsic::x86_avx_vtestnzc_ps:
10191     case Intrinsic::x86_avx_vtestnzc_pd:
10192     case Intrinsic::x86_avx_vtestnzc_ps_256:
10193     case Intrinsic::x86_avx_vtestnzc_pd_256:
10194       IsTestPacked = true; // Fallthrough
10195     case Intrinsic::x86_sse41_ptestnzc:
10196     case Intrinsic::x86_avx_ptestnzc_256:
10197       // ZF and CF = 0
10198       X86CC = X86::COND_A;
10199       break;
10200     }
10201
10202     SDValue LHS = Op.getOperand(1);
10203     SDValue RHS = Op.getOperand(2);
10204     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10205     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10206     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10207     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10208     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10209   }
10210
10211   // SSE/AVX shift intrinsics
10212   case Intrinsic::x86_sse2_psll_w:
10213   case Intrinsic::x86_sse2_psll_d:
10214   case Intrinsic::x86_sse2_psll_q:
10215   case Intrinsic::x86_avx2_psll_w:
10216   case Intrinsic::x86_avx2_psll_d:
10217   case Intrinsic::x86_avx2_psll_q:
10218   case Intrinsic::x86_sse2_psrl_w:
10219   case Intrinsic::x86_sse2_psrl_d:
10220   case Intrinsic::x86_sse2_psrl_q:
10221   case Intrinsic::x86_avx2_psrl_w:
10222   case Intrinsic::x86_avx2_psrl_d:
10223   case Intrinsic::x86_avx2_psrl_q:
10224   case Intrinsic::x86_sse2_psra_w:
10225   case Intrinsic::x86_sse2_psra_d:
10226   case Intrinsic::x86_avx2_psra_w:
10227   case Intrinsic::x86_avx2_psra_d: {
10228     unsigned Opcode;
10229     switch (IntNo) {
10230     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10231     case Intrinsic::x86_sse2_psll_w:
10232     case Intrinsic::x86_sse2_psll_d:
10233     case Intrinsic::x86_sse2_psll_q:
10234     case Intrinsic::x86_avx2_psll_w:
10235     case Intrinsic::x86_avx2_psll_d:
10236     case Intrinsic::x86_avx2_psll_q:
10237       Opcode = X86ISD::VSHL;
10238       break;
10239     case Intrinsic::x86_sse2_psrl_w:
10240     case Intrinsic::x86_sse2_psrl_d:
10241     case Intrinsic::x86_sse2_psrl_q:
10242     case Intrinsic::x86_avx2_psrl_w:
10243     case Intrinsic::x86_avx2_psrl_d:
10244     case Intrinsic::x86_avx2_psrl_q:
10245       Opcode = X86ISD::VSRL;
10246       break;
10247     case Intrinsic::x86_sse2_psra_w:
10248     case Intrinsic::x86_sse2_psra_d:
10249     case Intrinsic::x86_avx2_psra_w:
10250     case Intrinsic::x86_avx2_psra_d:
10251       Opcode = X86ISD::VSRA;
10252       break;
10253     }
10254     return DAG.getNode(Opcode, dl, Op.getValueType(),
10255                        Op.getOperand(1), Op.getOperand(2));
10256   }
10257
10258   // SSE/AVX immediate shift intrinsics
10259   case Intrinsic::x86_sse2_pslli_w:
10260   case Intrinsic::x86_sse2_pslli_d:
10261   case Intrinsic::x86_sse2_pslli_q:
10262   case Intrinsic::x86_avx2_pslli_w:
10263   case Intrinsic::x86_avx2_pslli_d:
10264   case Intrinsic::x86_avx2_pslli_q:
10265   case Intrinsic::x86_sse2_psrli_w:
10266   case Intrinsic::x86_sse2_psrli_d:
10267   case Intrinsic::x86_sse2_psrli_q:
10268   case Intrinsic::x86_avx2_psrli_w:
10269   case Intrinsic::x86_avx2_psrli_d:
10270   case Intrinsic::x86_avx2_psrli_q:
10271   case Intrinsic::x86_sse2_psrai_w:
10272   case Intrinsic::x86_sse2_psrai_d:
10273   case Intrinsic::x86_avx2_psrai_w:
10274   case Intrinsic::x86_avx2_psrai_d: {
10275     unsigned Opcode;
10276     switch (IntNo) {
10277     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10278     case Intrinsic::x86_sse2_pslli_w:
10279     case Intrinsic::x86_sse2_pslli_d:
10280     case Intrinsic::x86_sse2_pslli_q:
10281     case Intrinsic::x86_avx2_pslli_w:
10282     case Intrinsic::x86_avx2_pslli_d:
10283     case Intrinsic::x86_avx2_pslli_q:
10284       Opcode = X86ISD::VSHLI;
10285       break;
10286     case Intrinsic::x86_sse2_psrli_w:
10287     case Intrinsic::x86_sse2_psrli_d:
10288     case Intrinsic::x86_sse2_psrli_q:
10289     case Intrinsic::x86_avx2_psrli_w:
10290     case Intrinsic::x86_avx2_psrli_d:
10291     case Intrinsic::x86_avx2_psrli_q:
10292       Opcode = X86ISD::VSRLI;
10293       break;
10294     case Intrinsic::x86_sse2_psrai_w:
10295     case Intrinsic::x86_sse2_psrai_d:
10296     case Intrinsic::x86_avx2_psrai_w:
10297     case Intrinsic::x86_avx2_psrai_d:
10298       Opcode = X86ISD::VSRAI;
10299       break;
10300     }
10301     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10302                                Op.getOperand(1), Op.getOperand(2), DAG);
10303   }
10304
10305   case Intrinsic::x86_sse42_pcmpistria128:
10306   case Intrinsic::x86_sse42_pcmpestria128:
10307   case Intrinsic::x86_sse42_pcmpistric128:
10308   case Intrinsic::x86_sse42_pcmpestric128:
10309   case Intrinsic::x86_sse42_pcmpistrio128:
10310   case Intrinsic::x86_sse42_pcmpestrio128:
10311   case Intrinsic::x86_sse42_pcmpistris128:
10312   case Intrinsic::x86_sse42_pcmpestris128:
10313   case Intrinsic::x86_sse42_pcmpistriz128:
10314   case Intrinsic::x86_sse42_pcmpestriz128: {
10315     unsigned Opcode;
10316     unsigned X86CC;
10317     switch (IntNo) {
10318     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10319     case Intrinsic::x86_sse42_pcmpistria128:
10320       Opcode = X86ISD::PCMPISTRI;
10321       X86CC = X86::COND_A;
10322       break;
10323     case Intrinsic::x86_sse42_pcmpestria128:
10324       Opcode = X86ISD::PCMPESTRI;
10325       X86CC = X86::COND_A;
10326       break;
10327     case Intrinsic::x86_sse42_pcmpistric128:
10328       Opcode = X86ISD::PCMPISTRI;
10329       X86CC = X86::COND_B;
10330       break;
10331     case Intrinsic::x86_sse42_pcmpestric128:
10332       Opcode = X86ISD::PCMPESTRI;
10333       X86CC = X86::COND_B;
10334       break;
10335     case Intrinsic::x86_sse42_pcmpistrio128:
10336       Opcode = X86ISD::PCMPISTRI;
10337       X86CC = X86::COND_O;
10338       break;
10339     case Intrinsic::x86_sse42_pcmpestrio128:
10340       Opcode = X86ISD::PCMPESTRI;
10341       X86CC = X86::COND_O;
10342       break;
10343     case Intrinsic::x86_sse42_pcmpistris128:
10344       Opcode = X86ISD::PCMPISTRI;
10345       X86CC = X86::COND_S;
10346       break;
10347     case Intrinsic::x86_sse42_pcmpestris128:
10348       Opcode = X86ISD::PCMPESTRI;
10349       X86CC = X86::COND_S;
10350       break;
10351     case Intrinsic::x86_sse42_pcmpistriz128:
10352       Opcode = X86ISD::PCMPISTRI;
10353       X86CC = X86::COND_E;
10354       break;
10355     case Intrinsic::x86_sse42_pcmpestriz128:
10356       Opcode = X86ISD::PCMPESTRI;
10357       X86CC = X86::COND_E;
10358       break;
10359     }
10360     SmallVector<SDValue, 5> NewOps;
10361     NewOps.append(Op->op_begin()+1, Op->op_end());
10362     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10363     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10364     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10365                                 DAG.getConstant(X86CC, MVT::i8),
10366                                 SDValue(PCMP.getNode(), 1));
10367     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10368   }
10369
10370   case Intrinsic::x86_sse42_pcmpistri128:
10371   case Intrinsic::x86_sse42_pcmpestri128: {
10372     unsigned Opcode;
10373     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10374       Opcode = X86ISD::PCMPISTRI;
10375     else
10376       Opcode = X86ISD::PCMPESTRI;
10377
10378     SmallVector<SDValue, 5> NewOps;
10379     NewOps.append(Op->op_begin()+1, Op->op_end());
10380     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10381     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10382   }
10383   case Intrinsic::x86_fma_vfmadd_ps:
10384   case Intrinsic::x86_fma_vfmadd_pd:
10385   case Intrinsic::x86_fma_vfmsub_ps:
10386   case Intrinsic::x86_fma_vfmsub_pd:
10387   case Intrinsic::x86_fma_vfnmadd_ps:
10388   case Intrinsic::x86_fma_vfnmadd_pd:
10389   case Intrinsic::x86_fma_vfnmsub_ps:
10390   case Intrinsic::x86_fma_vfnmsub_pd:
10391   case Intrinsic::x86_fma_vfmaddsub_ps:
10392   case Intrinsic::x86_fma_vfmaddsub_pd:
10393   case Intrinsic::x86_fma_vfmsubadd_ps:
10394   case Intrinsic::x86_fma_vfmsubadd_pd:
10395   case Intrinsic::x86_fma_vfmadd_ps_256:
10396   case Intrinsic::x86_fma_vfmadd_pd_256:
10397   case Intrinsic::x86_fma_vfmsub_ps_256:
10398   case Intrinsic::x86_fma_vfmsub_pd_256:
10399   case Intrinsic::x86_fma_vfnmadd_ps_256:
10400   case Intrinsic::x86_fma_vfnmadd_pd_256:
10401   case Intrinsic::x86_fma_vfnmsub_ps_256:
10402   case Intrinsic::x86_fma_vfnmsub_pd_256:
10403   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10404   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10405   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10406   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10407     unsigned Opc;
10408     switch (IntNo) {
10409     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10410     case Intrinsic::x86_fma_vfmadd_ps:
10411     case Intrinsic::x86_fma_vfmadd_pd:
10412     case Intrinsic::x86_fma_vfmadd_ps_256:
10413     case Intrinsic::x86_fma_vfmadd_pd_256:
10414       Opc = X86ISD::FMADD;
10415       break;
10416     case Intrinsic::x86_fma_vfmsub_ps:
10417     case Intrinsic::x86_fma_vfmsub_pd:
10418     case Intrinsic::x86_fma_vfmsub_ps_256:
10419     case Intrinsic::x86_fma_vfmsub_pd_256:
10420       Opc = X86ISD::FMSUB;
10421       break;
10422     case Intrinsic::x86_fma_vfnmadd_ps:
10423     case Intrinsic::x86_fma_vfnmadd_pd:
10424     case Intrinsic::x86_fma_vfnmadd_ps_256:
10425     case Intrinsic::x86_fma_vfnmadd_pd_256:
10426       Opc = X86ISD::FNMADD;
10427       break;
10428     case Intrinsic::x86_fma_vfnmsub_ps:
10429     case Intrinsic::x86_fma_vfnmsub_pd:
10430     case Intrinsic::x86_fma_vfnmsub_ps_256:
10431     case Intrinsic::x86_fma_vfnmsub_pd_256:
10432       Opc = X86ISD::FNMSUB;
10433       break;
10434     case Intrinsic::x86_fma_vfmaddsub_ps:
10435     case Intrinsic::x86_fma_vfmaddsub_pd:
10436     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10437     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10438       Opc = X86ISD::FMADDSUB;
10439       break;
10440     case Intrinsic::x86_fma_vfmsubadd_ps:
10441     case Intrinsic::x86_fma_vfmsubadd_pd:
10442     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10443     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10444       Opc = X86ISD::FMSUBADD;
10445       break;
10446     }
10447
10448     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10449                        Op.getOperand(2), Op.getOperand(3));
10450   }
10451   }
10452 }
10453
10454 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10455   DebugLoc dl = Op.getDebugLoc();
10456   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10457   switch (IntNo) {
10458   default: return SDValue();    // Don't custom lower most intrinsics.
10459
10460   // RDRAND intrinsics.
10461   case Intrinsic::x86_rdrand_16:
10462   case Intrinsic::x86_rdrand_32:
10463   case Intrinsic::x86_rdrand_64: {
10464     // Emit the node with the right value type.
10465     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10466     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10467
10468     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10469     // return the value from Rand, which is always 0, casted to i32.
10470     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10471                       DAG.getConstant(1, Op->getValueType(1)),
10472                       DAG.getConstant(X86::COND_B, MVT::i32),
10473                       SDValue(Result.getNode(), 1) };
10474     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10475                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10476                                   Ops, 4);
10477
10478     // Return { result, isValid, chain }.
10479     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10480                        SDValue(Result.getNode(), 2));
10481   }
10482   }
10483 }
10484
10485 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10486                                            SelectionDAG &DAG) const {
10487   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10488   MFI->setReturnAddressIsTaken(true);
10489
10490   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10491   DebugLoc dl = Op.getDebugLoc();
10492
10493   if (Depth > 0) {
10494     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10495     SDValue Offset =
10496       DAG.getConstant(TD->getPointerSize(0),
10497                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10498     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10499                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10500                                    FrameAddr, Offset),
10501                        MachinePointerInfo(), false, false, false, 0);
10502   }
10503
10504   // Just load the return address.
10505   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10506   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10507                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10508 }
10509
10510 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10511   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10512   MFI->setFrameAddressIsTaken(true);
10513
10514   EVT VT = Op.getValueType();
10515   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10516   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10517   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10518   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10519   while (Depth--)
10520     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10521                             MachinePointerInfo(),
10522                             false, false, false, 0);
10523   return FrameAddr;
10524 }
10525
10526 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10527                                                      SelectionDAG &DAG) const {
10528   return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10529 }
10530
10531 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10532   SDValue Chain     = Op.getOperand(0);
10533   SDValue Offset    = Op.getOperand(1);
10534   SDValue Handler   = Op.getOperand(2);
10535   DebugLoc dl       = Op.getDebugLoc();
10536
10537   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10538                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10539                                      getPointerTy());
10540   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10541
10542   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10543                                   DAG.getIntPtrConstant(TD->getPointerSize(0)));
10544   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10545   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10546                        false, false, 0);
10547   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10548
10549   return DAG.getNode(X86ISD::EH_RETURN, dl,
10550                      MVT::Other,
10551                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10552 }
10553
10554 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10555                                                SelectionDAG &DAG) const {
10556   DebugLoc DL = Op.getDebugLoc();
10557   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10558                      DAG.getVTList(MVT::i32, MVT::Other),
10559                      Op.getOperand(0), Op.getOperand(1));
10560 }
10561
10562 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10563                                                 SelectionDAG &DAG) const {
10564   DebugLoc DL = Op.getDebugLoc();
10565   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10566                      Op.getOperand(0), Op.getOperand(1));
10567 }
10568
10569 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10570   return Op.getOperand(0);
10571 }
10572
10573 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10574                                                 SelectionDAG &DAG) const {
10575   SDValue Root = Op.getOperand(0);
10576   SDValue Trmp = Op.getOperand(1); // trampoline
10577   SDValue FPtr = Op.getOperand(2); // nested function
10578   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10579   DebugLoc dl  = Op.getDebugLoc();
10580
10581   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10582   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10583
10584   if (Subtarget->is64Bit()) {
10585     SDValue OutChains[6];
10586
10587     // Large code-model.
10588     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10589     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10590
10591     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10592     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10593
10594     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10595
10596     // Load the pointer to the nested function into R11.
10597     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10598     SDValue Addr = Trmp;
10599     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10600                                 Addr, MachinePointerInfo(TrmpAddr),
10601                                 false, false, 0);
10602
10603     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10604                        DAG.getConstant(2, MVT::i64));
10605     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10606                                 MachinePointerInfo(TrmpAddr, 2),
10607                                 false, false, 2);
10608
10609     // Load the 'nest' parameter value into R10.
10610     // R10 is specified in X86CallingConv.td
10611     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10612     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10613                        DAG.getConstant(10, MVT::i64));
10614     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10615                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10616                                 false, false, 0);
10617
10618     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10619                        DAG.getConstant(12, MVT::i64));
10620     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10621                                 MachinePointerInfo(TrmpAddr, 12),
10622                                 false, false, 2);
10623
10624     // Jump to the nested function.
10625     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10626     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10627                        DAG.getConstant(20, MVT::i64));
10628     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10629                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10630                                 false, false, 0);
10631
10632     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10633     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10634                        DAG.getConstant(22, MVT::i64));
10635     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10636                                 MachinePointerInfo(TrmpAddr, 22),
10637                                 false, false, 0);
10638
10639     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10640   } else {
10641     const Function *Func =
10642       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10643     CallingConv::ID CC = Func->getCallingConv();
10644     unsigned NestReg;
10645
10646     switch (CC) {
10647     default:
10648       llvm_unreachable("Unsupported calling convention");
10649     case CallingConv::C:
10650     case CallingConv::X86_StdCall: {
10651       // Pass 'nest' parameter in ECX.
10652       // Must be kept in sync with X86CallingConv.td
10653       NestReg = X86::ECX;
10654
10655       // Check that ECX wasn't needed by an 'inreg' parameter.
10656       FunctionType *FTy = Func->getFunctionType();
10657       const AttrListPtr &Attrs = Func->getAttributes();
10658
10659       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10660         unsigned InRegCount = 0;
10661         unsigned Idx = 1;
10662
10663         for (FunctionType::param_iterator I = FTy->param_begin(),
10664              E = FTy->param_end(); I != E; ++I, ++Idx)
10665           if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10666             // FIXME: should only count parameters that are lowered to integers.
10667             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10668
10669         if (InRegCount > 2) {
10670           report_fatal_error("Nest register in use - reduce number of inreg"
10671                              " parameters!");
10672         }
10673       }
10674       break;
10675     }
10676     case CallingConv::X86_FastCall:
10677     case CallingConv::X86_ThisCall:
10678     case CallingConv::Fast:
10679       // Pass 'nest' parameter in EAX.
10680       // Must be kept in sync with X86CallingConv.td
10681       NestReg = X86::EAX;
10682       break;
10683     }
10684
10685     SDValue OutChains[4];
10686     SDValue Addr, Disp;
10687
10688     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10689                        DAG.getConstant(10, MVT::i32));
10690     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10691
10692     // This is storing the opcode for MOV32ri.
10693     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10694     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10695     OutChains[0] = DAG.getStore(Root, dl,
10696                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10697                                 Trmp, MachinePointerInfo(TrmpAddr),
10698                                 false, false, 0);
10699
10700     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10701                        DAG.getConstant(1, MVT::i32));
10702     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10703                                 MachinePointerInfo(TrmpAddr, 1),
10704                                 false, false, 1);
10705
10706     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10707     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10708                        DAG.getConstant(5, MVT::i32));
10709     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10710                                 MachinePointerInfo(TrmpAddr, 5),
10711                                 false, false, 1);
10712
10713     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10714                        DAG.getConstant(6, MVT::i32));
10715     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10716                                 MachinePointerInfo(TrmpAddr, 6),
10717                                 false, false, 1);
10718
10719     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10720   }
10721 }
10722
10723 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10724                                             SelectionDAG &DAG) const {
10725   /*
10726    The rounding mode is in bits 11:10 of FPSR, and has the following
10727    settings:
10728      00 Round to nearest
10729      01 Round to -inf
10730      10 Round to +inf
10731      11 Round to 0
10732
10733   FLT_ROUNDS, on the other hand, expects the following:
10734     -1 Undefined
10735      0 Round to 0
10736      1 Round to nearest
10737      2 Round to +inf
10738      3 Round to -inf
10739
10740   To perform the conversion, we do:
10741     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10742   */
10743
10744   MachineFunction &MF = DAG.getMachineFunction();
10745   const TargetMachine &TM = MF.getTarget();
10746   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10747   unsigned StackAlignment = TFI.getStackAlignment();
10748   EVT VT = Op.getValueType();
10749   DebugLoc DL = Op.getDebugLoc();
10750
10751   // Save FP Control Word to stack slot
10752   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10753   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10754
10755
10756   MachineMemOperand *MMO =
10757    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10758                            MachineMemOperand::MOStore, 2, 2);
10759
10760   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10761   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10762                                           DAG.getVTList(MVT::Other),
10763                                           Ops, 2, MVT::i16, MMO);
10764
10765   // Load FP Control Word from stack slot
10766   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10767                             MachinePointerInfo(), false, false, false, 0);
10768
10769   // Transform as necessary
10770   SDValue CWD1 =
10771     DAG.getNode(ISD::SRL, DL, MVT::i16,
10772                 DAG.getNode(ISD::AND, DL, MVT::i16,
10773                             CWD, DAG.getConstant(0x800, MVT::i16)),
10774                 DAG.getConstant(11, MVT::i8));
10775   SDValue CWD2 =
10776     DAG.getNode(ISD::SRL, DL, MVT::i16,
10777                 DAG.getNode(ISD::AND, DL, MVT::i16,
10778                             CWD, DAG.getConstant(0x400, MVT::i16)),
10779                 DAG.getConstant(9, MVT::i8));
10780
10781   SDValue RetVal =
10782     DAG.getNode(ISD::AND, DL, MVT::i16,
10783                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10784                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10785                             DAG.getConstant(1, MVT::i16)),
10786                 DAG.getConstant(3, MVT::i16));
10787
10788
10789   return DAG.getNode((VT.getSizeInBits() < 16 ?
10790                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10791 }
10792
10793 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10794   EVT VT = Op.getValueType();
10795   EVT OpVT = VT;
10796   unsigned NumBits = VT.getSizeInBits();
10797   DebugLoc dl = Op.getDebugLoc();
10798
10799   Op = Op.getOperand(0);
10800   if (VT == MVT::i8) {
10801     // Zero extend to i32 since there is not an i8 bsr.
10802     OpVT = MVT::i32;
10803     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10804   }
10805
10806   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10807   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10808   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10809
10810   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10811   SDValue Ops[] = {
10812     Op,
10813     DAG.getConstant(NumBits+NumBits-1, OpVT),
10814     DAG.getConstant(X86::COND_E, MVT::i8),
10815     Op.getValue(1)
10816   };
10817   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10818
10819   // Finally xor with NumBits-1.
10820   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10821
10822   if (VT == MVT::i8)
10823     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10824   return Op;
10825 }
10826
10827 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10828   EVT VT = Op.getValueType();
10829   EVT OpVT = VT;
10830   unsigned NumBits = VT.getSizeInBits();
10831   DebugLoc dl = Op.getDebugLoc();
10832
10833   Op = Op.getOperand(0);
10834   if (VT == MVT::i8) {
10835     // Zero extend to i32 since there is not an i8 bsr.
10836     OpVT = MVT::i32;
10837     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10838   }
10839
10840   // Issue a bsr (scan bits in reverse).
10841   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10842   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10843
10844   // And xor with NumBits-1.
10845   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10846
10847   if (VT == MVT::i8)
10848     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10849   return Op;
10850 }
10851
10852 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10853   EVT VT = Op.getValueType();
10854   unsigned NumBits = VT.getSizeInBits();
10855   DebugLoc dl = Op.getDebugLoc();
10856   Op = Op.getOperand(0);
10857
10858   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10859   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10860   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10861
10862   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10863   SDValue Ops[] = {
10864     Op,
10865     DAG.getConstant(NumBits, VT),
10866     DAG.getConstant(X86::COND_E, MVT::i8),
10867     Op.getValue(1)
10868   };
10869   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10870 }
10871
10872 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10873 // ones, and then concatenate the result back.
10874 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10875   EVT VT = Op.getValueType();
10876
10877   assert(VT.is256BitVector() && VT.isInteger() &&
10878          "Unsupported value type for operation");
10879
10880   unsigned NumElems = VT.getVectorNumElements();
10881   DebugLoc dl = Op.getDebugLoc();
10882
10883   // Extract the LHS vectors
10884   SDValue LHS = Op.getOperand(0);
10885   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10886   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10887
10888   // Extract the RHS vectors
10889   SDValue RHS = Op.getOperand(1);
10890   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10891   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10892
10893   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10894   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10895
10896   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10897                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10898                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10899 }
10900
10901 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10902   assert(Op.getValueType().is256BitVector() &&
10903          Op.getValueType().isInteger() &&
10904          "Only handle AVX 256-bit vector integer operation");
10905   return Lower256IntArith(Op, DAG);
10906 }
10907
10908 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10909   assert(Op.getValueType().is256BitVector() &&
10910          Op.getValueType().isInteger() &&
10911          "Only handle AVX 256-bit vector integer operation");
10912   return Lower256IntArith(Op, DAG);
10913 }
10914
10915 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10916                         SelectionDAG &DAG) {
10917   EVT VT = Op.getValueType();
10918
10919   // Decompose 256-bit ops into smaller 128-bit ops.
10920   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10921     return Lower256IntArith(Op, DAG);
10922
10923   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10924          "Only know how to lower V2I64/V4I64 multiply");
10925
10926   DebugLoc dl = Op.getDebugLoc();
10927
10928   //  Ahi = psrlqi(a, 32);
10929   //  Bhi = psrlqi(b, 32);
10930   //
10931   //  AloBlo = pmuludq(a, b);
10932   //  AloBhi = pmuludq(a, Bhi);
10933   //  AhiBlo = pmuludq(Ahi, b);
10934
10935   //  AloBhi = psllqi(AloBhi, 32);
10936   //  AhiBlo = psllqi(AhiBlo, 32);
10937   //  return AloBlo + AloBhi + AhiBlo;
10938
10939   SDValue A = Op.getOperand(0);
10940   SDValue B = Op.getOperand(1);
10941
10942   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10943
10944   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10945   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10946
10947   // Bit cast to 32-bit vectors for MULUDQ
10948   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10949   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10950   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10951   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10952   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10953
10954   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10955   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10956   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10957
10958   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10959   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10960
10961   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10962   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10963 }
10964
10965 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10966
10967   EVT VT = Op.getValueType();
10968   DebugLoc dl = Op.getDebugLoc();
10969   SDValue R = Op.getOperand(0);
10970   SDValue Amt = Op.getOperand(1);
10971   LLVMContext *Context = DAG.getContext();
10972
10973   if (!Subtarget->hasSSE2())
10974     return SDValue();
10975
10976   // Optimize shl/srl/sra with constant shift amount.
10977   if (isSplatVector(Amt.getNode())) {
10978     SDValue SclrAmt = Amt->getOperand(0);
10979     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10980       uint64_t ShiftAmt = C->getZExtValue();
10981
10982       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10983           (Subtarget->hasAVX2() &&
10984            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10985         if (Op.getOpcode() == ISD::SHL)
10986           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10987                              DAG.getConstant(ShiftAmt, MVT::i32));
10988         if (Op.getOpcode() == ISD::SRL)
10989           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10990                              DAG.getConstant(ShiftAmt, MVT::i32));
10991         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10992           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10993                              DAG.getConstant(ShiftAmt, MVT::i32));
10994       }
10995
10996       if (VT == MVT::v16i8) {
10997         if (Op.getOpcode() == ISD::SHL) {
10998           // Make a large shift.
10999           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11000                                     DAG.getConstant(ShiftAmt, MVT::i32));
11001           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11002           // Zero out the rightmost bits.
11003           SmallVector<SDValue, 16> V(16,
11004                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11005                                                      MVT::i8));
11006           return DAG.getNode(ISD::AND, dl, VT, SHL,
11007                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11008         }
11009         if (Op.getOpcode() == ISD::SRL) {
11010           // Make a large shift.
11011           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11012                                     DAG.getConstant(ShiftAmt, MVT::i32));
11013           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11014           // Zero out the leftmost bits.
11015           SmallVector<SDValue, 16> V(16,
11016                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11017                                                      MVT::i8));
11018           return DAG.getNode(ISD::AND, dl, VT, SRL,
11019                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11020         }
11021         if (Op.getOpcode() == ISD::SRA) {
11022           if (ShiftAmt == 7) {
11023             // R s>> 7  ===  R s< 0
11024             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11025             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11026           }
11027
11028           // R s>> a === ((R u>> a) ^ m) - m
11029           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11030           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11031                                                          MVT::i8));
11032           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11033           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11034           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11035           return Res;
11036         }
11037         llvm_unreachable("Unknown shift opcode.");
11038       }
11039
11040       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11041         if (Op.getOpcode() == ISD::SHL) {
11042           // Make a large shift.
11043           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11044                                     DAG.getConstant(ShiftAmt, MVT::i32));
11045           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11046           // Zero out the rightmost bits.
11047           SmallVector<SDValue, 32> V(32,
11048                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11049                                                      MVT::i8));
11050           return DAG.getNode(ISD::AND, dl, VT, SHL,
11051                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11052         }
11053         if (Op.getOpcode() == ISD::SRL) {
11054           // Make a large shift.
11055           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11056                                     DAG.getConstant(ShiftAmt, MVT::i32));
11057           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11058           // Zero out the leftmost bits.
11059           SmallVector<SDValue, 32> V(32,
11060                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11061                                                      MVT::i8));
11062           return DAG.getNode(ISD::AND, dl, VT, SRL,
11063                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11064         }
11065         if (Op.getOpcode() == ISD::SRA) {
11066           if (ShiftAmt == 7) {
11067             // R s>> 7  ===  R s< 0
11068             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11069             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11070           }
11071
11072           // R s>> a === ((R u>> a) ^ m) - m
11073           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11074           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11075                                                          MVT::i8));
11076           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11077           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11078           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11079           return Res;
11080         }
11081         llvm_unreachable("Unknown shift opcode.");
11082       }
11083     }
11084   }
11085
11086   // Lower SHL with variable shift amount.
11087   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11088     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11089                      DAG.getConstant(23, MVT::i32));
11090
11091     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11092     Constant *C = ConstantDataVector::get(*Context, CV);
11093     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11094     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11095                                  MachinePointerInfo::getConstantPool(),
11096                                  false, false, false, 16);
11097
11098     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11099     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11100     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11101     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11102   }
11103   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11104     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11105
11106     // a = a << 5;
11107     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11108                      DAG.getConstant(5, MVT::i32));
11109     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11110
11111     // Turn 'a' into a mask suitable for VSELECT
11112     SDValue VSelM = DAG.getConstant(0x80, VT);
11113     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11114     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11115
11116     SDValue CM1 = DAG.getConstant(0x0f, VT);
11117     SDValue CM2 = DAG.getConstant(0x3f, VT);
11118
11119     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11120     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11121     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11122                             DAG.getConstant(4, MVT::i32), DAG);
11123     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11124     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11125
11126     // a += a
11127     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11128     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11129     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11130
11131     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11132     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11133     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11134                             DAG.getConstant(2, MVT::i32), DAG);
11135     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11136     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11137
11138     // a += a
11139     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11140     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11141     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11142
11143     // return VSELECT(r, r+r, a);
11144     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11145                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11146     return R;
11147   }
11148
11149   // Decompose 256-bit shifts into smaller 128-bit shifts.
11150   if (VT.is256BitVector()) {
11151     unsigned NumElems = VT.getVectorNumElements();
11152     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11153     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11154
11155     // Extract the two vectors
11156     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11157     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11158
11159     // Recreate the shift amount vectors
11160     SDValue Amt1, Amt2;
11161     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11162       // Constant shift amount
11163       SmallVector<SDValue, 4> Amt1Csts;
11164       SmallVector<SDValue, 4> Amt2Csts;
11165       for (unsigned i = 0; i != NumElems/2; ++i)
11166         Amt1Csts.push_back(Amt->getOperand(i));
11167       for (unsigned i = NumElems/2; i != NumElems; ++i)
11168         Amt2Csts.push_back(Amt->getOperand(i));
11169
11170       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11171                                  &Amt1Csts[0], NumElems/2);
11172       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11173                                  &Amt2Csts[0], NumElems/2);
11174     } else {
11175       // Variable shift amount
11176       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11177       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11178     }
11179
11180     // Issue new vector shifts for the smaller types
11181     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11182     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11183
11184     // Concatenate the result back
11185     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11186   }
11187
11188   return SDValue();
11189 }
11190
11191 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11192   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11193   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11194   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11195   // has only one use.
11196   SDNode *N = Op.getNode();
11197   SDValue LHS = N->getOperand(0);
11198   SDValue RHS = N->getOperand(1);
11199   unsigned BaseOp = 0;
11200   unsigned Cond = 0;
11201   DebugLoc DL = Op.getDebugLoc();
11202   switch (Op.getOpcode()) {
11203   default: llvm_unreachable("Unknown ovf instruction!");
11204   case ISD::SADDO:
11205     // A subtract of one will be selected as a INC. Note that INC doesn't
11206     // set CF, so we can't do this for UADDO.
11207     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11208       if (C->isOne()) {
11209         BaseOp = X86ISD::INC;
11210         Cond = X86::COND_O;
11211         break;
11212       }
11213     BaseOp = X86ISD::ADD;
11214     Cond = X86::COND_O;
11215     break;
11216   case ISD::UADDO:
11217     BaseOp = X86ISD::ADD;
11218     Cond = X86::COND_B;
11219     break;
11220   case ISD::SSUBO:
11221     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11222     // set CF, so we can't do this for USUBO.
11223     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11224       if (C->isOne()) {
11225         BaseOp = X86ISD::DEC;
11226         Cond = X86::COND_O;
11227         break;
11228       }
11229     BaseOp = X86ISD::SUB;
11230     Cond = X86::COND_O;
11231     break;
11232   case ISD::USUBO:
11233     BaseOp = X86ISD::SUB;
11234     Cond = X86::COND_B;
11235     break;
11236   case ISD::SMULO:
11237     BaseOp = X86ISD::SMUL;
11238     Cond = X86::COND_O;
11239     break;
11240   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11241     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11242                                  MVT::i32);
11243     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11244
11245     SDValue SetCC =
11246       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11247                   DAG.getConstant(X86::COND_O, MVT::i32),
11248                   SDValue(Sum.getNode(), 2));
11249
11250     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11251   }
11252   }
11253
11254   // Also sets EFLAGS.
11255   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11256   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11257
11258   SDValue SetCC =
11259     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11260                 DAG.getConstant(Cond, MVT::i32),
11261                 SDValue(Sum.getNode(), 1));
11262
11263   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11264 }
11265
11266 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11267                                                   SelectionDAG &DAG) const {
11268   DebugLoc dl = Op.getDebugLoc();
11269   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11270   EVT VT = Op.getValueType();
11271
11272   if (!Subtarget->hasSSE2() || !VT.isVector())
11273     return SDValue();
11274
11275   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11276                       ExtraVT.getScalarType().getSizeInBits();
11277   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11278
11279   switch (VT.getSimpleVT().SimpleTy) {
11280     default: return SDValue();
11281     case MVT::v8i32:
11282     case MVT::v16i16:
11283       if (!Subtarget->hasAVX())
11284         return SDValue();
11285       if (!Subtarget->hasAVX2()) {
11286         // needs to be split
11287         unsigned NumElems = VT.getVectorNumElements();
11288
11289         // Extract the LHS vectors
11290         SDValue LHS = Op.getOperand(0);
11291         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11292         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11293
11294         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11295         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11296
11297         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11298         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11299         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11300                                    ExtraNumElems/2);
11301         SDValue Extra = DAG.getValueType(ExtraVT);
11302
11303         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11304         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11305
11306         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11307       }
11308       // fall through
11309     case MVT::v4i32:
11310     case MVT::v8i16: {
11311       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11312                                          Op.getOperand(0), ShAmt, DAG);
11313       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11314     }
11315   }
11316 }
11317
11318
11319 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11320                               SelectionDAG &DAG) {
11321   DebugLoc dl = Op.getDebugLoc();
11322
11323   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11324   // There isn't any reason to disable it if the target processor supports it.
11325   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11326     SDValue Chain = Op.getOperand(0);
11327     SDValue Zero = DAG.getConstant(0, MVT::i32);
11328     SDValue Ops[] = {
11329       DAG.getRegister(X86::ESP, MVT::i32), // Base
11330       DAG.getTargetConstant(1, MVT::i8),   // Scale
11331       DAG.getRegister(0, MVT::i32),        // Index
11332       DAG.getTargetConstant(0, MVT::i32),  // Disp
11333       DAG.getRegister(0, MVT::i32),        // Segment.
11334       Zero,
11335       Chain
11336     };
11337     SDNode *Res =
11338       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11339                           array_lengthof(Ops));
11340     return SDValue(Res, 0);
11341   }
11342
11343   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11344   if (!isDev)
11345     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11346
11347   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11348   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11349   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11350   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11351
11352   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11353   if (!Op1 && !Op2 && !Op3 && Op4)
11354     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11355
11356   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11357   if (Op1 && !Op2 && !Op3 && !Op4)
11358     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11359
11360   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11361   //           (MFENCE)>;
11362   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11363 }
11364
11365 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11366                                  SelectionDAG &DAG) {
11367   DebugLoc dl = Op.getDebugLoc();
11368   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11369     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11370   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11371     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11372
11373   // The only fence that needs an instruction is a sequentially-consistent
11374   // cross-thread fence.
11375   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11376     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11377     // no-sse2). There isn't any reason to disable it if the target processor
11378     // supports it.
11379     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11380       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11381
11382     SDValue Chain = Op.getOperand(0);
11383     SDValue Zero = DAG.getConstant(0, MVT::i32);
11384     SDValue Ops[] = {
11385       DAG.getRegister(X86::ESP, MVT::i32), // Base
11386       DAG.getTargetConstant(1, MVT::i8),   // Scale
11387       DAG.getRegister(0, MVT::i32),        // Index
11388       DAG.getTargetConstant(0, MVT::i32),  // Disp
11389       DAG.getRegister(0, MVT::i32),        // Segment.
11390       Zero,
11391       Chain
11392     };
11393     SDNode *Res =
11394       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11395                          array_lengthof(Ops));
11396     return SDValue(Res, 0);
11397   }
11398
11399   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11400   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11401 }
11402
11403
11404 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11405                              SelectionDAG &DAG) {
11406   EVT T = Op.getValueType();
11407   DebugLoc DL = Op.getDebugLoc();
11408   unsigned Reg = 0;
11409   unsigned size = 0;
11410   switch(T.getSimpleVT().SimpleTy) {
11411   default: llvm_unreachable("Invalid value type!");
11412   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11413   case MVT::i16: Reg = X86::AX;  size = 2; break;
11414   case MVT::i32: Reg = X86::EAX; size = 4; break;
11415   case MVT::i64:
11416     assert(Subtarget->is64Bit() && "Node not type legal!");
11417     Reg = X86::RAX; size = 8;
11418     break;
11419   }
11420   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11421                                     Op.getOperand(2), SDValue());
11422   SDValue Ops[] = { cpIn.getValue(0),
11423                     Op.getOperand(1),
11424                     Op.getOperand(3),
11425                     DAG.getTargetConstant(size, MVT::i8),
11426                     cpIn.getValue(1) };
11427   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11428   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11429   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11430                                            Ops, 5, T, MMO);
11431   SDValue cpOut =
11432     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11433   return cpOut;
11434 }
11435
11436 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11437                                      SelectionDAG &DAG) {
11438   assert(Subtarget->is64Bit() && "Result not type legalized?");
11439   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11440   SDValue TheChain = Op.getOperand(0);
11441   DebugLoc dl = Op.getDebugLoc();
11442   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11443   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11444   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11445                                    rax.getValue(2));
11446   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11447                             DAG.getConstant(32, MVT::i8));
11448   SDValue Ops[] = {
11449     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11450     rdx.getValue(1)
11451   };
11452   return DAG.getMergeValues(Ops, 2, dl);
11453 }
11454
11455 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11456   EVT SrcVT = Op.getOperand(0).getValueType();
11457   EVT DstVT = Op.getValueType();
11458   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11459          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11460   assert((DstVT == MVT::i64 ||
11461           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11462          "Unexpected custom BITCAST");
11463   // i64 <=> MMX conversions are Legal.
11464   if (SrcVT==MVT::i64 && DstVT.isVector())
11465     return Op;
11466   if (DstVT==MVT::i64 && SrcVT.isVector())
11467     return Op;
11468   // MMX <=> MMX conversions are Legal.
11469   if (SrcVT.isVector() && DstVT.isVector())
11470     return Op;
11471   // All other conversions need to be expanded.
11472   return SDValue();
11473 }
11474
11475 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11476   SDNode *Node = Op.getNode();
11477   DebugLoc dl = Node->getDebugLoc();
11478   EVT T = Node->getValueType(0);
11479   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11480                               DAG.getConstant(0, T), Node->getOperand(2));
11481   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11482                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11483                        Node->getOperand(0),
11484                        Node->getOperand(1), negOp,
11485                        cast<AtomicSDNode>(Node)->getSrcValue(),
11486                        cast<AtomicSDNode>(Node)->getAlignment(),
11487                        cast<AtomicSDNode>(Node)->getOrdering(),
11488                        cast<AtomicSDNode>(Node)->getSynchScope());
11489 }
11490
11491 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11492   SDNode *Node = Op.getNode();
11493   DebugLoc dl = Node->getDebugLoc();
11494   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11495
11496   // Convert seq_cst store -> xchg
11497   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11498   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11499   //        (The only way to get a 16-byte store is cmpxchg16b)
11500   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11501   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11502       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11503     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11504                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11505                                  Node->getOperand(0),
11506                                  Node->getOperand(1), Node->getOperand(2),
11507                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11508                                  cast<AtomicSDNode>(Node)->getOrdering(),
11509                                  cast<AtomicSDNode>(Node)->getSynchScope());
11510     return Swap.getValue(1);
11511   }
11512   // Other atomic stores have a simple pattern.
11513   return Op;
11514 }
11515
11516 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11517   EVT VT = Op.getNode()->getValueType(0);
11518
11519   // Let legalize expand this if it isn't a legal type yet.
11520   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11521     return SDValue();
11522
11523   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11524
11525   unsigned Opc;
11526   bool ExtraOp = false;
11527   switch (Op.getOpcode()) {
11528   default: llvm_unreachable("Invalid code");
11529   case ISD::ADDC: Opc = X86ISD::ADD; break;
11530   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11531   case ISD::SUBC: Opc = X86ISD::SUB; break;
11532   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11533   }
11534
11535   if (!ExtraOp)
11536     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11537                        Op.getOperand(1));
11538   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11539                      Op.getOperand(1), Op.getOperand(2));
11540 }
11541
11542 /// LowerOperation - Provide custom lowering hooks for some operations.
11543 ///
11544 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11545   switch (Op.getOpcode()) {
11546   default: llvm_unreachable("Should not custom lower this!");
11547   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11548   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
11549   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11550   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
11551   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11552   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11553   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11554   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11555   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11556   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11557   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11558   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11559   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11560   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11561   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11562   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11563   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11564   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11565   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11566   case ISD::SHL_PARTS:
11567   case ISD::SRA_PARTS:
11568   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11569   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11570   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11571   case ISD::TRUNCATE:           return lowerTRUNCATE(Op, DAG);
11572   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11573   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11574   case ISD::FP_EXTEND:          return lowerFP_EXTEND(Op, DAG);
11575   case ISD::FABS:               return LowerFABS(Op, DAG);
11576   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11577   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11578   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11579   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11580   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11581   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11582   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11583   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11584   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11585   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
11586   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11587   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11588   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11589   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11590   case ISD::FRAME_TO_ARGS_OFFSET:
11591                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11592   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11593   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11594   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11595   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11596   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11597   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11598   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11599   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11600   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11601   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11602   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
11603   case ISD::SRA:
11604   case ISD::SRL:
11605   case ISD::SHL:                return LowerShift(Op, DAG);
11606   case ISD::SADDO:
11607   case ISD::UADDO:
11608   case ISD::SSUBO:
11609   case ISD::USUBO:
11610   case ISD::SMULO:
11611   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11612   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11613   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11614   case ISD::ADDC:
11615   case ISD::ADDE:
11616   case ISD::SUBC:
11617   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11618   case ISD::ADD:                return LowerADD(Op, DAG);
11619   case ISD::SUB:                return LowerSUB(Op, DAG);
11620   }
11621 }
11622
11623 static void ReplaceATOMIC_LOAD(SDNode *Node,
11624                                   SmallVectorImpl<SDValue> &Results,
11625                                   SelectionDAG &DAG) {
11626   DebugLoc dl = Node->getDebugLoc();
11627   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11628
11629   // Convert wide load -> cmpxchg8b/cmpxchg16b
11630   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11631   //        (The only way to get a 16-byte load is cmpxchg16b)
11632   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11633   SDValue Zero = DAG.getConstant(0, VT);
11634   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11635                                Node->getOperand(0),
11636                                Node->getOperand(1), Zero, Zero,
11637                                cast<AtomicSDNode>(Node)->getMemOperand(),
11638                                cast<AtomicSDNode>(Node)->getOrdering(),
11639                                cast<AtomicSDNode>(Node)->getSynchScope());
11640   Results.push_back(Swap.getValue(0));
11641   Results.push_back(Swap.getValue(1));
11642 }
11643
11644 static void
11645 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11646                         SelectionDAG &DAG, unsigned NewOp) {
11647   DebugLoc dl = Node->getDebugLoc();
11648   assert (Node->getValueType(0) == MVT::i64 &&
11649           "Only know how to expand i64 atomics");
11650
11651   SDValue Chain = Node->getOperand(0);
11652   SDValue In1 = Node->getOperand(1);
11653   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11654                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11655   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11656                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11657   SDValue Ops[] = { Chain, In1, In2L, In2H };
11658   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11659   SDValue Result =
11660     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11661                             cast<MemSDNode>(Node)->getMemOperand());
11662   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11663   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11664   Results.push_back(Result.getValue(2));
11665 }
11666
11667 /// ReplaceNodeResults - Replace a node with an illegal result type
11668 /// with a new node built out of custom code.
11669 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11670                                            SmallVectorImpl<SDValue>&Results,
11671                                            SelectionDAG &DAG) const {
11672   DebugLoc dl = N->getDebugLoc();
11673   switch (N->getOpcode()) {
11674   default:
11675     llvm_unreachable("Do not know how to custom type legalize this operation!");
11676   case ISD::SIGN_EXTEND_INREG:
11677   case ISD::ADDC:
11678   case ISD::ADDE:
11679   case ISD::SUBC:
11680   case ISD::SUBE:
11681     // We don't want to expand or promote these.
11682     return;
11683   case ISD::FP_TO_SINT:
11684   case ISD::FP_TO_UINT: {
11685     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11686
11687     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11688       return;
11689
11690     std::pair<SDValue,SDValue> Vals =
11691         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11692     SDValue FIST = Vals.first, StackSlot = Vals.second;
11693     if (FIST.getNode() != 0) {
11694       EVT VT = N->getValueType(0);
11695       // Return a load from the stack slot.
11696       if (StackSlot.getNode() != 0)
11697         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11698                                       MachinePointerInfo(),
11699                                       false, false, false, 0));
11700       else
11701         Results.push_back(FIST);
11702     }
11703     return;
11704   }
11705   case ISD::FP_ROUND: {
11706     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11707     Results.push_back(V);
11708     return;
11709   }
11710   case ISD::READCYCLECOUNTER: {
11711     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11712     SDValue TheChain = N->getOperand(0);
11713     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11714     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11715                                      rd.getValue(1));
11716     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11717                                      eax.getValue(2));
11718     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11719     SDValue Ops[] = { eax, edx };
11720     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11721     Results.push_back(edx.getValue(1));
11722     return;
11723   }
11724   case ISD::ATOMIC_CMP_SWAP: {
11725     EVT T = N->getValueType(0);
11726     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11727     bool Regs64bit = T == MVT::i128;
11728     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11729     SDValue cpInL, cpInH;
11730     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11731                         DAG.getConstant(0, HalfT));
11732     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11733                         DAG.getConstant(1, HalfT));
11734     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11735                              Regs64bit ? X86::RAX : X86::EAX,
11736                              cpInL, SDValue());
11737     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11738                              Regs64bit ? X86::RDX : X86::EDX,
11739                              cpInH, cpInL.getValue(1));
11740     SDValue swapInL, swapInH;
11741     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11742                           DAG.getConstant(0, HalfT));
11743     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11744                           DAG.getConstant(1, HalfT));
11745     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11746                                Regs64bit ? X86::RBX : X86::EBX,
11747                                swapInL, cpInH.getValue(1));
11748     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11749                                Regs64bit ? X86::RCX : X86::ECX,
11750                                swapInH, swapInL.getValue(1));
11751     SDValue Ops[] = { swapInH.getValue(0),
11752                       N->getOperand(1),
11753                       swapInH.getValue(1) };
11754     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11755     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11756     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11757                                   X86ISD::LCMPXCHG8_DAG;
11758     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11759                                              Ops, 3, T, MMO);
11760     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11761                                         Regs64bit ? X86::RAX : X86::EAX,
11762                                         HalfT, Result.getValue(1));
11763     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11764                                         Regs64bit ? X86::RDX : X86::EDX,
11765                                         HalfT, cpOutL.getValue(2));
11766     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11767     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11768     Results.push_back(cpOutH.getValue(1));
11769     return;
11770   }
11771   case ISD::ATOMIC_LOAD_ADD:
11772   case ISD::ATOMIC_LOAD_AND:
11773   case ISD::ATOMIC_LOAD_NAND:
11774   case ISD::ATOMIC_LOAD_OR:
11775   case ISD::ATOMIC_LOAD_SUB:
11776   case ISD::ATOMIC_LOAD_XOR:
11777   case ISD::ATOMIC_LOAD_MAX:
11778   case ISD::ATOMIC_LOAD_MIN:
11779   case ISD::ATOMIC_LOAD_UMAX:
11780   case ISD::ATOMIC_LOAD_UMIN:
11781   case ISD::ATOMIC_SWAP: {
11782     unsigned Opc;
11783     switch (N->getOpcode()) {
11784     default: llvm_unreachable("Unexpected opcode");
11785     case ISD::ATOMIC_LOAD_ADD:
11786       Opc = X86ISD::ATOMADD64_DAG;
11787       break;
11788     case ISD::ATOMIC_LOAD_AND:
11789       Opc = X86ISD::ATOMAND64_DAG;
11790       break;
11791     case ISD::ATOMIC_LOAD_NAND:
11792       Opc = X86ISD::ATOMNAND64_DAG;
11793       break;
11794     case ISD::ATOMIC_LOAD_OR:
11795       Opc = X86ISD::ATOMOR64_DAG;
11796       break;
11797     case ISD::ATOMIC_LOAD_SUB:
11798       Opc = X86ISD::ATOMSUB64_DAG;
11799       break;
11800     case ISD::ATOMIC_LOAD_XOR:
11801       Opc = X86ISD::ATOMXOR64_DAG;
11802       break;
11803     case ISD::ATOMIC_LOAD_MAX:
11804       Opc = X86ISD::ATOMMAX64_DAG;
11805       break;
11806     case ISD::ATOMIC_LOAD_MIN:
11807       Opc = X86ISD::ATOMMIN64_DAG;
11808       break;
11809     case ISD::ATOMIC_LOAD_UMAX:
11810       Opc = X86ISD::ATOMUMAX64_DAG;
11811       break;
11812     case ISD::ATOMIC_LOAD_UMIN:
11813       Opc = X86ISD::ATOMUMIN64_DAG;
11814       break;
11815     case ISD::ATOMIC_SWAP:
11816       Opc = X86ISD::ATOMSWAP64_DAG;
11817       break;
11818     }
11819     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11820     return;
11821   }
11822   case ISD::ATOMIC_LOAD:
11823     ReplaceATOMIC_LOAD(N, Results, DAG);
11824   }
11825 }
11826
11827 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11828   switch (Opcode) {
11829   default: return NULL;
11830   case X86ISD::BSF:                return "X86ISD::BSF";
11831   case X86ISD::BSR:                return "X86ISD::BSR";
11832   case X86ISD::SHLD:               return "X86ISD::SHLD";
11833   case X86ISD::SHRD:               return "X86ISD::SHRD";
11834   case X86ISD::FAND:               return "X86ISD::FAND";
11835   case X86ISD::FOR:                return "X86ISD::FOR";
11836   case X86ISD::FXOR:               return "X86ISD::FXOR";
11837   case X86ISD::FSRL:               return "X86ISD::FSRL";
11838   case X86ISD::FILD:               return "X86ISD::FILD";
11839   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11840   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11841   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11842   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11843   case X86ISD::FLD:                return "X86ISD::FLD";
11844   case X86ISD::FST:                return "X86ISD::FST";
11845   case X86ISD::CALL:               return "X86ISD::CALL";
11846   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11847   case X86ISD::BT:                 return "X86ISD::BT";
11848   case X86ISD::CMP:                return "X86ISD::CMP";
11849   case X86ISD::COMI:               return "X86ISD::COMI";
11850   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11851   case X86ISD::SETCC:              return "X86ISD::SETCC";
11852   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11853   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11854   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11855   case X86ISD::CMOV:               return "X86ISD::CMOV";
11856   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11857   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11858   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11859   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11860   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11861   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11862   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11863   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11864   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11865   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11866   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11867   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11868   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11869   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11870   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11871   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11872   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11873   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11874   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11875   case X86ISD::HADD:               return "X86ISD::HADD";
11876   case X86ISD::HSUB:               return "X86ISD::HSUB";
11877   case X86ISD::FHADD:              return "X86ISD::FHADD";
11878   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11879   case X86ISD::FMAX:               return "X86ISD::FMAX";
11880   case X86ISD::FMIN:               return "X86ISD::FMIN";
11881   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11882   case X86ISD::FMINC:              return "X86ISD::FMINC";
11883   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11884   case X86ISD::FRCP:               return "X86ISD::FRCP";
11885   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11886   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11887   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11888   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
11889   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
11890   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11891   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11892   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11893   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11894   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11895   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11896   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11897   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11898   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11899   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11900   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11901   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11902   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11903   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11904   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11905   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
11906   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
11907   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11908   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
11909   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11910   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11911   case X86ISD::VSHL:               return "X86ISD::VSHL";
11912   case X86ISD::VSRL:               return "X86ISD::VSRL";
11913   case X86ISD::VSRA:               return "X86ISD::VSRA";
11914   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11915   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11916   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11917   case X86ISD::CMPP:               return "X86ISD::CMPP";
11918   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11919   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11920   case X86ISD::ADD:                return "X86ISD::ADD";
11921   case X86ISD::SUB:                return "X86ISD::SUB";
11922   case X86ISD::ADC:                return "X86ISD::ADC";
11923   case X86ISD::SBB:                return "X86ISD::SBB";
11924   case X86ISD::SMUL:               return "X86ISD::SMUL";
11925   case X86ISD::UMUL:               return "X86ISD::UMUL";
11926   case X86ISD::INC:                return "X86ISD::INC";
11927   case X86ISD::DEC:                return "X86ISD::DEC";
11928   case X86ISD::OR:                 return "X86ISD::OR";
11929   case X86ISD::XOR:                return "X86ISD::XOR";
11930   case X86ISD::AND:                return "X86ISD::AND";
11931   case X86ISD::ANDN:               return "X86ISD::ANDN";
11932   case X86ISD::BLSI:               return "X86ISD::BLSI";
11933   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11934   case X86ISD::BLSR:               return "X86ISD::BLSR";
11935   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11936   case X86ISD::PTEST:              return "X86ISD::PTEST";
11937   case X86ISD::TESTP:              return "X86ISD::TESTP";
11938   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11939   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11940   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11941   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11942   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11943   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11944   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11945   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11946   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11947   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11948   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11949   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11950   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11951   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11952   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11953   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11954   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11955   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11956   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11957   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11958   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11959   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11960   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11961   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11962   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11963   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11964   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11965   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11966   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11967   case X86ISD::SAHF:               return "X86ISD::SAHF";
11968   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11969   case X86ISD::FMADD:              return "X86ISD::FMADD";
11970   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11971   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11972   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11973   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11974   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11975   }
11976 }
11977
11978 // isLegalAddressingMode - Return true if the addressing mode represented
11979 // by AM is legal for this target, for a load/store of the specified type.
11980 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11981                                               Type *Ty) const {
11982   // X86 supports extremely general addressing modes.
11983   CodeModel::Model M = getTargetMachine().getCodeModel();
11984   Reloc::Model R = getTargetMachine().getRelocationModel();
11985
11986   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11987   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11988     return false;
11989
11990   if (AM.BaseGV) {
11991     unsigned GVFlags =
11992       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11993
11994     // If a reference to this global requires an extra load, we can't fold it.
11995     if (isGlobalStubReference(GVFlags))
11996       return false;
11997
11998     // If BaseGV requires a register for the PIC base, we cannot also have a
11999     // BaseReg specified.
12000     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12001       return false;
12002
12003     // If lower 4G is not available, then we must use rip-relative addressing.
12004     if ((M != CodeModel::Small || R != Reloc::Static) &&
12005         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12006       return false;
12007   }
12008
12009   switch (AM.Scale) {
12010   case 0:
12011   case 1:
12012   case 2:
12013   case 4:
12014   case 8:
12015     // These scales always work.
12016     break;
12017   case 3:
12018   case 5:
12019   case 9:
12020     // These scales are formed with basereg+scalereg.  Only accept if there is
12021     // no basereg yet.
12022     if (AM.HasBaseReg)
12023       return false;
12024     break;
12025   default:  // Other stuff never works.
12026     return false;
12027   }
12028
12029   return true;
12030 }
12031
12032
12033 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12034   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12035     return false;
12036   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12037   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12038   if (NumBits1 <= NumBits2)
12039     return false;
12040   return true;
12041 }
12042
12043 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12044   return Imm == (int32_t)Imm;
12045 }
12046
12047 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12048   // Can also use sub to handle negated immediates.
12049   return Imm == (int32_t)Imm;
12050 }
12051
12052 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12053   if (!VT1.isInteger() || !VT2.isInteger())
12054     return false;
12055   unsigned NumBits1 = VT1.getSizeInBits();
12056   unsigned NumBits2 = VT2.getSizeInBits();
12057   if (NumBits1 <= NumBits2)
12058     return false;
12059   return true;
12060 }
12061
12062 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12063   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12064   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12065 }
12066
12067 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12068   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12069   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12070 }
12071
12072 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12073   // i16 instructions are longer (0x66 prefix) and potentially slower.
12074   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12075 }
12076
12077 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12078 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12079 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12080 /// are assumed to be legal.
12081 bool
12082 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12083                                       EVT VT) const {
12084   // Very little shuffling can be done for 64-bit vectors right now.
12085   if (VT.getSizeInBits() == 64)
12086     return false;
12087
12088   // FIXME: pshufb, blends, shifts.
12089   return (VT.getVectorNumElements() == 2 ||
12090           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12091           isMOVLMask(M, VT) ||
12092           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12093           isPSHUFDMask(M, VT) ||
12094           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12095           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12096           isPALIGNRMask(M, VT, Subtarget) ||
12097           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12098           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12099           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12100           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12101 }
12102
12103 bool
12104 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12105                                           EVT VT) const {
12106   unsigned NumElts = VT.getVectorNumElements();
12107   // FIXME: This collection of masks seems suspect.
12108   if (NumElts == 2)
12109     return true;
12110   if (NumElts == 4 && VT.is128BitVector()) {
12111     return (isMOVLMask(Mask, VT)  ||
12112             isCommutedMOVLMask(Mask, VT, true) ||
12113             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12114             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12115   }
12116   return false;
12117 }
12118
12119 //===----------------------------------------------------------------------===//
12120 //                           X86 Scheduler Hooks
12121 //===----------------------------------------------------------------------===//
12122
12123 // private utility function
12124
12125 // Get CMPXCHG opcode for the specified data type.
12126 static unsigned getCmpXChgOpcode(EVT VT) {
12127   switch (VT.getSimpleVT().SimpleTy) {
12128   case MVT::i8:  return X86::LCMPXCHG8;
12129   case MVT::i16: return X86::LCMPXCHG16;
12130   case MVT::i32: return X86::LCMPXCHG32;
12131   case MVT::i64: return X86::LCMPXCHG64;
12132   default:
12133     break;
12134   }
12135   llvm_unreachable("Invalid operand size!");
12136 }
12137
12138 // Get LOAD opcode for the specified data type.
12139 static unsigned getLoadOpcode(EVT VT) {
12140   switch (VT.getSimpleVT().SimpleTy) {
12141   case MVT::i8:  return X86::MOV8rm;
12142   case MVT::i16: return X86::MOV16rm;
12143   case MVT::i32: return X86::MOV32rm;
12144   case MVT::i64: return X86::MOV64rm;
12145   default:
12146     break;
12147   }
12148   llvm_unreachable("Invalid operand size!");
12149 }
12150
12151 // Get opcode of the non-atomic one from the specified atomic instruction.
12152 static unsigned getNonAtomicOpcode(unsigned Opc) {
12153   switch (Opc) {
12154   case X86::ATOMAND8:  return X86::AND8rr;
12155   case X86::ATOMAND16: return X86::AND16rr;
12156   case X86::ATOMAND32: return X86::AND32rr;
12157   case X86::ATOMAND64: return X86::AND64rr;
12158   case X86::ATOMOR8:   return X86::OR8rr;
12159   case X86::ATOMOR16:  return X86::OR16rr;
12160   case X86::ATOMOR32:  return X86::OR32rr;
12161   case X86::ATOMOR64:  return X86::OR64rr;
12162   case X86::ATOMXOR8:  return X86::XOR8rr;
12163   case X86::ATOMXOR16: return X86::XOR16rr;
12164   case X86::ATOMXOR32: return X86::XOR32rr;
12165   case X86::ATOMXOR64: return X86::XOR64rr;
12166   }
12167   llvm_unreachable("Unhandled atomic-load-op opcode!");
12168 }
12169
12170 // Get opcode of the non-atomic one from the specified atomic instruction with
12171 // extra opcode.
12172 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12173                                                unsigned &ExtraOpc) {
12174   switch (Opc) {
12175   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12176   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12177   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12178   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12179   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12180   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12181   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12182   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12183   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12184   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12185   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12186   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12187   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12188   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12189   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12190   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12191   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12192   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12193   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12194   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12195   }
12196   llvm_unreachable("Unhandled atomic-load-op opcode!");
12197 }
12198
12199 // Get opcode of the non-atomic one from the specified atomic instruction for
12200 // 64-bit data type on 32-bit target.
12201 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12202   switch (Opc) {
12203   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12204   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12205   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12206   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12207   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12208   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12209   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12210   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12211   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12212   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12213   }
12214   llvm_unreachable("Unhandled atomic-load-op opcode!");
12215 }
12216
12217 // Get opcode of the non-atomic one from the specified atomic instruction for
12218 // 64-bit data type on 32-bit target with extra opcode.
12219 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12220                                                    unsigned &HiOpc,
12221                                                    unsigned &ExtraOpc) {
12222   switch (Opc) {
12223   case X86::ATOMNAND6432:
12224     ExtraOpc = X86::NOT32r;
12225     HiOpc = X86::AND32rr;
12226     return X86::AND32rr;
12227   }
12228   llvm_unreachable("Unhandled atomic-load-op opcode!");
12229 }
12230
12231 // Get pseudo CMOV opcode from the specified data type.
12232 static unsigned getPseudoCMOVOpc(EVT VT) {
12233   switch (VT.getSimpleVT().SimpleTy) {
12234   case MVT::i8:  return X86::CMOV_GR8;
12235   case MVT::i16: return X86::CMOV_GR16;
12236   case MVT::i32: return X86::CMOV_GR32;
12237   default:
12238     break;
12239   }
12240   llvm_unreachable("Unknown CMOV opcode!");
12241 }
12242
12243 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12244 // They will be translated into a spin-loop or compare-exchange loop from
12245 //
12246 //    ...
12247 //    dst = atomic-fetch-op MI.addr, MI.val
12248 //    ...
12249 //
12250 // to
12251 //
12252 //    ...
12253 //    EAX = LOAD MI.addr
12254 // loop:
12255 //    t1 = OP MI.val, EAX
12256 //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12257 //    JNE loop
12258 // sink:
12259 //    dst = EAX
12260 //    ...
12261 MachineBasicBlock *
12262 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12263                                        MachineBasicBlock *MBB) const {
12264   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12265   DebugLoc DL = MI->getDebugLoc();
12266
12267   MachineFunction *MF = MBB->getParent();
12268   MachineRegisterInfo &MRI = MF->getRegInfo();
12269
12270   const BasicBlock *BB = MBB->getBasicBlock();
12271   MachineFunction::iterator I = MBB;
12272   ++I;
12273
12274   assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12275          "Unexpected number of operands");
12276
12277   assert(MI->hasOneMemOperand() &&
12278          "Expected atomic-load-op to have one memoperand");
12279
12280   // Memory Reference
12281   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12282   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12283
12284   unsigned DstReg, SrcReg;
12285   unsigned MemOpndSlot;
12286
12287   unsigned CurOp = 0;
12288
12289   DstReg = MI->getOperand(CurOp++).getReg();
12290   MemOpndSlot = CurOp;
12291   CurOp += X86::AddrNumOperands;
12292   SrcReg = MI->getOperand(CurOp++).getReg();
12293
12294   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12295   MVT::SimpleValueType VT = *RC->vt_begin();
12296   unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12297
12298   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12299   unsigned LOADOpc = getLoadOpcode(VT);
12300
12301   // For the atomic load-arith operator, we generate
12302   //
12303   //  thisMBB:
12304   //    EAX = LOAD [MI.addr]
12305   //  mainMBB:
12306   //    t1 = OP MI.val, EAX
12307   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12308   //    JNE mainMBB
12309   //  sinkMBB:
12310
12311   MachineBasicBlock *thisMBB = MBB;
12312   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12313   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12314   MF->insert(I, mainMBB);
12315   MF->insert(I, sinkMBB);
12316
12317   MachineInstrBuilder MIB;
12318
12319   // Transfer the remainder of BB and its successor edges to sinkMBB.
12320   sinkMBB->splice(sinkMBB->begin(), MBB,
12321                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12322   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12323
12324   // thisMBB:
12325   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12326   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12327     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12328   MIB.setMemRefs(MMOBegin, MMOEnd);
12329
12330   thisMBB->addSuccessor(mainMBB);
12331
12332   // mainMBB:
12333   MachineBasicBlock *origMainMBB = mainMBB;
12334   mainMBB->addLiveIn(AccPhyReg);
12335
12336   // Copy AccPhyReg as it is used more than once.
12337   unsigned AccReg = MRI.createVirtualRegister(RC);
12338   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12339     .addReg(AccPhyReg);
12340
12341   unsigned t1 = MRI.createVirtualRegister(RC);
12342   unsigned Opc = MI->getOpcode();
12343   switch (Opc) {
12344   default:
12345     llvm_unreachable("Unhandled atomic-load-op opcode!");
12346   case X86::ATOMAND8:
12347   case X86::ATOMAND16:
12348   case X86::ATOMAND32:
12349   case X86::ATOMAND64:
12350   case X86::ATOMOR8:
12351   case X86::ATOMOR16:
12352   case X86::ATOMOR32:
12353   case X86::ATOMOR64:
12354   case X86::ATOMXOR8:
12355   case X86::ATOMXOR16:
12356   case X86::ATOMXOR32:
12357   case X86::ATOMXOR64: {
12358     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12359     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12360       .addReg(AccReg);
12361     break;
12362   }
12363   case X86::ATOMNAND8:
12364   case X86::ATOMNAND16:
12365   case X86::ATOMNAND32:
12366   case X86::ATOMNAND64: {
12367     unsigned t2 = MRI.createVirtualRegister(RC);
12368     unsigned NOTOpc;
12369     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12370     BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12371       .addReg(AccReg);
12372     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12373     break;
12374   }
12375   case X86::ATOMMAX8:
12376   case X86::ATOMMAX16:
12377   case X86::ATOMMAX32:
12378   case X86::ATOMMAX64:
12379   case X86::ATOMMIN8:
12380   case X86::ATOMMIN16:
12381   case X86::ATOMMIN32:
12382   case X86::ATOMMIN64:
12383   case X86::ATOMUMAX8:
12384   case X86::ATOMUMAX16:
12385   case X86::ATOMUMAX32:
12386   case X86::ATOMUMAX64:
12387   case X86::ATOMUMIN8:
12388   case X86::ATOMUMIN16:
12389   case X86::ATOMUMIN32:
12390   case X86::ATOMUMIN64: {
12391     unsigned CMPOpc;
12392     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12393
12394     BuildMI(mainMBB, DL, TII->get(CMPOpc))
12395       .addReg(SrcReg)
12396       .addReg(AccReg);
12397
12398     if (Subtarget->hasCMov()) {
12399       if (VT != MVT::i8) {
12400         // Native support
12401         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12402           .addReg(SrcReg)
12403           .addReg(AccReg);
12404       } else {
12405         // Promote i8 to i32 to use CMOV32
12406         const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12407         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12408         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12409         unsigned t2 = MRI.createVirtualRegister(RC32);
12410
12411         unsigned Undef = MRI.createVirtualRegister(RC32);
12412         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12413
12414         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12415           .addReg(Undef)
12416           .addReg(SrcReg)
12417           .addImm(X86::sub_8bit);
12418         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12419           .addReg(Undef)
12420           .addReg(AccReg)
12421           .addImm(X86::sub_8bit);
12422
12423         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12424           .addReg(SrcReg32)
12425           .addReg(AccReg32);
12426
12427         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12428           .addReg(t2, 0, X86::sub_8bit);
12429       }
12430     } else {
12431       // Use pseudo select and lower them.
12432       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12433              "Invalid atomic-load-op transformation!");
12434       unsigned SelOpc = getPseudoCMOVOpc(VT);
12435       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12436       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12437       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12438               .addReg(SrcReg).addReg(AccReg)
12439               .addImm(CC);
12440       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12441     }
12442     break;
12443   }
12444   }
12445
12446   // Copy AccPhyReg back from virtual register.
12447   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12448     .addReg(AccReg);
12449
12450   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12451   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12452     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12453   MIB.addReg(t1);
12454   MIB.setMemRefs(MMOBegin, MMOEnd);
12455
12456   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12457
12458   mainMBB->addSuccessor(origMainMBB);
12459   mainMBB->addSuccessor(sinkMBB);
12460
12461   // sinkMBB:
12462   sinkMBB->addLiveIn(AccPhyReg);
12463
12464   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12465           TII->get(TargetOpcode::COPY), DstReg)
12466     .addReg(AccPhyReg);
12467
12468   MI->eraseFromParent();
12469   return sinkMBB;
12470 }
12471
12472 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12473 // instructions. They will be translated into a spin-loop or compare-exchange
12474 // loop from
12475 //
12476 //    ...
12477 //    dst = atomic-fetch-op MI.addr, MI.val
12478 //    ...
12479 //
12480 // to
12481 //
12482 //    ...
12483 //    EAX = LOAD [MI.addr + 0]
12484 //    EDX = LOAD [MI.addr + 4]
12485 // loop:
12486 //    EBX = OP MI.val.lo, EAX
12487 //    ECX = OP MI.val.hi, EDX
12488 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12489 //    JNE loop
12490 // sink:
12491 //    dst = EDX:EAX
12492 //    ...
12493 MachineBasicBlock *
12494 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12495                                            MachineBasicBlock *MBB) const {
12496   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12497   DebugLoc DL = MI->getDebugLoc();
12498
12499   MachineFunction *MF = MBB->getParent();
12500   MachineRegisterInfo &MRI = MF->getRegInfo();
12501
12502   const BasicBlock *BB = MBB->getBasicBlock();
12503   MachineFunction::iterator I = MBB;
12504   ++I;
12505
12506   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12507          "Unexpected number of operands");
12508
12509   assert(MI->hasOneMemOperand() &&
12510          "Expected atomic-load-op32 to have one memoperand");
12511
12512   // Memory Reference
12513   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12514   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12515
12516   unsigned DstLoReg, DstHiReg;
12517   unsigned SrcLoReg, SrcHiReg;
12518   unsigned MemOpndSlot;
12519
12520   unsigned CurOp = 0;
12521
12522   DstLoReg = MI->getOperand(CurOp++).getReg();
12523   DstHiReg = MI->getOperand(CurOp++).getReg();
12524   MemOpndSlot = CurOp;
12525   CurOp += X86::AddrNumOperands;
12526   SrcLoReg = MI->getOperand(CurOp++).getReg();
12527   SrcHiReg = MI->getOperand(CurOp++).getReg();
12528
12529   const TargetRegisterClass *RC = &X86::GR32RegClass;
12530   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12531
12532   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12533   unsigned LOADOpc = X86::MOV32rm;
12534
12535   // For the atomic load-arith operator, we generate
12536   //
12537   //  thisMBB:
12538   //    EAX = LOAD [MI.addr + 0]
12539   //    EDX = LOAD [MI.addr + 4]
12540   //  mainMBB:
12541   //    EBX = OP MI.vallo, EAX
12542   //    ECX = OP MI.valhi, EDX
12543   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12544   //    JNE mainMBB
12545   //  sinkMBB:
12546
12547   MachineBasicBlock *thisMBB = MBB;
12548   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12549   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12550   MF->insert(I, mainMBB);
12551   MF->insert(I, sinkMBB);
12552
12553   MachineInstrBuilder MIB;
12554
12555   // Transfer the remainder of BB and its successor edges to sinkMBB.
12556   sinkMBB->splice(sinkMBB->begin(), MBB,
12557                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12558   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12559
12560   // thisMBB:
12561   // Lo
12562   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12563   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12564     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12565   MIB.setMemRefs(MMOBegin, MMOEnd);
12566   // Hi
12567   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12568   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12569     if (i == X86::AddrDisp)
12570       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12571     else
12572       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12573   }
12574   MIB.setMemRefs(MMOBegin, MMOEnd);
12575
12576   thisMBB->addSuccessor(mainMBB);
12577
12578   // mainMBB:
12579   MachineBasicBlock *origMainMBB = mainMBB;
12580   mainMBB->addLiveIn(X86::EAX);
12581   mainMBB->addLiveIn(X86::EDX);
12582
12583   // Copy EDX:EAX as they are used more than once.
12584   unsigned LoReg = MRI.createVirtualRegister(RC);
12585   unsigned HiReg = MRI.createVirtualRegister(RC);
12586   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12587   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12588
12589   unsigned t1L = MRI.createVirtualRegister(RC);
12590   unsigned t1H = MRI.createVirtualRegister(RC);
12591
12592   unsigned Opc = MI->getOpcode();
12593   switch (Opc) {
12594   default:
12595     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12596   case X86::ATOMAND6432:
12597   case X86::ATOMOR6432:
12598   case X86::ATOMXOR6432:
12599   case X86::ATOMADD6432:
12600   case X86::ATOMSUB6432: {
12601     unsigned HiOpc;
12602     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12603     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12604     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12605     break;
12606   }
12607   case X86::ATOMNAND6432: {
12608     unsigned HiOpc, NOTOpc;
12609     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12610     unsigned t2L = MRI.createVirtualRegister(RC);
12611     unsigned t2H = MRI.createVirtualRegister(RC);
12612     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12613     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12614     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12615     BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12616     break;
12617   }
12618   case X86::ATOMMAX6432:
12619   case X86::ATOMMIN6432:
12620   case X86::ATOMUMAX6432:
12621   case X86::ATOMUMIN6432: {
12622     unsigned HiOpc;
12623     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12624     unsigned cL = MRI.createVirtualRegister(RC8);
12625     unsigned cH = MRI.createVirtualRegister(RC8);
12626     unsigned cL32 = MRI.createVirtualRegister(RC);
12627     unsigned cH32 = MRI.createVirtualRegister(RC);
12628     unsigned cc = MRI.createVirtualRegister(RC);
12629     // cl := cmp src_lo, lo
12630     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12631       .addReg(SrcLoReg).addReg(LoReg);
12632     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12633     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12634     // ch := cmp src_hi, hi
12635     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12636       .addReg(SrcHiReg).addReg(HiReg);
12637     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12638     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12639     // cc := if (src_hi == hi) ? cl : ch;
12640     if (Subtarget->hasCMov()) {
12641       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12642         .addReg(cH32).addReg(cL32);
12643     } else {
12644       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12645               .addReg(cH32).addReg(cL32)
12646               .addImm(X86::COND_E);
12647       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12648     }
12649     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12650     if (Subtarget->hasCMov()) {
12651       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12652         .addReg(SrcLoReg).addReg(LoReg);
12653       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12654         .addReg(SrcHiReg).addReg(HiReg);
12655     } else {
12656       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12657               .addReg(SrcLoReg).addReg(LoReg)
12658               .addImm(X86::COND_NE);
12659       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12660       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12661               .addReg(SrcHiReg).addReg(HiReg)
12662               .addImm(X86::COND_NE);
12663       mainMBB = EmitLoweredSelect(MIB, mainMBB);
12664     }
12665     break;
12666   }
12667   case X86::ATOMSWAP6432: {
12668     unsigned HiOpc;
12669     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12670     BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12671     BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12672     break;
12673   }
12674   }
12675
12676   // Copy EDX:EAX back from HiReg:LoReg
12677   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12678   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12679   // Copy ECX:EBX from t1H:t1L
12680   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12681   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12682
12683   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12684   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12685     MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12686   MIB.setMemRefs(MMOBegin, MMOEnd);
12687
12688   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12689
12690   mainMBB->addSuccessor(origMainMBB);
12691   mainMBB->addSuccessor(sinkMBB);
12692
12693   // sinkMBB:
12694   sinkMBB->addLiveIn(X86::EAX);
12695   sinkMBB->addLiveIn(X86::EDX);
12696
12697   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12698           TII->get(TargetOpcode::COPY), DstLoReg)
12699     .addReg(X86::EAX);
12700   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12701           TII->get(TargetOpcode::COPY), DstHiReg)
12702     .addReg(X86::EDX);
12703
12704   MI->eraseFromParent();
12705   return sinkMBB;
12706 }
12707
12708 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12709 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12710 // in the .td file.
12711 MachineBasicBlock *
12712 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12713                             unsigned numArgs, bool memArg) const {
12714   assert(Subtarget->hasSSE42() &&
12715          "Target must have SSE4.2 or AVX features enabled");
12716
12717   DebugLoc dl = MI->getDebugLoc();
12718   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12719   unsigned Opc;
12720   if (!Subtarget->hasAVX()) {
12721     if (memArg)
12722       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12723     else
12724       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12725   } else {
12726     if (memArg)
12727       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12728     else
12729       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12730   }
12731
12732   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12733   for (unsigned i = 0; i < numArgs; ++i) {
12734     MachineOperand &Op = MI->getOperand(i+1);
12735     if (!(Op.isReg() && Op.isImplicit()))
12736       MIB.addOperand(Op);
12737   }
12738   BuildMI(*BB, MI, dl,
12739     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12740     .addReg(X86::XMM0);
12741
12742   MI->eraseFromParent();
12743   return BB;
12744 }
12745
12746 MachineBasicBlock *
12747 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12748   DebugLoc dl = MI->getDebugLoc();
12749   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12750
12751   // Address into RAX/EAX, other two args into ECX, EDX.
12752   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12753   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12754   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12755   for (int i = 0; i < X86::AddrNumOperands; ++i)
12756     MIB.addOperand(MI->getOperand(i));
12757
12758   unsigned ValOps = X86::AddrNumOperands;
12759   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12760     .addReg(MI->getOperand(ValOps).getReg());
12761   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12762     .addReg(MI->getOperand(ValOps+1).getReg());
12763
12764   // The instruction doesn't actually take any operands though.
12765   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12766
12767   MI->eraseFromParent(); // The pseudo is gone now.
12768   return BB;
12769 }
12770
12771 MachineBasicBlock *
12772 X86TargetLowering::EmitVAARG64WithCustomInserter(
12773                    MachineInstr *MI,
12774                    MachineBasicBlock *MBB) const {
12775   // Emit va_arg instruction on X86-64.
12776
12777   // Operands to this pseudo-instruction:
12778   // 0  ) Output        : destination address (reg)
12779   // 1-5) Input         : va_list address (addr, i64mem)
12780   // 6  ) ArgSize       : Size (in bytes) of vararg type
12781   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12782   // 8  ) Align         : Alignment of type
12783   // 9  ) EFLAGS (implicit-def)
12784
12785   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12786   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12787
12788   unsigned DestReg = MI->getOperand(0).getReg();
12789   MachineOperand &Base = MI->getOperand(1);
12790   MachineOperand &Scale = MI->getOperand(2);
12791   MachineOperand &Index = MI->getOperand(3);
12792   MachineOperand &Disp = MI->getOperand(4);
12793   MachineOperand &Segment = MI->getOperand(5);
12794   unsigned ArgSize = MI->getOperand(6).getImm();
12795   unsigned ArgMode = MI->getOperand(7).getImm();
12796   unsigned Align = MI->getOperand(8).getImm();
12797
12798   // Memory Reference
12799   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12800   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12801   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12802
12803   // Machine Information
12804   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12805   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12806   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12807   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12808   DebugLoc DL = MI->getDebugLoc();
12809
12810   // struct va_list {
12811   //   i32   gp_offset
12812   //   i32   fp_offset
12813   //   i64   overflow_area (address)
12814   //   i64   reg_save_area (address)
12815   // }
12816   // sizeof(va_list) = 24
12817   // alignment(va_list) = 8
12818
12819   unsigned TotalNumIntRegs = 6;
12820   unsigned TotalNumXMMRegs = 8;
12821   bool UseGPOffset = (ArgMode == 1);
12822   bool UseFPOffset = (ArgMode == 2);
12823   unsigned MaxOffset = TotalNumIntRegs * 8 +
12824                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12825
12826   /* Align ArgSize to a multiple of 8 */
12827   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12828   bool NeedsAlign = (Align > 8);
12829
12830   MachineBasicBlock *thisMBB = MBB;
12831   MachineBasicBlock *overflowMBB;
12832   MachineBasicBlock *offsetMBB;
12833   MachineBasicBlock *endMBB;
12834
12835   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12836   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12837   unsigned OffsetReg = 0;
12838
12839   if (!UseGPOffset && !UseFPOffset) {
12840     // If we only pull from the overflow region, we don't create a branch.
12841     // We don't need to alter control flow.
12842     OffsetDestReg = 0; // unused
12843     OverflowDestReg = DestReg;
12844
12845     offsetMBB = NULL;
12846     overflowMBB = thisMBB;
12847     endMBB = thisMBB;
12848   } else {
12849     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12850     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12851     // If not, pull from overflow_area. (branch to overflowMBB)
12852     //
12853     //       thisMBB
12854     //         |     .
12855     //         |        .
12856     //     offsetMBB   overflowMBB
12857     //         |        .
12858     //         |     .
12859     //        endMBB
12860
12861     // Registers for the PHI in endMBB
12862     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12863     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12864
12865     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12866     MachineFunction *MF = MBB->getParent();
12867     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12868     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12869     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12870
12871     MachineFunction::iterator MBBIter = MBB;
12872     ++MBBIter;
12873
12874     // Insert the new basic blocks
12875     MF->insert(MBBIter, offsetMBB);
12876     MF->insert(MBBIter, overflowMBB);
12877     MF->insert(MBBIter, endMBB);
12878
12879     // Transfer the remainder of MBB and its successor edges to endMBB.
12880     endMBB->splice(endMBB->begin(), thisMBB,
12881                     llvm::next(MachineBasicBlock::iterator(MI)),
12882                     thisMBB->end());
12883     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12884
12885     // Make offsetMBB and overflowMBB successors of thisMBB
12886     thisMBB->addSuccessor(offsetMBB);
12887     thisMBB->addSuccessor(overflowMBB);
12888
12889     // endMBB is a successor of both offsetMBB and overflowMBB
12890     offsetMBB->addSuccessor(endMBB);
12891     overflowMBB->addSuccessor(endMBB);
12892
12893     // Load the offset value into a register
12894     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12895     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12896       .addOperand(Base)
12897       .addOperand(Scale)
12898       .addOperand(Index)
12899       .addDisp(Disp, UseFPOffset ? 4 : 0)
12900       .addOperand(Segment)
12901       .setMemRefs(MMOBegin, MMOEnd);
12902
12903     // Check if there is enough room left to pull this argument.
12904     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12905       .addReg(OffsetReg)
12906       .addImm(MaxOffset + 8 - ArgSizeA8);
12907
12908     // Branch to "overflowMBB" if offset >= max
12909     // Fall through to "offsetMBB" otherwise
12910     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12911       .addMBB(overflowMBB);
12912   }
12913
12914   // In offsetMBB, emit code to use the reg_save_area.
12915   if (offsetMBB) {
12916     assert(OffsetReg != 0);
12917
12918     // Read the reg_save_area address.
12919     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12920     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12921       .addOperand(Base)
12922       .addOperand(Scale)
12923       .addOperand(Index)
12924       .addDisp(Disp, 16)
12925       .addOperand(Segment)
12926       .setMemRefs(MMOBegin, MMOEnd);
12927
12928     // Zero-extend the offset
12929     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12930       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12931         .addImm(0)
12932         .addReg(OffsetReg)
12933         .addImm(X86::sub_32bit);
12934
12935     // Add the offset to the reg_save_area to get the final address.
12936     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12937       .addReg(OffsetReg64)
12938       .addReg(RegSaveReg);
12939
12940     // Compute the offset for the next argument
12941     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12942     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12943       .addReg(OffsetReg)
12944       .addImm(UseFPOffset ? 16 : 8);
12945
12946     // Store it back into the va_list.
12947     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12948       .addOperand(Base)
12949       .addOperand(Scale)
12950       .addOperand(Index)
12951       .addDisp(Disp, UseFPOffset ? 4 : 0)
12952       .addOperand(Segment)
12953       .addReg(NextOffsetReg)
12954       .setMemRefs(MMOBegin, MMOEnd);
12955
12956     // Jump to endMBB
12957     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12958       .addMBB(endMBB);
12959   }
12960
12961   //
12962   // Emit code to use overflow area
12963   //
12964
12965   // Load the overflow_area address into a register.
12966   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12967   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12968     .addOperand(Base)
12969     .addOperand(Scale)
12970     .addOperand(Index)
12971     .addDisp(Disp, 8)
12972     .addOperand(Segment)
12973     .setMemRefs(MMOBegin, MMOEnd);
12974
12975   // If we need to align it, do so. Otherwise, just copy the address
12976   // to OverflowDestReg.
12977   if (NeedsAlign) {
12978     // Align the overflow address
12979     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12980     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12981
12982     // aligned_addr = (addr + (align-1)) & ~(align-1)
12983     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12984       .addReg(OverflowAddrReg)
12985       .addImm(Align-1);
12986
12987     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12988       .addReg(TmpReg)
12989       .addImm(~(uint64_t)(Align-1));
12990   } else {
12991     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12992       .addReg(OverflowAddrReg);
12993   }
12994
12995   // Compute the next overflow address after this argument.
12996   // (the overflow address should be kept 8-byte aligned)
12997   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12998   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12999     .addReg(OverflowDestReg)
13000     .addImm(ArgSizeA8);
13001
13002   // Store the new overflow address.
13003   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13004     .addOperand(Base)
13005     .addOperand(Scale)
13006     .addOperand(Index)
13007     .addDisp(Disp, 8)
13008     .addOperand(Segment)
13009     .addReg(NextAddrReg)
13010     .setMemRefs(MMOBegin, MMOEnd);
13011
13012   // If we branched, emit the PHI to the front of endMBB.
13013   if (offsetMBB) {
13014     BuildMI(*endMBB, endMBB->begin(), DL,
13015             TII->get(X86::PHI), DestReg)
13016       .addReg(OffsetDestReg).addMBB(offsetMBB)
13017       .addReg(OverflowDestReg).addMBB(overflowMBB);
13018   }
13019
13020   // Erase the pseudo instruction
13021   MI->eraseFromParent();
13022
13023   return endMBB;
13024 }
13025
13026 MachineBasicBlock *
13027 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13028                                                  MachineInstr *MI,
13029                                                  MachineBasicBlock *MBB) const {
13030   // Emit code to save XMM registers to the stack. The ABI says that the
13031   // number of registers to save is given in %al, so it's theoretically
13032   // possible to do an indirect jump trick to avoid saving all of them,
13033   // however this code takes a simpler approach and just executes all
13034   // of the stores if %al is non-zero. It's less code, and it's probably
13035   // easier on the hardware branch predictor, and stores aren't all that
13036   // expensive anyway.
13037
13038   // Create the new basic blocks. One block contains all the XMM stores,
13039   // and one block is the final destination regardless of whether any
13040   // stores were performed.
13041   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13042   MachineFunction *F = MBB->getParent();
13043   MachineFunction::iterator MBBIter = MBB;
13044   ++MBBIter;
13045   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13046   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13047   F->insert(MBBIter, XMMSaveMBB);
13048   F->insert(MBBIter, EndMBB);
13049
13050   // Transfer the remainder of MBB and its successor edges to EndMBB.
13051   EndMBB->splice(EndMBB->begin(), MBB,
13052                  llvm::next(MachineBasicBlock::iterator(MI)),
13053                  MBB->end());
13054   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13055
13056   // The original block will now fall through to the XMM save block.
13057   MBB->addSuccessor(XMMSaveMBB);
13058   // The XMMSaveMBB will fall through to the end block.
13059   XMMSaveMBB->addSuccessor(EndMBB);
13060
13061   // Now add the instructions.
13062   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13063   DebugLoc DL = MI->getDebugLoc();
13064
13065   unsigned CountReg = MI->getOperand(0).getReg();
13066   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13067   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13068
13069   if (!Subtarget->isTargetWin64()) {
13070     // If %al is 0, branch around the XMM save block.
13071     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13072     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13073     MBB->addSuccessor(EndMBB);
13074   }
13075
13076   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13077   // In the XMM save block, save all the XMM argument registers.
13078   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13079     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13080     MachineMemOperand *MMO =
13081       F->getMachineMemOperand(
13082           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13083         MachineMemOperand::MOStore,
13084         /*Size=*/16, /*Align=*/16);
13085     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13086       .addFrameIndex(RegSaveFrameIndex)
13087       .addImm(/*Scale=*/1)
13088       .addReg(/*IndexReg=*/0)
13089       .addImm(/*Disp=*/Offset)
13090       .addReg(/*Segment=*/0)
13091       .addReg(MI->getOperand(i).getReg())
13092       .addMemOperand(MMO);
13093   }
13094
13095   MI->eraseFromParent();   // The pseudo instruction is gone now.
13096
13097   return EndMBB;
13098 }
13099
13100 // The EFLAGS operand of SelectItr might be missing a kill marker
13101 // because there were multiple uses of EFLAGS, and ISel didn't know
13102 // which to mark. Figure out whether SelectItr should have had a
13103 // kill marker, and set it if it should. Returns the correct kill
13104 // marker value.
13105 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13106                                      MachineBasicBlock* BB,
13107                                      const TargetRegisterInfo* TRI) {
13108   // Scan forward through BB for a use/def of EFLAGS.
13109   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13110   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13111     const MachineInstr& mi = *miI;
13112     if (mi.readsRegister(X86::EFLAGS))
13113       return false;
13114     if (mi.definesRegister(X86::EFLAGS))
13115       break; // Should have kill-flag - update below.
13116   }
13117
13118   // If we hit the end of the block, check whether EFLAGS is live into a
13119   // successor.
13120   if (miI == BB->end()) {
13121     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13122                                           sEnd = BB->succ_end();
13123          sItr != sEnd; ++sItr) {
13124       MachineBasicBlock* succ = *sItr;
13125       if (succ->isLiveIn(X86::EFLAGS))
13126         return false;
13127     }
13128   }
13129
13130   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13131   // out. SelectMI should have a kill flag on EFLAGS.
13132   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13133   return true;
13134 }
13135
13136 MachineBasicBlock *
13137 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13138                                      MachineBasicBlock *BB) const {
13139   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13140   DebugLoc DL = MI->getDebugLoc();
13141
13142   // To "insert" a SELECT_CC instruction, we actually have to insert the
13143   // diamond control-flow pattern.  The incoming instruction knows the
13144   // destination vreg to set, the condition code register to branch on, the
13145   // true/false values to select between, and a branch opcode to use.
13146   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13147   MachineFunction::iterator It = BB;
13148   ++It;
13149
13150   //  thisMBB:
13151   //  ...
13152   //   TrueVal = ...
13153   //   cmpTY ccX, r1, r2
13154   //   bCC copy1MBB
13155   //   fallthrough --> copy0MBB
13156   MachineBasicBlock *thisMBB = BB;
13157   MachineFunction *F = BB->getParent();
13158   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13159   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13160   F->insert(It, copy0MBB);
13161   F->insert(It, sinkMBB);
13162
13163   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13164   // live into the sink and copy blocks.
13165   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13166   if (!MI->killsRegister(X86::EFLAGS) &&
13167       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13168     copy0MBB->addLiveIn(X86::EFLAGS);
13169     sinkMBB->addLiveIn(X86::EFLAGS);
13170   }
13171
13172   // Transfer the remainder of BB and its successor edges to sinkMBB.
13173   sinkMBB->splice(sinkMBB->begin(), BB,
13174                   llvm::next(MachineBasicBlock::iterator(MI)),
13175                   BB->end());
13176   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13177
13178   // Add the true and fallthrough blocks as its successors.
13179   BB->addSuccessor(copy0MBB);
13180   BB->addSuccessor(sinkMBB);
13181
13182   // Create the conditional branch instruction.
13183   unsigned Opc =
13184     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13185   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13186
13187   //  copy0MBB:
13188   //   %FalseValue = ...
13189   //   # fallthrough to sinkMBB
13190   copy0MBB->addSuccessor(sinkMBB);
13191
13192   //  sinkMBB:
13193   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13194   //  ...
13195   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13196           TII->get(X86::PHI), MI->getOperand(0).getReg())
13197     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13198     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13199
13200   MI->eraseFromParent();   // The pseudo instruction is gone now.
13201   return sinkMBB;
13202 }
13203
13204 MachineBasicBlock *
13205 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13206                                         bool Is64Bit) const {
13207   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13208   DebugLoc DL = MI->getDebugLoc();
13209   MachineFunction *MF = BB->getParent();
13210   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13211
13212   assert(getTargetMachine().Options.EnableSegmentedStacks);
13213
13214   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13215   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13216
13217   // BB:
13218   //  ... [Till the alloca]
13219   // If stacklet is not large enough, jump to mallocMBB
13220   //
13221   // bumpMBB:
13222   //  Allocate by subtracting from RSP
13223   //  Jump to continueMBB
13224   //
13225   // mallocMBB:
13226   //  Allocate by call to runtime
13227   //
13228   // continueMBB:
13229   //  ...
13230   //  [rest of original BB]
13231   //
13232
13233   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13234   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13235   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13236
13237   MachineRegisterInfo &MRI = MF->getRegInfo();
13238   const TargetRegisterClass *AddrRegClass =
13239     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13240
13241   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13242     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13243     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13244     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13245     sizeVReg = MI->getOperand(1).getReg(),
13246     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13247
13248   MachineFunction::iterator MBBIter = BB;
13249   ++MBBIter;
13250
13251   MF->insert(MBBIter, bumpMBB);
13252   MF->insert(MBBIter, mallocMBB);
13253   MF->insert(MBBIter, continueMBB);
13254
13255   continueMBB->splice(continueMBB->begin(), BB, llvm::next
13256                       (MachineBasicBlock::iterator(MI)), BB->end());
13257   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13258
13259   // Add code to the main basic block to check if the stack limit has been hit,
13260   // and if so, jump to mallocMBB otherwise to bumpMBB.
13261   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13262   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13263     .addReg(tmpSPVReg).addReg(sizeVReg);
13264   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13265     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13266     .addReg(SPLimitVReg);
13267   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13268
13269   // bumpMBB simply decreases the stack pointer, since we know the current
13270   // stacklet has enough space.
13271   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13272     .addReg(SPLimitVReg);
13273   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13274     .addReg(SPLimitVReg);
13275   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13276
13277   // Calls into a routine in libgcc to allocate more space from the heap.
13278   const uint32_t *RegMask =
13279     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13280   if (Is64Bit) {
13281     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13282       .addReg(sizeVReg);
13283     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13284       .addExternalSymbol("__morestack_allocate_stack_space")
13285       .addRegMask(RegMask)
13286       .addReg(X86::RDI, RegState::Implicit)
13287       .addReg(X86::RAX, RegState::ImplicitDefine);
13288   } else {
13289     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13290       .addImm(12);
13291     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13292     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13293       .addExternalSymbol("__morestack_allocate_stack_space")
13294       .addRegMask(RegMask)
13295       .addReg(X86::EAX, RegState::ImplicitDefine);
13296   }
13297
13298   if (!Is64Bit)
13299     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13300       .addImm(16);
13301
13302   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13303     .addReg(Is64Bit ? X86::RAX : X86::EAX);
13304   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13305
13306   // Set up the CFG correctly.
13307   BB->addSuccessor(bumpMBB);
13308   BB->addSuccessor(mallocMBB);
13309   mallocMBB->addSuccessor(continueMBB);
13310   bumpMBB->addSuccessor(continueMBB);
13311
13312   // Take care of the PHI nodes.
13313   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13314           MI->getOperand(0).getReg())
13315     .addReg(mallocPtrVReg).addMBB(mallocMBB)
13316     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13317
13318   // Delete the original pseudo instruction.
13319   MI->eraseFromParent();
13320
13321   // And we're done.
13322   return continueMBB;
13323 }
13324
13325 MachineBasicBlock *
13326 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13327                                           MachineBasicBlock *BB) const {
13328   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13329   DebugLoc DL = MI->getDebugLoc();
13330
13331   assert(!Subtarget->isTargetEnvMacho());
13332
13333   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
13334   // non-trivial part is impdef of ESP.
13335
13336   if (Subtarget->isTargetWin64()) {
13337     if (Subtarget->isTargetCygMing()) {
13338       // ___chkstk(Mingw64):
13339       // Clobbers R10, R11, RAX and EFLAGS.
13340       // Updates RSP.
13341       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13342         .addExternalSymbol("___chkstk")
13343         .addReg(X86::RAX, RegState::Implicit)
13344         .addReg(X86::RSP, RegState::Implicit)
13345         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13346         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13347         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13348     } else {
13349       // __chkstk(MSVCRT): does not update stack pointer.
13350       // Clobbers R10, R11 and EFLAGS.
13351       // FIXME: RAX(allocated size) might be reused and not killed.
13352       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13353         .addExternalSymbol("__chkstk")
13354         .addReg(X86::RAX, RegState::Implicit)
13355         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13356       // RAX has the offset to subtracted from RSP.
13357       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13358         .addReg(X86::RSP)
13359         .addReg(X86::RAX);
13360     }
13361   } else {
13362     const char *StackProbeSymbol =
13363       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13364
13365     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13366       .addExternalSymbol(StackProbeSymbol)
13367       .addReg(X86::EAX, RegState::Implicit)
13368       .addReg(X86::ESP, RegState::Implicit)
13369       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13370       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13371       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13372   }
13373
13374   MI->eraseFromParent();   // The pseudo instruction is gone now.
13375   return BB;
13376 }
13377
13378 MachineBasicBlock *
13379 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13380                                       MachineBasicBlock *BB) const {
13381   // This is pretty easy.  We're taking the value that we received from
13382   // our load from the relocation, sticking it in either RDI (x86-64)
13383   // or EAX and doing an indirect call.  The return value will then
13384   // be in the normal return register.
13385   const X86InstrInfo *TII
13386     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13387   DebugLoc DL = MI->getDebugLoc();
13388   MachineFunction *F = BB->getParent();
13389
13390   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13391   assert(MI->getOperand(3).isGlobal() && "This should be a global");
13392
13393   // Get a register mask for the lowered call.
13394   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13395   // proper register mask.
13396   const uint32_t *RegMask =
13397     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13398   if (Subtarget->is64Bit()) {
13399     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13400                                       TII->get(X86::MOV64rm), X86::RDI)
13401     .addReg(X86::RIP)
13402     .addImm(0).addReg(0)
13403     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13404                       MI->getOperand(3).getTargetFlags())
13405     .addReg(0);
13406     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13407     addDirectMem(MIB, X86::RDI);
13408     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13409   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13410     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13411                                       TII->get(X86::MOV32rm), X86::EAX)
13412     .addReg(0)
13413     .addImm(0).addReg(0)
13414     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13415                       MI->getOperand(3).getTargetFlags())
13416     .addReg(0);
13417     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13418     addDirectMem(MIB, X86::EAX);
13419     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13420   } else {
13421     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13422                                       TII->get(X86::MOV32rm), X86::EAX)
13423     .addReg(TII->getGlobalBaseReg(F))
13424     .addImm(0).addReg(0)
13425     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13426                       MI->getOperand(3).getTargetFlags())
13427     .addReg(0);
13428     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13429     addDirectMem(MIB, X86::EAX);
13430     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13431   }
13432
13433   MI->eraseFromParent(); // The pseudo instruction is gone now.
13434   return BB;
13435 }
13436
13437 MachineBasicBlock *
13438 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13439                                     MachineBasicBlock *MBB) const {
13440   DebugLoc DL = MI->getDebugLoc();
13441   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13442
13443   MachineFunction *MF = MBB->getParent();
13444   MachineRegisterInfo &MRI = MF->getRegInfo();
13445
13446   const BasicBlock *BB = MBB->getBasicBlock();
13447   MachineFunction::iterator I = MBB;
13448   ++I;
13449
13450   // Memory Reference
13451   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13452   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13453
13454   unsigned DstReg;
13455   unsigned MemOpndSlot = 0;
13456
13457   unsigned CurOp = 0;
13458
13459   DstReg = MI->getOperand(CurOp++).getReg();
13460   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13461   assert(RC->hasType(MVT::i32) && "Invalid destination!");
13462   unsigned mainDstReg = MRI.createVirtualRegister(RC);
13463   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13464
13465   MemOpndSlot = CurOp;
13466
13467   MVT PVT = getPointerTy();
13468   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13469          "Invalid Pointer Size!");
13470
13471   // For v = setjmp(buf), we generate
13472   //
13473   // thisMBB:
13474   //  buf[LabelOffset] = restoreMBB
13475   //  SjLjSetup restoreMBB
13476   //
13477   // mainMBB:
13478   //  v_main = 0
13479   //
13480   // sinkMBB:
13481   //  v = phi(main, restore)
13482   //
13483   // restoreMBB:
13484   //  v_restore = 1
13485
13486   MachineBasicBlock *thisMBB = MBB;
13487   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13488   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13489   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13490   MF->insert(I, mainMBB);
13491   MF->insert(I, sinkMBB);
13492   MF->push_back(restoreMBB);
13493
13494   MachineInstrBuilder MIB;
13495
13496   // Transfer the remainder of BB and its successor edges to sinkMBB.
13497   sinkMBB->splice(sinkMBB->begin(), MBB,
13498                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13499   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13500
13501   // thisMBB:
13502   unsigned PtrStoreOpc = 0;
13503   unsigned LabelReg = 0;
13504   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13505   Reloc::Model RM = getTargetMachine().getRelocationModel();
13506   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13507                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13508
13509   // Prepare IP either in reg or imm.
13510   if (!UseImmLabel) {
13511     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13512     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13513     LabelReg = MRI.createVirtualRegister(PtrRC);
13514     if (Subtarget->is64Bit()) {
13515       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13516               .addReg(X86::RIP)
13517               .addImm(0)
13518               .addReg(0)
13519               .addMBB(restoreMBB)
13520               .addReg(0);
13521     } else {
13522       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13523       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13524               .addReg(XII->getGlobalBaseReg(MF))
13525               .addImm(0)
13526               .addReg(0)
13527               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13528               .addReg(0);
13529     }
13530   } else
13531     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13532   // Store IP
13533   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13534   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13535     if (i == X86::AddrDisp)
13536       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13537     else
13538       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13539   }
13540   if (!UseImmLabel)
13541     MIB.addReg(LabelReg);
13542   else
13543     MIB.addMBB(restoreMBB);
13544   MIB.setMemRefs(MMOBegin, MMOEnd);
13545   // Setup
13546   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13547           .addMBB(restoreMBB);
13548   MIB.addRegMask(RegInfo->getNoPreservedMask());
13549   thisMBB->addSuccessor(mainMBB);
13550   thisMBB->addSuccessor(restoreMBB);
13551
13552   // mainMBB:
13553   //  EAX = 0
13554   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13555   mainMBB->addSuccessor(sinkMBB);
13556
13557   // sinkMBB:
13558   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13559           TII->get(X86::PHI), DstReg)
13560     .addReg(mainDstReg).addMBB(mainMBB)
13561     .addReg(restoreDstReg).addMBB(restoreMBB);
13562
13563   // restoreMBB:
13564   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13565   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13566   restoreMBB->addSuccessor(sinkMBB);
13567
13568   MI->eraseFromParent();
13569   return sinkMBB;
13570 }
13571
13572 MachineBasicBlock *
13573 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13574                                      MachineBasicBlock *MBB) const {
13575   DebugLoc DL = MI->getDebugLoc();
13576   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13577
13578   MachineFunction *MF = MBB->getParent();
13579   MachineRegisterInfo &MRI = MF->getRegInfo();
13580
13581   // Memory Reference
13582   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13583   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13584
13585   MVT PVT = getPointerTy();
13586   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13587          "Invalid Pointer Size!");
13588
13589   const TargetRegisterClass *RC =
13590     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13591   unsigned Tmp = MRI.createVirtualRegister(RC);
13592   // Since FP is only updated here but NOT referenced, it's treated as GPR.
13593   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13594   unsigned SP = RegInfo->getStackRegister();
13595
13596   MachineInstrBuilder MIB;
13597
13598   const int64_t LabelOffset = 1 * PVT.getStoreSize();
13599   const int64_t SPOffset = 2 * PVT.getStoreSize();
13600
13601   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13602   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13603
13604   // Reload FP
13605   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13606   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13607     MIB.addOperand(MI->getOperand(i));
13608   MIB.setMemRefs(MMOBegin, MMOEnd);
13609   // Reload IP
13610   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13611   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13612     if (i == X86::AddrDisp)
13613       MIB.addDisp(MI->getOperand(i), LabelOffset);
13614     else
13615       MIB.addOperand(MI->getOperand(i));
13616   }
13617   MIB.setMemRefs(MMOBegin, MMOEnd);
13618   // Reload SP
13619   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13620   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13621     if (i == X86::AddrDisp)
13622       MIB.addDisp(MI->getOperand(i), SPOffset);
13623     else
13624       MIB.addOperand(MI->getOperand(i));
13625   }
13626   MIB.setMemRefs(MMOBegin, MMOEnd);
13627   // Jump
13628   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13629
13630   MI->eraseFromParent();
13631   return MBB;
13632 }
13633
13634 MachineBasicBlock *
13635 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13636                                                MachineBasicBlock *BB) const {
13637   switch (MI->getOpcode()) {
13638   default: llvm_unreachable("Unexpected instr type to insert");
13639   case X86::TAILJMPd64:
13640   case X86::TAILJMPr64:
13641   case X86::TAILJMPm64:
13642     llvm_unreachable("TAILJMP64 would not be touched here.");
13643   case X86::TCRETURNdi64:
13644   case X86::TCRETURNri64:
13645   case X86::TCRETURNmi64:
13646     return BB;
13647   case X86::WIN_ALLOCA:
13648     return EmitLoweredWinAlloca(MI, BB);
13649   case X86::SEG_ALLOCA_32:
13650     return EmitLoweredSegAlloca(MI, BB, false);
13651   case X86::SEG_ALLOCA_64:
13652     return EmitLoweredSegAlloca(MI, BB, true);
13653   case X86::TLSCall_32:
13654   case X86::TLSCall_64:
13655     return EmitLoweredTLSCall(MI, BB);
13656   case X86::CMOV_GR8:
13657   case X86::CMOV_FR32:
13658   case X86::CMOV_FR64:
13659   case X86::CMOV_V4F32:
13660   case X86::CMOV_V2F64:
13661   case X86::CMOV_V2I64:
13662   case X86::CMOV_V8F32:
13663   case X86::CMOV_V4F64:
13664   case X86::CMOV_V4I64:
13665   case X86::CMOV_GR16:
13666   case X86::CMOV_GR32:
13667   case X86::CMOV_RFP32:
13668   case X86::CMOV_RFP64:
13669   case X86::CMOV_RFP80:
13670     return EmitLoweredSelect(MI, BB);
13671
13672   case X86::FP32_TO_INT16_IN_MEM:
13673   case X86::FP32_TO_INT32_IN_MEM:
13674   case X86::FP32_TO_INT64_IN_MEM:
13675   case X86::FP64_TO_INT16_IN_MEM:
13676   case X86::FP64_TO_INT32_IN_MEM:
13677   case X86::FP64_TO_INT64_IN_MEM:
13678   case X86::FP80_TO_INT16_IN_MEM:
13679   case X86::FP80_TO_INT32_IN_MEM:
13680   case X86::FP80_TO_INT64_IN_MEM: {
13681     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13682     DebugLoc DL = MI->getDebugLoc();
13683
13684     // Change the floating point control register to use "round towards zero"
13685     // mode when truncating to an integer value.
13686     MachineFunction *F = BB->getParent();
13687     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13688     addFrameReference(BuildMI(*BB, MI, DL,
13689                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
13690
13691     // Load the old value of the high byte of the control word...
13692     unsigned OldCW =
13693       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13694     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13695                       CWFrameIdx);
13696
13697     // Set the high part to be round to zero...
13698     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13699       .addImm(0xC7F);
13700
13701     // Reload the modified control word now...
13702     addFrameReference(BuildMI(*BB, MI, DL,
13703                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13704
13705     // Restore the memory image of control word to original value
13706     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13707       .addReg(OldCW);
13708
13709     // Get the X86 opcode to use.
13710     unsigned Opc;
13711     switch (MI->getOpcode()) {
13712     default: llvm_unreachable("illegal opcode!");
13713     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13714     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13715     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13716     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13717     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13718     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13719     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13720     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13721     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13722     }
13723
13724     X86AddressMode AM;
13725     MachineOperand &Op = MI->getOperand(0);
13726     if (Op.isReg()) {
13727       AM.BaseType = X86AddressMode::RegBase;
13728       AM.Base.Reg = Op.getReg();
13729     } else {
13730       AM.BaseType = X86AddressMode::FrameIndexBase;
13731       AM.Base.FrameIndex = Op.getIndex();
13732     }
13733     Op = MI->getOperand(1);
13734     if (Op.isImm())
13735       AM.Scale = Op.getImm();
13736     Op = MI->getOperand(2);
13737     if (Op.isImm())
13738       AM.IndexReg = Op.getImm();
13739     Op = MI->getOperand(3);
13740     if (Op.isGlobal()) {
13741       AM.GV = Op.getGlobal();
13742     } else {
13743       AM.Disp = Op.getImm();
13744     }
13745     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13746                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13747
13748     // Reload the original control word now.
13749     addFrameReference(BuildMI(*BB, MI, DL,
13750                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13751
13752     MI->eraseFromParent();   // The pseudo instruction is gone now.
13753     return BB;
13754   }
13755     // String/text processing lowering.
13756   case X86::PCMPISTRM128REG:
13757   case X86::VPCMPISTRM128REG:
13758   case X86::PCMPISTRM128MEM:
13759   case X86::VPCMPISTRM128MEM:
13760   case X86::PCMPESTRM128REG:
13761   case X86::VPCMPESTRM128REG:
13762   case X86::PCMPESTRM128MEM:
13763   case X86::VPCMPESTRM128MEM: {
13764     unsigned NumArgs;
13765     bool MemArg;
13766     switch (MI->getOpcode()) {
13767     default: llvm_unreachable("illegal opcode!");
13768     case X86::PCMPISTRM128REG:
13769     case X86::VPCMPISTRM128REG:
13770       NumArgs = 3; MemArg = false; break;
13771     case X86::PCMPISTRM128MEM:
13772     case X86::VPCMPISTRM128MEM:
13773       NumArgs = 3; MemArg = true; break;
13774     case X86::PCMPESTRM128REG:
13775     case X86::VPCMPESTRM128REG:
13776       NumArgs = 5; MemArg = false; break;
13777     case X86::PCMPESTRM128MEM:
13778     case X86::VPCMPESTRM128MEM:
13779       NumArgs = 5; MemArg = true; break;
13780     }
13781     return EmitPCMP(MI, BB, NumArgs, MemArg);
13782   }
13783
13784     // Thread synchronization.
13785   case X86::MONITOR:
13786     return EmitMonitor(MI, BB);
13787
13788     // Atomic Lowering.
13789   case X86::ATOMAND8:
13790   case X86::ATOMAND16:
13791   case X86::ATOMAND32:
13792   case X86::ATOMAND64:
13793     // Fall through
13794   case X86::ATOMOR8:
13795   case X86::ATOMOR16:
13796   case X86::ATOMOR32:
13797   case X86::ATOMOR64:
13798     // Fall through
13799   case X86::ATOMXOR16:
13800   case X86::ATOMXOR8:
13801   case X86::ATOMXOR32:
13802   case X86::ATOMXOR64:
13803     // Fall through
13804   case X86::ATOMNAND8:
13805   case X86::ATOMNAND16:
13806   case X86::ATOMNAND32:
13807   case X86::ATOMNAND64:
13808     // Fall through
13809   case X86::ATOMMAX8:
13810   case X86::ATOMMAX16:
13811   case X86::ATOMMAX32:
13812   case X86::ATOMMAX64:
13813     // Fall through
13814   case X86::ATOMMIN8:
13815   case X86::ATOMMIN16:
13816   case X86::ATOMMIN32:
13817   case X86::ATOMMIN64:
13818     // Fall through
13819   case X86::ATOMUMAX8:
13820   case X86::ATOMUMAX16:
13821   case X86::ATOMUMAX32:
13822   case X86::ATOMUMAX64:
13823     // Fall through
13824   case X86::ATOMUMIN8:
13825   case X86::ATOMUMIN16:
13826   case X86::ATOMUMIN32:
13827   case X86::ATOMUMIN64:
13828     return EmitAtomicLoadArith(MI, BB);
13829
13830   // This group does 64-bit operations on a 32-bit host.
13831   case X86::ATOMAND6432:
13832   case X86::ATOMOR6432:
13833   case X86::ATOMXOR6432:
13834   case X86::ATOMNAND6432:
13835   case X86::ATOMADD6432:
13836   case X86::ATOMSUB6432:
13837   case X86::ATOMMAX6432:
13838   case X86::ATOMMIN6432:
13839   case X86::ATOMUMAX6432:
13840   case X86::ATOMUMIN6432:
13841   case X86::ATOMSWAP6432:
13842     return EmitAtomicLoadArith6432(MI, BB);
13843
13844   case X86::VASTART_SAVE_XMM_REGS:
13845     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13846
13847   case X86::VAARG_64:
13848     return EmitVAARG64WithCustomInserter(MI, BB);
13849
13850   case X86::EH_SjLj_SetJmp32:
13851   case X86::EH_SjLj_SetJmp64:
13852     return emitEHSjLjSetJmp(MI, BB);
13853
13854   case X86::EH_SjLj_LongJmp32:
13855   case X86::EH_SjLj_LongJmp64:
13856     return emitEHSjLjLongJmp(MI, BB);
13857   }
13858 }
13859
13860 //===----------------------------------------------------------------------===//
13861 //                           X86 Optimization Hooks
13862 //===----------------------------------------------------------------------===//
13863
13864 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13865                                                        APInt &KnownZero,
13866                                                        APInt &KnownOne,
13867                                                        const SelectionDAG &DAG,
13868                                                        unsigned Depth) const {
13869   unsigned BitWidth = KnownZero.getBitWidth();
13870   unsigned Opc = Op.getOpcode();
13871   assert((Opc >= ISD::BUILTIN_OP_END ||
13872           Opc == ISD::INTRINSIC_WO_CHAIN ||
13873           Opc == ISD::INTRINSIC_W_CHAIN ||
13874           Opc == ISD::INTRINSIC_VOID) &&
13875          "Should use MaskedValueIsZero if you don't know whether Op"
13876          " is a target node!");
13877
13878   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13879   switch (Opc) {
13880   default: break;
13881   case X86ISD::ADD:
13882   case X86ISD::SUB:
13883   case X86ISD::ADC:
13884   case X86ISD::SBB:
13885   case X86ISD::SMUL:
13886   case X86ISD::UMUL:
13887   case X86ISD::INC:
13888   case X86ISD::DEC:
13889   case X86ISD::OR:
13890   case X86ISD::XOR:
13891   case X86ISD::AND:
13892     // These nodes' second result is a boolean.
13893     if (Op.getResNo() == 0)
13894       break;
13895     // Fallthrough
13896   case X86ISD::SETCC:
13897     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13898     break;
13899   case ISD::INTRINSIC_WO_CHAIN: {
13900     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13901     unsigned NumLoBits = 0;
13902     switch (IntId) {
13903     default: break;
13904     case Intrinsic::x86_sse_movmsk_ps:
13905     case Intrinsic::x86_avx_movmsk_ps_256:
13906     case Intrinsic::x86_sse2_movmsk_pd:
13907     case Intrinsic::x86_avx_movmsk_pd_256:
13908     case Intrinsic::x86_mmx_pmovmskb:
13909     case Intrinsic::x86_sse2_pmovmskb_128:
13910     case Intrinsic::x86_avx2_pmovmskb: {
13911       // High bits of movmskp{s|d}, pmovmskb are known zero.
13912       switch (IntId) {
13913         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13914         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13915         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13916         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13917         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13918         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13919         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13920         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13921       }
13922       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13923       break;
13924     }
13925     }
13926     break;
13927   }
13928   }
13929 }
13930
13931 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13932                                                          unsigned Depth) const {
13933   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13934   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13935     return Op.getValueType().getScalarType().getSizeInBits();
13936
13937   // Fallback case.
13938   return 1;
13939 }
13940
13941 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13942 /// node is a GlobalAddress + offset.
13943 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13944                                        const GlobalValue* &GA,
13945                                        int64_t &Offset) const {
13946   if (N->getOpcode() == X86ISD::Wrapper) {
13947     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13948       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13949       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13950       return true;
13951     }
13952   }
13953   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13954 }
13955
13956 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13957 /// same as extracting the high 128-bit part of 256-bit vector and then
13958 /// inserting the result into the low part of a new 256-bit vector
13959 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13960   EVT VT = SVOp->getValueType(0);
13961   unsigned NumElems = VT.getVectorNumElements();
13962
13963   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13964   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13965     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13966         SVOp->getMaskElt(j) >= 0)
13967       return false;
13968
13969   return true;
13970 }
13971
13972 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13973 /// same as extracting the low 128-bit part of 256-bit vector and then
13974 /// inserting the result into the high part of a new 256-bit vector
13975 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13976   EVT VT = SVOp->getValueType(0);
13977   unsigned NumElems = VT.getVectorNumElements();
13978
13979   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13980   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13981     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13982         SVOp->getMaskElt(j) >= 0)
13983       return false;
13984
13985   return true;
13986 }
13987
13988 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13989 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13990                                         TargetLowering::DAGCombinerInfo &DCI,
13991                                         const X86Subtarget* Subtarget) {
13992   DebugLoc dl = N->getDebugLoc();
13993   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13994   SDValue V1 = SVOp->getOperand(0);
13995   SDValue V2 = SVOp->getOperand(1);
13996   EVT VT = SVOp->getValueType(0);
13997   unsigned NumElems = VT.getVectorNumElements();
13998
13999   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14000       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14001     //
14002     //                   0,0,0,...
14003     //                      |
14004     //    V      UNDEF    BUILD_VECTOR    UNDEF
14005     //     \      /           \           /
14006     //  CONCAT_VECTOR         CONCAT_VECTOR
14007     //         \                  /
14008     //          \                /
14009     //          RESULT: V + zero extended
14010     //
14011     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14012         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14013         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14014       return SDValue();
14015
14016     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14017       return SDValue();
14018
14019     // To match the shuffle mask, the first half of the mask should
14020     // be exactly the first vector, and all the rest a splat with the
14021     // first element of the second one.
14022     for (unsigned i = 0; i != NumElems/2; ++i)
14023       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14024           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14025         return SDValue();
14026
14027     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14028     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14029       if (Ld->hasNUsesOfValue(1, 0)) {
14030         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14031         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14032         SDValue ResNode =
14033           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14034                                   Ld->getMemoryVT(),
14035                                   Ld->getPointerInfo(),
14036                                   Ld->getAlignment(),
14037                                   false/*isVolatile*/, true/*ReadMem*/,
14038                                   false/*WriteMem*/);
14039         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14040       }
14041     }
14042
14043     // Emit a zeroed vector and insert the desired subvector on its
14044     // first half.
14045     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14046     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14047     return DCI.CombineTo(N, InsV);
14048   }
14049
14050   //===--------------------------------------------------------------------===//
14051   // Combine some shuffles into subvector extracts and inserts:
14052   //
14053
14054   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14055   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14056     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14057     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14058     return DCI.CombineTo(N, InsV);
14059   }
14060
14061   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14062   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14063     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14064     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14065     return DCI.CombineTo(N, InsV);
14066   }
14067
14068   return SDValue();
14069 }
14070
14071 /// PerformShuffleCombine - Performs several different shuffle combines.
14072 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14073                                      TargetLowering::DAGCombinerInfo &DCI,
14074                                      const X86Subtarget *Subtarget) {
14075   DebugLoc dl = N->getDebugLoc();
14076   EVT VT = N->getValueType(0);
14077
14078   // Don't create instructions with illegal types after legalize types has run.
14079   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14080   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14081     return SDValue();
14082
14083   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14084   if (Subtarget->hasAVX() && VT.is256BitVector() &&
14085       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14086     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14087
14088   // Only handle 128 wide vector from here on.
14089   if (!VT.is128BitVector())
14090     return SDValue();
14091
14092   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14093   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14094   // consecutive, non-overlapping, and in the right order.
14095   SmallVector<SDValue, 16> Elts;
14096   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14097     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14098
14099   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14100 }
14101
14102
14103 /// PerformTruncateCombine - Converts truncate operation to
14104 /// a sequence of vector shuffle operations.
14105 /// It is possible when we truncate 256-bit vector to 128-bit vector
14106 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14107                                       TargetLowering::DAGCombinerInfo &DCI,
14108                                       const X86Subtarget *Subtarget)  {
14109   if (!DCI.isBeforeLegalizeOps())
14110     return SDValue();
14111
14112   if (!Subtarget->hasAVX())
14113     return SDValue();
14114
14115   EVT VT = N->getValueType(0);
14116   SDValue Op = N->getOperand(0);
14117   EVT OpVT = Op.getValueType();
14118   DebugLoc dl = N->getDebugLoc();
14119
14120   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14121
14122     if (Subtarget->hasAVX2()) {
14123       // AVX2: v4i64 -> v4i32
14124
14125       // VPERMD
14126       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14127
14128       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14129       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14130                                 ShufMask);
14131
14132       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14133                          DAG.getIntPtrConstant(0));
14134     }
14135
14136     // AVX: v4i64 -> v4i32
14137     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14138                                DAG.getIntPtrConstant(0));
14139
14140     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14141                                DAG.getIntPtrConstant(2));
14142
14143     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14144     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14145
14146     // PSHUFD
14147     static const int ShufMask1[] = {0, 2, 0, 0};
14148
14149     SDValue Undef = DAG.getUNDEF(VT);
14150     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14151     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14152
14153     // MOVLHPS
14154     static const int ShufMask2[] = {0, 1, 4, 5};
14155
14156     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14157   }
14158
14159   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14160
14161     if (Subtarget->hasAVX2()) {
14162       // AVX2: v8i32 -> v8i16
14163
14164       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14165
14166       // PSHUFB
14167       SmallVector<SDValue,32> pshufbMask;
14168       for (unsigned i = 0; i < 2; ++i) {
14169         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14170         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14171         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14172         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14173         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14174         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14175         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14176         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14177         for (unsigned j = 0; j < 8; ++j)
14178           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14179       }
14180       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14181                                &pshufbMask[0], 32);
14182       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14183
14184       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14185
14186       static const int ShufMask[] = {0,  2,  -1,  -1};
14187       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
14188                                 &ShufMask[0]);
14189
14190       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14191                        DAG.getIntPtrConstant(0));
14192
14193       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14194     }
14195
14196     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14197                                DAG.getIntPtrConstant(0));
14198
14199     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14200                                DAG.getIntPtrConstant(4));
14201
14202     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14203     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14204
14205     // PSHUFB
14206     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
14207                                    -1, -1, -1, -1, -1, -1, -1, -1};
14208
14209     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14210     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14211     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14212
14213     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14214     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14215
14216     // MOVLHPS
14217     static const int ShufMask2[] = {0, 1, 4, 5};
14218
14219     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14220     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14221   }
14222
14223   return SDValue();
14224 }
14225
14226 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14227 /// specific shuffle of a load can be folded into a single element load.
14228 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14229 /// shuffles have been customed lowered so we need to handle those here.
14230 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14231                                          TargetLowering::DAGCombinerInfo &DCI) {
14232   if (DCI.isBeforeLegalizeOps())
14233     return SDValue();
14234
14235   SDValue InVec = N->getOperand(0);
14236   SDValue EltNo = N->getOperand(1);
14237
14238   if (!isa<ConstantSDNode>(EltNo))
14239     return SDValue();
14240
14241   EVT VT = InVec.getValueType();
14242
14243   bool HasShuffleIntoBitcast = false;
14244   if (InVec.getOpcode() == ISD::BITCAST) {
14245     // Don't duplicate a load with other uses.
14246     if (!InVec.hasOneUse())
14247       return SDValue();
14248     EVT BCVT = InVec.getOperand(0).getValueType();
14249     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14250       return SDValue();
14251     InVec = InVec.getOperand(0);
14252     HasShuffleIntoBitcast = true;
14253   }
14254
14255   if (!isTargetShuffle(InVec.getOpcode()))
14256     return SDValue();
14257
14258   // Don't duplicate a load with other uses.
14259   if (!InVec.hasOneUse())
14260     return SDValue();
14261
14262   SmallVector<int, 16> ShuffleMask;
14263   bool UnaryShuffle;
14264   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14265                             UnaryShuffle))
14266     return SDValue();
14267
14268   // Select the input vector, guarding against out of range extract vector.
14269   unsigned NumElems = VT.getVectorNumElements();
14270   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14271   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14272   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14273                                          : InVec.getOperand(1);
14274
14275   // If inputs to shuffle are the same for both ops, then allow 2 uses
14276   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14277
14278   if (LdNode.getOpcode() == ISD::BITCAST) {
14279     // Don't duplicate a load with other uses.
14280     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14281       return SDValue();
14282
14283     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14284     LdNode = LdNode.getOperand(0);
14285   }
14286
14287   if (!ISD::isNormalLoad(LdNode.getNode()))
14288     return SDValue();
14289
14290   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14291
14292   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14293     return SDValue();
14294
14295   if (HasShuffleIntoBitcast) {
14296     // If there's a bitcast before the shuffle, check if the load type and
14297     // alignment is valid.
14298     unsigned Align = LN0->getAlignment();
14299     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14300     unsigned NewAlign = TLI.getDataLayout()->
14301       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14302
14303     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14304       return SDValue();
14305   }
14306
14307   // All checks match so transform back to vector_shuffle so that DAG combiner
14308   // can finish the job
14309   DebugLoc dl = N->getDebugLoc();
14310
14311   // Create shuffle node taking into account the case that its a unary shuffle
14312   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14313   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14314                                  InVec.getOperand(0), Shuffle,
14315                                  &ShuffleMask[0]);
14316   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14317   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14318                      EltNo);
14319 }
14320
14321 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14322 /// generation and convert it from being a bunch of shuffles and extracts
14323 /// to a simple store and scalar loads to extract the elements.
14324 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14325                                          TargetLowering::DAGCombinerInfo &DCI) {
14326   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14327   if (NewOp.getNode())
14328     return NewOp;
14329
14330   SDValue InputVector = N->getOperand(0);
14331
14332   // Only operate on vectors of 4 elements, where the alternative shuffling
14333   // gets to be more expensive.
14334   if (InputVector.getValueType() != MVT::v4i32)
14335     return SDValue();
14336
14337   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14338   // single use which is a sign-extend or zero-extend, and all elements are
14339   // used.
14340   SmallVector<SDNode *, 4> Uses;
14341   unsigned ExtractedElements = 0;
14342   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14343        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14344     if (UI.getUse().getResNo() != InputVector.getResNo())
14345       return SDValue();
14346
14347     SDNode *Extract = *UI;
14348     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14349       return SDValue();
14350
14351     if (Extract->getValueType(0) != MVT::i32)
14352       return SDValue();
14353     if (!Extract->hasOneUse())
14354       return SDValue();
14355     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14356         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14357       return SDValue();
14358     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14359       return SDValue();
14360
14361     // Record which element was extracted.
14362     ExtractedElements |=
14363       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14364
14365     Uses.push_back(Extract);
14366   }
14367
14368   // If not all the elements were used, this may not be worthwhile.
14369   if (ExtractedElements != 15)
14370     return SDValue();
14371
14372   // Ok, we've now decided to do the transformation.
14373   DebugLoc dl = InputVector.getDebugLoc();
14374
14375   // Store the value to a temporary stack slot.
14376   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14377   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14378                             MachinePointerInfo(), false, false, 0);
14379
14380   // Replace each use (extract) with a load of the appropriate element.
14381   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14382        UE = Uses.end(); UI != UE; ++UI) {
14383     SDNode *Extract = *UI;
14384
14385     // cOMpute the element's address.
14386     SDValue Idx = Extract->getOperand(1);
14387     unsigned EltSize =
14388         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14389     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14390     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14391     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14392
14393     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14394                                      StackPtr, OffsetVal);
14395
14396     // Load the scalar.
14397     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14398                                      ScalarAddr, MachinePointerInfo(),
14399                                      false, false, false, 0);
14400
14401     // Replace the exact with the load.
14402     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14403   }
14404
14405   // The replacement was made in place; don't return anything.
14406   return SDValue();
14407 }
14408
14409 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14410 /// nodes.
14411 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14412                                     TargetLowering::DAGCombinerInfo &DCI,
14413                                     const X86Subtarget *Subtarget) {
14414   DebugLoc DL = N->getDebugLoc();
14415   SDValue Cond = N->getOperand(0);
14416   // Get the LHS/RHS of the select.
14417   SDValue LHS = N->getOperand(1);
14418   SDValue RHS = N->getOperand(2);
14419   EVT VT = LHS.getValueType();
14420
14421   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14422   // instructions match the semantics of the common C idiom x<y?x:y but not
14423   // x<=y?x:y, because of how they handle negative zero (which can be
14424   // ignored in unsafe-math mode).
14425   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14426       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14427       (Subtarget->hasSSE2() ||
14428        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14429     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14430
14431     unsigned Opcode = 0;
14432     // Check for x CC y ? x : y.
14433     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14434         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14435       switch (CC) {
14436       default: break;
14437       case ISD::SETULT:
14438         // Converting this to a min would handle NaNs incorrectly, and swapping
14439         // the operands would cause it to handle comparisons between positive
14440         // and negative zero incorrectly.
14441         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14442           if (!DAG.getTarget().Options.UnsafeFPMath &&
14443               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14444             break;
14445           std::swap(LHS, RHS);
14446         }
14447         Opcode = X86ISD::FMIN;
14448         break;
14449       case ISD::SETOLE:
14450         // Converting this to a min would handle comparisons between positive
14451         // and negative zero incorrectly.
14452         if (!DAG.getTarget().Options.UnsafeFPMath &&
14453             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14454           break;
14455         Opcode = X86ISD::FMIN;
14456         break;
14457       case ISD::SETULE:
14458         // Converting this to a min would handle both negative zeros and NaNs
14459         // incorrectly, but we can swap the operands to fix both.
14460         std::swap(LHS, RHS);
14461       case ISD::SETOLT:
14462       case ISD::SETLT:
14463       case ISD::SETLE:
14464         Opcode = X86ISD::FMIN;
14465         break;
14466
14467       case ISD::SETOGE:
14468         // Converting this to a max would handle comparisons between positive
14469         // and negative zero incorrectly.
14470         if (!DAG.getTarget().Options.UnsafeFPMath &&
14471             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14472           break;
14473         Opcode = X86ISD::FMAX;
14474         break;
14475       case ISD::SETUGT:
14476         // Converting this to a max would handle NaNs incorrectly, and swapping
14477         // the operands would cause it to handle comparisons between positive
14478         // and negative zero incorrectly.
14479         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14480           if (!DAG.getTarget().Options.UnsafeFPMath &&
14481               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14482             break;
14483           std::swap(LHS, RHS);
14484         }
14485         Opcode = X86ISD::FMAX;
14486         break;
14487       case ISD::SETUGE:
14488         // Converting this to a max would handle both negative zeros and NaNs
14489         // incorrectly, but we can swap the operands to fix both.
14490         std::swap(LHS, RHS);
14491       case ISD::SETOGT:
14492       case ISD::SETGT:
14493       case ISD::SETGE:
14494         Opcode = X86ISD::FMAX;
14495         break;
14496       }
14497     // Check for x CC y ? y : x -- a min/max with reversed arms.
14498     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14499                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14500       switch (CC) {
14501       default: break;
14502       case ISD::SETOGE:
14503         // Converting this to a min would handle comparisons between positive
14504         // and negative zero incorrectly, and swapping the operands would
14505         // cause it to handle NaNs incorrectly.
14506         if (!DAG.getTarget().Options.UnsafeFPMath &&
14507             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14508           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14509             break;
14510           std::swap(LHS, RHS);
14511         }
14512         Opcode = X86ISD::FMIN;
14513         break;
14514       case ISD::SETUGT:
14515         // Converting this to a min would handle NaNs incorrectly.
14516         if (!DAG.getTarget().Options.UnsafeFPMath &&
14517             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14518           break;
14519         Opcode = X86ISD::FMIN;
14520         break;
14521       case ISD::SETUGE:
14522         // Converting this to a min would handle both negative zeros and NaNs
14523         // incorrectly, but we can swap the operands to fix both.
14524         std::swap(LHS, RHS);
14525       case ISD::SETOGT:
14526       case ISD::SETGT:
14527       case ISD::SETGE:
14528         Opcode = X86ISD::FMIN;
14529         break;
14530
14531       case ISD::SETULT:
14532         // Converting this to a max would handle NaNs incorrectly.
14533         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14534           break;
14535         Opcode = X86ISD::FMAX;
14536         break;
14537       case ISD::SETOLE:
14538         // Converting this to a max would handle comparisons between positive
14539         // and negative zero incorrectly, and swapping the operands would
14540         // cause it to handle NaNs incorrectly.
14541         if (!DAG.getTarget().Options.UnsafeFPMath &&
14542             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14543           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14544             break;
14545           std::swap(LHS, RHS);
14546         }
14547         Opcode = X86ISD::FMAX;
14548         break;
14549       case ISD::SETULE:
14550         // Converting this to a max would handle both negative zeros and NaNs
14551         // incorrectly, but we can swap the operands to fix both.
14552         std::swap(LHS, RHS);
14553       case ISD::SETOLT:
14554       case ISD::SETLT:
14555       case ISD::SETLE:
14556         Opcode = X86ISD::FMAX;
14557         break;
14558       }
14559     }
14560
14561     if (Opcode)
14562       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14563   }
14564
14565   // If this is a select between two integer constants, try to do some
14566   // optimizations.
14567   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14568     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14569       // Don't do this for crazy integer types.
14570       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14571         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14572         // so that TrueC (the true value) is larger than FalseC.
14573         bool NeedsCondInvert = false;
14574
14575         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14576             // Efficiently invertible.
14577             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
14578              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
14579               isa<ConstantSDNode>(Cond.getOperand(1))))) {
14580           NeedsCondInvert = true;
14581           std::swap(TrueC, FalseC);
14582         }
14583
14584         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
14585         if (FalseC->getAPIntValue() == 0 &&
14586             TrueC->getAPIntValue().isPowerOf2()) {
14587           if (NeedsCondInvert) // Invert the condition if needed.
14588             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14589                                DAG.getConstant(1, Cond.getValueType()));
14590
14591           // Zero extend the condition if needed.
14592           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14593
14594           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14595           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14596                              DAG.getConstant(ShAmt, MVT::i8));
14597         }
14598
14599         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14600         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14601           if (NeedsCondInvert) // Invert the condition if needed.
14602             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14603                                DAG.getConstant(1, Cond.getValueType()));
14604
14605           // Zero extend the condition if needed.
14606           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14607                              FalseC->getValueType(0), Cond);
14608           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14609                              SDValue(FalseC, 0));
14610         }
14611
14612         // Optimize cases that will turn into an LEA instruction.  This requires
14613         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14614         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14615           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14616           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14617
14618           bool isFastMultiplier = false;
14619           if (Diff < 10) {
14620             switch ((unsigned char)Diff) {
14621               default: break;
14622               case 1:  // result = add base, cond
14623               case 2:  // result = lea base(    , cond*2)
14624               case 3:  // result = lea base(cond, cond*2)
14625               case 4:  // result = lea base(    , cond*4)
14626               case 5:  // result = lea base(cond, cond*4)
14627               case 8:  // result = lea base(    , cond*8)
14628               case 9:  // result = lea base(cond, cond*8)
14629                 isFastMultiplier = true;
14630                 break;
14631             }
14632           }
14633
14634           if (isFastMultiplier) {
14635             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14636             if (NeedsCondInvert) // Invert the condition if needed.
14637               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14638                                  DAG.getConstant(1, Cond.getValueType()));
14639
14640             // Zero extend the condition if needed.
14641             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14642                                Cond);
14643             // Scale the condition by the difference.
14644             if (Diff != 1)
14645               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14646                                  DAG.getConstant(Diff, Cond.getValueType()));
14647
14648             // Add the base if non-zero.
14649             if (FalseC->getAPIntValue() != 0)
14650               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14651                                  SDValue(FalseC, 0));
14652             return Cond;
14653           }
14654         }
14655       }
14656   }
14657
14658   // Canonicalize max and min:
14659   // (x > y) ? x : y -> (x >= y) ? x : y
14660   // (x < y) ? x : y -> (x <= y) ? x : y
14661   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14662   // the need for an extra compare
14663   // against zero. e.g.
14664   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14665   // subl   %esi, %edi
14666   // testl  %edi, %edi
14667   // movl   $0, %eax
14668   // cmovgl %edi, %eax
14669   // =>
14670   // xorl   %eax, %eax
14671   // subl   %esi, $edi
14672   // cmovsl %eax, %edi
14673   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14674       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14675       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14676     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14677     switch (CC) {
14678     default: break;
14679     case ISD::SETLT:
14680     case ISD::SETGT: {
14681       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14682       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14683                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14684       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14685     }
14686     }
14687   }
14688
14689   // If we know that this node is legal then we know that it is going to be
14690   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14691   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14692   // to simplify previous instructions.
14693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14694   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14695       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14696     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14697
14698     // Don't optimize vector selects that map to mask-registers.
14699     if (BitWidth == 1)
14700       return SDValue();
14701
14702     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14703     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14704
14705     APInt KnownZero, KnownOne;
14706     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14707                                           DCI.isBeforeLegalizeOps());
14708     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14709         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14710       DCI.CommitTargetLoweringOpt(TLO);
14711   }
14712
14713   return SDValue();
14714 }
14715
14716 // Check whether a boolean test is testing a boolean value generated by
14717 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14718 // code.
14719 //
14720 // Simplify the following patterns:
14721 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14722 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14723 // to (Op EFLAGS Cond)
14724 //
14725 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14726 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14727 // to (Op EFLAGS !Cond)
14728 //
14729 // where Op could be BRCOND or CMOV.
14730 //
14731 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14732   // Quit if not CMP and SUB with its value result used.
14733   if (Cmp.getOpcode() != X86ISD::CMP &&
14734       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14735       return SDValue();
14736
14737   // Quit if not used as a boolean value.
14738   if (CC != X86::COND_E && CC != X86::COND_NE)
14739     return SDValue();
14740
14741   // Check CMP operands. One of them should be 0 or 1 and the other should be
14742   // an SetCC or extended from it.
14743   SDValue Op1 = Cmp.getOperand(0);
14744   SDValue Op2 = Cmp.getOperand(1);
14745
14746   SDValue SetCC;
14747   const ConstantSDNode* C = 0;
14748   bool needOppositeCond = (CC == X86::COND_E);
14749
14750   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14751     SetCC = Op2;
14752   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14753     SetCC = Op1;
14754   else // Quit if all operands are not constants.
14755     return SDValue();
14756
14757   if (C->getZExtValue() == 1)
14758     needOppositeCond = !needOppositeCond;
14759   else if (C->getZExtValue() != 0)
14760     // Quit if the constant is neither 0 or 1.
14761     return SDValue();
14762
14763   // Skip 'zext' node.
14764   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14765     SetCC = SetCC.getOperand(0);
14766
14767   switch (SetCC.getOpcode()) {
14768   case X86ISD::SETCC:
14769     // Set the condition code or opposite one if necessary.
14770     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14771     if (needOppositeCond)
14772       CC = X86::GetOppositeBranchCondition(CC);
14773     return SetCC.getOperand(1);
14774   case X86ISD::CMOV: {
14775     // Check whether false/true value has canonical one, i.e. 0 or 1.
14776     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14777     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14778     // Quit if true value is not a constant.
14779     if (!TVal)
14780       return SDValue();
14781     // Quit if false value is not a constant.
14782     if (!FVal) {
14783       // A special case for rdrand, where 0 is set if false cond is found.
14784       SDValue Op = SetCC.getOperand(0);
14785       if (Op.getOpcode() != X86ISD::RDRAND)
14786         return SDValue();
14787     }
14788     // Quit if false value is not the constant 0 or 1.
14789     bool FValIsFalse = true;
14790     if (FVal && FVal->getZExtValue() != 0) {
14791       if (FVal->getZExtValue() != 1)
14792         return SDValue();
14793       // If FVal is 1, opposite cond is needed.
14794       needOppositeCond = !needOppositeCond;
14795       FValIsFalse = false;
14796     }
14797     // Quit if TVal is not the constant opposite of FVal.
14798     if (FValIsFalse && TVal->getZExtValue() != 1)
14799       return SDValue();
14800     if (!FValIsFalse && TVal->getZExtValue() != 0)
14801       return SDValue();
14802     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14803     if (needOppositeCond)
14804       CC = X86::GetOppositeBranchCondition(CC);
14805     return SetCC.getOperand(3);
14806   }
14807   }
14808
14809   return SDValue();
14810 }
14811
14812 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14813 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14814                                   TargetLowering::DAGCombinerInfo &DCI,
14815                                   const X86Subtarget *Subtarget) {
14816   DebugLoc DL = N->getDebugLoc();
14817
14818   // If the flag operand isn't dead, don't touch this CMOV.
14819   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14820     return SDValue();
14821
14822   SDValue FalseOp = N->getOperand(0);
14823   SDValue TrueOp = N->getOperand(1);
14824   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14825   SDValue Cond = N->getOperand(3);
14826
14827   if (CC == X86::COND_E || CC == X86::COND_NE) {
14828     switch (Cond.getOpcode()) {
14829     default: break;
14830     case X86ISD::BSR:
14831     case X86ISD::BSF:
14832       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14833       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14834         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14835     }
14836   }
14837
14838   SDValue Flags;
14839
14840   Flags = checkBoolTestSetCCCombine(Cond, CC);
14841   if (Flags.getNode() &&
14842       // Extra check as FCMOV only supports a subset of X86 cond.
14843       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14844     SDValue Ops[] = { FalseOp, TrueOp,
14845                       DAG.getConstant(CC, MVT::i8), Flags };
14846     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14847                        Ops, array_lengthof(Ops));
14848   }
14849
14850   // If this is a select between two integer constants, try to do some
14851   // optimizations.  Note that the operands are ordered the opposite of SELECT
14852   // operands.
14853   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14854     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14855       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14856       // larger than FalseC (the false value).
14857       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14858         CC = X86::GetOppositeBranchCondition(CC);
14859         std::swap(TrueC, FalseC);
14860         std::swap(TrueOp, FalseOp);
14861       }
14862
14863       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14864       // This is efficient for any integer data type (including i8/i16) and
14865       // shift amount.
14866       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14867         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14868                            DAG.getConstant(CC, MVT::i8), Cond);
14869
14870         // Zero extend the condition if needed.
14871         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14872
14873         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14874         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14875                            DAG.getConstant(ShAmt, MVT::i8));
14876         if (N->getNumValues() == 2)  // Dead flag value?
14877           return DCI.CombineTo(N, Cond, SDValue());
14878         return Cond;
14879       }
14880
14881       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14882       // for any integer data type, including i8/i16.
14883       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14884         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14885                            DAG.getConstant(CC, MVT::i8), Cond);
14886
14887         // Zero extend the condition if needed.
14888         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14889                            FalseC->getValueType(0), Cond);
14890         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14891                            SDValue(FalseC, 0));
14892
14893         if (N->getNumValues() == 2)  // Dead flag value?
14894           return DCI.CombineTo(N, Cond, SDValue());
14895         return Cond;
14896       }
14897
14898       // Optimize cases that will turn into an LEA instruction.  This requires
14899       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14900       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14901         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14902         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14903
14904         bool isFastMultiplier = false;
14905         if (Diff < 10) {
14906           switch ((unsigned char)Diff) {
14907           default: break;
14908           case 1:  // result = add base, cond
14909           case 2:  // result = lea base(    , cond*2)
14910           case 3:  // result = lea base(cond, cond*2)
14911           case 4:  // result = lea base(    , cond*4)
14912           case 5:  // result = lea base(cond, cond*4)
14913           case 8:  // result = lea base(    , cond*8)
14914           case 9:  // result = lea base(cond, cond*8)
14915             isFastMultiplier = true;
14916             break;
14917           }
14918         }
14919
14920         if (isFastMultiplier) {
14921           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14922           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14923                              DAG.getConstant(CC, MVT::i8), Cond);
14924           // Zero extend the condition if needed.
14925           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14926                              Cond);
14927           // Scale the condition by the difference.
14928           if (Diff != 1)
14929             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14930                                DAG.getConstant(Diff, Cond.getValueType()));
14931
14932           // Add the base if non-zero.
14933           if (FalseC->getAPIntValue() != 0)
14934             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14935                                SDValue(FalseC, 0));
14936           if (N->getNumValues() == 2)  // Dead flag value?
14937             return DCI.CombineTo(N, Cond, SDValue());
14938           return Cond;
14939         }
14940       }
14941     }
14942   }
14943
14944   // Handle these cases:
14945   //   (select (x != c), e, c) -> select (x != c), e, x),
14946   //   (select (x == c), c, e) -> select (x == c), x, e)
14947   // where the c is an integer constant, and the "select" is the combination
14948   // of CMOV and CMP.
14949   //
14950   // The rationale for this change is that the conditional-move from a constant
14951   // needs two instructions, however, conditional-move from a register needs
14952   // only one instruction.
14953   //
14954   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14955   //  some instruction-combining opportunities. This opt needs to be
14956   //  postponed as late as possible.
14957   //
14958   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14959     // the DCI.xxxx conditions are provided to postpone the optimization as
14960     // late as possible.
14961
14962     ConstantSDNode *CmpAgainst = 0;
14963     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14964         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14965         dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14966
14967       if (CC == X86::COND_NE &&
14968           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14969         CC = X86::GetOppositeBranchCondition(CC);
14970         std::swap(TrueOp, FalseOp);
14971       }
14972
14973       if (CC == X86::COND_E &&
14974           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14975         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14976                           DAG.getConstant(CC, MVT::i8), Cond };
14977         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14978                            array_lengthof(Ops));
14979       }
14980     }
14981   }
14982
14983   return SDValue();
14984 }
14985
14986
14987 /// PerformMulCombine - Optimize a single multiply with constant into two
14988 /// in order to implement it with two cheaper instructions, e.g.
14989 /// LEA + SHL, LEA + LEA.
14990 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14991                                  TargetLowering::DAGCombinerInfo &DCI) {
14992   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14993     return SDValue();
14994
14995   EVT VT = N->getValueType(0);
14996   if (VT != MVT::i64)
14997     return SDValue();
14998
14999   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15000   if (!C)
15001     return SDValue();
15002   uint64_t MulAmt = C->getZExtValue();
15003   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15004     return SDValue();
15005
15006   uint64_t MulAmt1 = 0;
15007   uint64_t MulAmt2 = 0;
15008   if ((MulAmt % 9) == 0) {
15009     MulAmt1 = 9;
15010     MulAmt2 = MulAmt / 9;
15011   } else if ((MulAmt % 5) == 0) {
15012     MulAmt1 = 5;
15013     MulAmt2 = MulAmt / 5;
15014   } else if ((MulAmt % 3) == 0) {
15015     MulAmt1 = 3;
15016     MulAmt2 = MulAmt / 3;
15017   }
15018   if (MulAmt2 &&
15019       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15020     DebugLoc DL = N->getDebugLoc();
15021
15022     if (isPowerOf2_64(MulAmt2) &&
15023         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15024       // If second multiplifer is pow2, issue it first. We want the multiply by
15025       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15026       // is an add.
15027       std::swap(MulAmt1, MulAmt2);
15028
15029     SDValue NewMul;
15030     if (isPowerOf2_64(MulAmt1))
15031       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15032                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15033     else
15034       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15035                            DAG.getConstant(MulAmt1, VT));
15036
15037     if (isPowerOf2_64(MulAmt2))
15038       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15039                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15040     else
15041       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15042                            DAG.getConstant(MulAmt2, VT));
15043
15044     // Do not add new nodes to DAG combiner worklist.
15045     DCI.CombineTo(N, NewMul, false);
15046   }
15047   return SDValue();
15048 }
15049
15050 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15051   SDValue N0 = N->getOperand(0);
15052   SDValue N1 = N->getOperand(1);
15053   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15054   EVT VT = N0.getValueType();
15055
15056   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15057   // since the result of setcc_c is all zero's or all ones.
15058   if (VT.isInteger() && !VT.isVector() &&
15059       N1C && N0.getOpcode() == ISD::AND &&
15060       N0.getOperand(1).getOpcode() == ISD::Constant) {
15061     SDValue N00 = N0.getOperand(0);
15062     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15063         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15064           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15065          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15066       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15067       APInt ShAmt = N1C->getAPIntValue();
15068       Mask = Mask.shl(ShAmt);
15069       if (Mask != 0)
15070         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15071                            N00, DAG.getConstant(Mask, VT));
15072     }
15073   }
15074
15075
15076   // Hardware support for vector shifts is sparse which makes us scalarize the
15077   // vector operations in many cases. Also, on sandybridge ADD is faster than
15078   // shl.
15079   // (shl V, 1) -> add V,V
15080   if (isSplatVector(N1.getNode())) {
15081     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15082     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15083     // We shift all of the values by one. In many cases we do not have
15084     // hardware support for this operation. This is better expressed as an ADD
15085     // of two values.
15086     if (N1C && (1 == N1C->getZExtValue())) {
15087       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15088     }
15089   }
15090
15091   return SDValue();
15092 }
15093
15094 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15095 ///                       when possible.
15096 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15097                                    TargetLowering::DAGCombinerInfo &DCI,
15098                                    const X86Subtarget *Subtarget) {
15099   EVT VT = N->getValueType(0);
15100   if (N->getOpcode() == ISD::SHL) {
15101     SDValue V = PerformSHLCombine(N, DAG);
15102     if (V.getNode()) return V;
15103   }
15104
15105   // On X86 with SSE2 support, we can transform this to a vector shift if
15106   // all elements are shifted by the same amount.  We can't do this in legalize
15107   // because the a constant vector is typically transformed to a constant pool
15108   // so we have no knowledge of the shift amount.
15109   if (!Subtarget->hasSSE2())
15110     return SDValue();
15111
15112   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15113       (!Subtarget->hasAVX2() ||
15114        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15115     return SDValue();
15116
15117   SDValue ShAmtOp = N->getOperand(1);
15118   EVT EltVT = VT.getVectorElementType();
15119   DebugLoc DL = N->getDebugLoc();
15120   SDValue BaseShAmt = SDValue();
15121   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15122     unsigned NumElts = VT.getVectorNumElements();
15123     unsigned i = 0;
15124     for (; i != NumElts; ++i) {
15125       SDValue Arg = ShAmtOp.getOperand(i);
15126       if (Arg.getOpcode() == ISD::UNDEF) continue;
15127       BaseShAmt = Arg;
15128       break;
15129     }
15130     // Handle the case where the build_vector is all undef
15131     // FIXME: Should DAG allow this?
15132     if (i == NumElts)
15133       return SDValue();
15134
15135     for (; i != NumElts; ++i) {
15136       SDValue Arg = ShAmtOp.getOperand(i);
15137       if (Arg.getOpcode() == ISD::UNDEF) continue;
15138       if (Arg != BaseShAmt) {
15139         return SDValue();
15140       }
15141     }
15142   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15143              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15144     SDValue InVec = ShAmtOp.getOperand(0);
15145     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15146       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15147       unsigned i = 0;
15148       for (; i != NumElts; ++i) {
15149         SDValue Arg = InVec.getOperand(i);
15150         if (Arg.getOpcode() == ISD::UNDEF) continue;
15151         BaseShAmt = Arg;
15152         break;
15153       }
15154     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15155        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15156          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15157          if (C->getZExtValue() == SplatIdx)
15158            BaseShAmt = InVec.getOperand(1);
15159        }
15160     }
15161     if (BaseShAmt.getNode() == 0) {
15162       // Don't create instructions with illegal types after legalize
15163       // types has run.
15164       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15165           !DCI.isBeforeLegalize())
15166         return SDValue();
15167
15168       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15169                               DAG.getIntPtrConstant(0));
15170     }
15171   } else
15172     return SDValue();
15173
15174   // The shift amount is an i32.
15175   if (EltVT.bitsGT(MVT::i32))
15176     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15177   else if (EltVT.bitsLT(MVT::i32))
15178     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15179
15180   // The shift amount is identical so we can do a vector shift.
15181   SDValue  ValOp = N->getOperand(0);
15182   switch (N->getOpcode()) {
15183   default:
15184     llvm_unreachable("Unknown shift opcode!");
15185   case ISD::SHL:
15186     switch (VT.getSimpleVT().SimpleTy) {
15187     default: return SDValue();
15188     case MVT::v2i64:
15189     case MVT::v4i32:
15190     case MVT::v8i16:
15191     case MVT::v4i64:
15192     case MVT::v8i32:
15193     case MVT::v16i16:
15194       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15195     }
15196   case ISD::SRA:
15197     switch (VT.getSimpleVT().SimpleTy) {
15198     default: return SDValue();
15199     case MVT::v4i32:
15200     case MVT::v8i16:
15201     case MVT::v8i32:
15202     case MVT::v16i16:
15203       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15204     }
15205   case ISD::SRL:
15206     switch (VT.getSimpleVT().SimpleTy) {
15207     default: return SDValue();
15208     case MVT::v2i64:
15209     case MVT::v4i32:
15210     case MVT::v8i16:
15211     case MVT::v4i64:
15212     case MVT::v8i32:
15213     case MVT::v16i16:
15214       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15215     }
15216   }
15217 }
15218
15219
15220 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
15221 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15222 // and friends.  Likewise for OR -> CMPNEQSS.
15223 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15224                             TargetLowering::DAGCombinerInfo &DCI,
15225                             const X86Subtarget *Subtarget) {
15226   unsigned opcode;
15227
15228   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15229   // we're requiring SSE2 for both.
15230   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15231     SDValue N0 = N->getOperand(0);
15232     SDValue N1 = N->getOperand(1);
15233     SDValue CMP0 = N0->getOperand(1);
15234     SDValue CMP1 = N1->getOperand(1);
15235     DebugLoc DL = N->getDebugLoc();
15236
15237     // The SETCCs should both refer to the same CMP.
15238     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15239       return SDValue();
15240
15241     SDValue CMP00 = CMP0->getOperand(0);
15242     SDValue CMP01 = CMP0->getOperand(1);
15243     EVT     VT    = CMP00.getValueType();
15244
15245     if (VT == MVT::f32 || VT == MVT::f64) {
15246       bool ExpectingFlags = false;
15247       // Check for any users that want flags:
15248       for (SDNode::use_iterator UI = N->use_begin(),
15249              UE = N->use_end();
15250            !ExpectingFlags && UI != UE; ++UI)
15251         switch (UI->getOpcode()) {
15252         default:
15253         case ISD::BR_CC:
15254         case ISD::BRCOND:
15255         case ISD::SELECT:
15256           ExpectingFlags = true;
15257           break;
15258         case ISD::CopyToReg:
15259         case ISD::SIGN_EXTEND:
15260         case ISD::ZERO_EXTEND:
15261         case ISD::ANY_EXTEND:
15262           break;
15263         }
15264
15265       if (!ExpectingFlags) {
15266         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15267         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15268
15269         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15270           X86::CondCode tmp = cc0;
15271           cc0 = cc1;
15272           cc1 = tmp;
15273         }
15274
15275         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
15276             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15277           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15278           X86ISD::NodeType NTOperator = is64BitFP ?
15279             X86ISD::FSETCCsd : X86ISD::FSETCCss;
15280           // FIXME: need symbolic constants for these magic numbers.
15281           // See X86ATTInstPrinter.cpp:printSSECC().
15282           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15283           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15284                                               DAG.getConstant(x86cc, MVT::i8));
15285           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15286                                               OnesOrZeroesF);
15287           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15288                                       DAG.getConstant(1, MVT::i32));
15289           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15290           return OneBitOfTruth;
15291         }
15292       }
15293     }
15294   }
15295   return SDValue();
15296 }
15297
15298 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15299 /// so it can be folded inside ANDNP.
15300 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15301   EVT VT = N->getValueType(0);
15302
15303   // Match direct AllOnes for 128 and 256-bit vectors
15304   if (ISD::isBuildVectorAllOnes(N))
15305     return true;
15306
15307   // Look through a bit convert.
15308   if (N->getOpcode() == ISD::BITCAST)
15309     N = N->getOperand(0).getNode();
15310
15311   // Sometimes the operand may come from a insert_subvector building a 256-bit
15312   // allones vector
15313   if (VT.is256BitVector() &&
15314       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15315     SDValue V1 = N->getOperand(0);
15316     SDValue V2 = N->getOperand(1);
15317
15318     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15319         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15320         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15321         ISD::isBuildVectorAllOnes(V2.getNode()))
15322       return true;
15323   }
15324
15325   return false;
15326 }
15327
15328 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15329                                  TargetLowering::DAGCombinerInfo &DCI,
15330                                  const X86Subtarget *Subtarget) {
15331   if (DCI.isBeforeLegalizeOps())
15332     return SDValue();
15333
15334   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15335   if (R.getNode())
15336     return R;
15337
15338   EVT VT = N->getValueType(0);
15339
15340   // Create ANDN, BLSI, and BLSR instructions
15341   // BLSI is X & (-X)
15342   // BLSR is X & (X-1)
15343   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15344     SDValue N0 = N->getOperand(0);
15345     SDValue N1 = N->getOperand(1);
15346     DebugLoc DL = N->getDebugLoc();
15347
15348     // Check LHS for not
15349     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15350       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15351     // Check RHS for not
15352     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15353       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15354
15355     // Check LHS for neg
15356     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15357         isZero(N0.getOperand(0)))
15358       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15359
15360     // Check RHS for neg
15361     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15362         isZero(N1.getOperand(0)))
15363       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15364
15365     // Check LHS for X-1
15366     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15367         isAllOnes(N0.getOperand(1)))
15368       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15369
15370     // Check RHS for X-1
15371     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15372         isAllOnes(N1.getOperand(1)))
15373       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15374
15375     return SDValue();
15376   }
15377
15378   // Want to form ANDNP nodes:
15379   // 1) In the hopes of then easily combining them with OR and AND nodes
15380   //    to form PBLEND/PSIGN.
15381   // 2) To match ANDN packed intrinsics
15382   if (VT != MVT::v2i64 && VT != MVT::v4i64)
15383     return SDValue();
15384
15385   SDValue N0 = N->getOperand(0);
15386   SDValue N1 = N->getOperand(1);
15387   DebugLoc DL = N->getDebugLoc();
15388
15389   // Check LHS for vnot
15390   if (N0.getOpcode() == ISD::XOR &&
15391       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15392       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15393     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15394
15395   // Check RHS for vnot
15396   if (N1.getOpcode() == ISD::XOR &&
15397       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15398       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15399     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15400
15401   return SDValue();
15402 }
15403
15404 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15405                                 TargetLowering::DAGCombinerInfo &DCI,
15406                                 const X86Subtarget *Subtarget) {
15407   if (DCI.isBeforeLegalizeOps())
15408     return SDValue();
15409
15410   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15411   if (R.getNode())
15412     return R;
15413
15414   EVT VT = N->getValueType(0);
15415
15416   SDValue N0 = N->getOperand(0);
15417   SDValue N1 = N->getOperand(1);
15418
15419   // look for psign/blend
15420   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15421     if (!Subtarget->hasSSSE3() ||
15422         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15423       return SDValue();
15424
15425     // Canonicalize pandn to RHS
15426     if (N0.getOpcode() == X86ISD::ANDNP)
15427       std::swap(N0, N1);
15428     // or (and (m, y), (pandn m, x))
15429     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15430       SDValue Mask = N1.getOperand(0);
15431       SDValue X    = N1.getOperand(1);
15432       SDValue Y;
15433       if (N0.getOperand(0) == Mask)
15434         Y = N0.getOperand(1);
15435       if (N0.getOperand(1) == Mask)
15436         Y = N0.getOperand(0);
15437
15438       // Check to see if the mask appeared in both the AND and ANDNP and
15439       if (!Y.getNode())
15440         return SDValue();
15441
15442       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15443       // Look through mask bitcast.
15444       if (Mask.getOpcode() == ISD::BITCAST)
15445         Mask = Mask.getOperand(0);
15446       if (X.getOpcode() == ISD::BITCAST)
15447         X = X.getOperand(0);
15448       if (Y.getOpcode() == ISD::BITCAST)
15449         Y = Y.getOperand(0);
15450
15451       EVT MaskVT = Mask.getValueType();
15452
15453       // Validate that the Mask operand is a vector sra node.
15454       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15455       // there is no psrai.b
15456       if (Mask.getOpcode() != X86ISD::VSRAI)
15457         return SDValue();
15458
15459       // Check that the SRA is all signbits.
15460       SDValue SraC = Mask.getOperand(1);
15461       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
15462       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15463       if ((SraAmt + 1) != EltBits)
15464         return SDValue();
15465
15466       DebugLoc DL = N->getDebugLoc();
15467
15468       // Now we know we at least have a plendvb with the mask val.  See if
15469       // we can form a psignb/w/d.
15470       // psign = x.type == y.type == mask.type && y = sub(0, x);
15471       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15472           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15473           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15474         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15475                "Unsupported VT for PSIGN");
15476         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15477         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15478       }
15479       // PBLENDVB only available on SSE 4.1
15480       if (!Subtarget->hasSSE41())
15481         return SDValue();
15482
15483       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15484
15485       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15486       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15487       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15488       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15489       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15490     }
15491   }
15492
15493   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15494     return SDValue();
15495
15496   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15497   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15498     std::swap(N0, N1);
15499   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15500     return SDValue();
15501   if (!N0.hasOneUse() || !N1.hasOneUse())
15502     return SDValue();
15503
15504   SDValue ShAmt0 = N0.getOperand(1);
15505   if (ShAmt0.getValueType() != MVT::i8)
15506     return SDValue();
15507   SDValue ShAmt1 = N1.getOperand(1);
15508   if (ShAmt1.getValueType() != MVT::i8)
15509     return SDValue();
15510   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15511     ShAmt0 = ShAmt0.getOperand(0);
15512   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15513     ShAmt1 = ShAmt1.getOperand(0);
15514
15515   DebugLoc DL = N->getDebugLoc();
15516   unsigned Opc = X86ISD::SHLD;
15517   SDValue Op0 = N0.getOperand(0);
15518   SDValue Op1 = N1.getOperand(0);
15519   if (ShAmt0.getOpcode() == ISD::SUB) {
15520     Opc = X86ISD::SHRD;
15521     std::swap(Op0, Op1);
15522     std::swap(ShAmt0, ShAmt1);
15523   }
15524
15525   unsigned Bits = VT.getSizeInBits();
15526   if (ShAmt1.getOpcode() == ISD::SUB) {
15527     SDValue Sum = ShAmt1.getOperand(0);
15528     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15529       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15530       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15531         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15532       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15533         return DAG.getNode(Opc, DL, VT,
15534                            Op0, Op1,
15535                            DAG.getNode(ISD::TRUNCATE, DL,
15536                                        MVT::i8, ShAmt0));
15537     }
15538   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15539     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15540     if (ShAmt0C &&
15541         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15542       return DAG.getNode(Opc, DL, VT,
15543                          N0.getOperand(0), N1.getOperand(0),
15544                          DAG.getNode(ISD::TRUNCATE, DL,
15545                                        MVT::i8, ShAmt0));
15546   }
15547
15548   return SDValue();
15549 }
15550
15551 // Generate NEG and CMOV for integer abs.
15552 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15553   EVT VT = N->getValueType(0);
15554
15555   // Since X86 does not have CMOV for 8-bit integer, we don't convert
15556   // 8-bit integer abs to NEG and CMOV.
15557   if (VT.isInteger() && VT.getSizeInBits() == 8)
15558     return SDValue();
15559
15560   SDValue N0 = N->getOperand(0);
15561   SDValue N1 = N->getOperand(1);
15562   DebugLoc DL = N->getDebugLoc();
15563
15564   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15565   // and change it to SUB and CMOV.
15566   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15567       N0.getOpcode() == ISD::ADD &&
15568       N0.getOperand(1) == N1 &&
15569       N1.getOpcode() == ISD::SRA &&
15570       N1.getOperand(0) == N0.getOperand(0))
15571     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15572       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15573         // Generate SUB & CMOV.
15574         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15575                                   DAG.getConstant(0, VT), N0.getOperand(0));
15576
15577         SDValue Ops[] = { N0.getOperand(0), Neg,
15578                           DAG.getConstant(X86::COND_GE, MVT::i8),
15579                           SDValue(Neg.getNode(), 1) };
15580         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15581                            Ops, array_lengthof(Ops));
15582       }
15583   return SDValue();
15584 }
15585
15586 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15587 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15588                                  TargetLowering::DAGCombinerInfo &DCI,
15589                                  const X86Subtarget *Subtarget) {
15590   if (DCI.isBeforeLegalizeOps())
15591     return SDValue();
15592
15593   if (Subtarget->hasCMov()) {
15594     SDValue RV = performIntegerAbsCombine(N, DAG);
15595     if (RV.getNode())
15596       return RV;
15597   }
15598
15599   // Try forming BMI if it is available.
15600   if (!Subtarget->hasBMI())
15601     return SDValue();
15602
15603   EVT VT = N->getValueType(0);
15604
15605   if (VT != MVT::i32 && VT != MVT::i64)
15606     return SDValue();
15607
15608   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15609
15610   // Create BLSMSK instructions by finding X ^ (X-1)
15611   SDValue N0 = N->getOperand(0);
15612   SDValue N1 = N->getOperand(1);
15613   DebugLoc DL = N->getDebugLoc();
15614
15615   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15616       isAllOnes(N0.getOperand(1)))
15617     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15618
15619   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15620       isAllOnes(N1.getOperand(1)))
15621     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15622
15623   return SDValue();
15624 }
15625
15626 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15627 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15628                                   TargetLowering::DAGCombinerInfo &DCI,
15629                                   const X86Subtarget *Subtarget) {
15630   LoadSDNode *Ld = cast<LoadSDNode>(N);
15631   EVT RegVT = Ld->getValueType(0);
15632   EVT MemVT = Ld->getMemoryVT();
15633   DebugLoc dl = Ld->getDebugLoc();
15634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15635
15636   ISD::LoadExtType Ext = Ld->getExtensionType();
15637
15638   // If this is a vector EXT Load then attempt to optimize it using a
15639   // shuffle. We need SSSE3 shuffles.
15640   // TODO: It is possible to support ZExt by zeroing the undef values
15641   // during the shuffle phase or after the shuffle.
15642   if (RegVT.isVector() && RegVT.isInteger() &&
15643       Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15644     assert(MemVT != RegVT && "Cannot extend to the same type");
15645     assert(MemVT.isVector() && "Must load a vector from memory");
15646
15647     unsigned NumElems = RegVT.getVectorNumElements();
15648     unsigned RegSz = RegVT.getSizeInBits();
15649     unsigned MemSz = MemVT.getSizeInBits();
15650     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15651
15652     // All sizes must be a power of two.
15653     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15654       return SDValue();
15655
15656     // Attempt to load the original value using scalar loads.
15657     // Find the largest scalar type that divides the total loaded size.
15658     MVT SclrLoadTy = MVT::i8;
15659     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15660          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15661       MVT Tp = (MVT::SimpleValueType)tp;
15662       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15663         SclrLoadTy = Tp;
15664       }
15665     }
15666
15667     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15668     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15669         (64 <= MemSz))
15670       SclrLoadTy = MVT::f64;
15671
15672     // Calculate the number of scalar loads that we need to perform
15673     // in order to load our vector from memory.
15674     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15675
15676     // Represent our vector as a sequence of elements which are the
15677     // largest scalar that we can load.
15678     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15679       RegSz/SclrLoadTy.getSizeInBits());
15680
15681     // Represent the data using the same element type that is stored in
15682     // memory. In practice, we ''widen'' MemVT.
15683     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15684                                   RegSz/MemVT.getScalarType().getSizeInBits());
15685
15686     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15687       "Invalid vector type");
15688
15689     // We can't shuffle using an illegal type.
15690     if (!TLI.isTypeLegal(WideVecVT))
15691       return SDValue();
15692
15693     SmallVector<SDValue, 8> Chains;
15694     SDValue Ptr = Ld->getBasePtr();
15695     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15696                                         TLI.getPointerTy());
15697     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15698
15699     for (unsigned i = 0; i < NumLoads; ++i) {
15700       // Perform a single load.
15701       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15702                                        Ptr, Ld->getPointerInfo(),
15703                                        Ld->isVolatile(), Ld->isNonTemporal(),
15704                                        Ld->isInvariant(), Ld->getAlignment());
15705       Chains.push_back(ScalarLoad.getValue(1));
15706       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15707       // another round of DAGCombining.
15708       if (i == 0)
15709         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15710       else
15711         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15712                           ScalarLoad, DAG.getIntPtrConstant(i));
15713
15714       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15715     }
15716
15717     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15718                                Chains.size());
15719
15720     // Bitcast the loaded value to a vector of the original element type, in
15721     // the size of the target vector type.
15722     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15723     unsigned SizeRatio = RegSz/MemSz;
15724
15725     // Redistribute the loaded elements into the different locations.
15726     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15727     for (unsigned i = 0; i != NumElems; ++i)
15728       ShuffleVec[i*SizeRatio] = i;
15729
15730     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15731                                          DAG.getUNDEF(WideVecVT),
15732                                          &ShuffleVec[0]);
15733
15734     // Bitcast to the requested type.
15735     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15736     // Replace the original load with the new sequence
15737     // and return the new chain.
15738     return DCI.CombineTo(N, Shuff, TF, true);
15739   }
15740
15741   return SDValue();
15742 }
15743
15744 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15745 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15746                                    const X86Subtarget *Subtarget) {
15747   StoreSDNode *St = cast<StoreSDNode>(N);
15748   EVT VT = St->getValue().getValueType();
15749   EVT StVT = St->getMemoryVT();
15750   DebugLoc dl = St->getDebugLoc();
15751   SDValue StoredVal = St->getOperand(1);
15752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15753
15754   // If we are saving a concatenation of two XMM registers, perform two stores.
15755   // On Sandy Bridge, 256-bit memory operations are executed by two
15756   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15757   // memory  operation.
15758   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15759       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15760       StoredVal.getNumOperands() == 2) {
15761     SDValue Value0 = StoredVal.getOperand(0);
15762     SDValue Value1 = StoredVal.getOperand(1);
15763
15764     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15765     SDValue Ptr0 = St->getBasePtr();
15766     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15767
15768     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15769                                 St->getPointerInfo(), St->isVolatile(),
15770                                 St->isNonTemporal(), St->getAlignment());
15771     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15772                                 St->getPointerInfo(), St->isVolatile(),
15773                                 St->isNonTemporal(), St->getAlignment());
15774     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15775   }
15776
15777   // Optimize trunc store (of multiple scalars) to shuffle and store.
15778   // First, pack all of the elements in one place. Next, store to memory
15779   // in fewer chunks.
15780   if (St->isTruncatingStore() && VT.isVector()) {
15781     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15782     unsigned NumElems = VT.getVectorNumElements();
15783     assert(StVT != VT && "Cannot truncate to the same type");
15784     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15785     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15786
15787     // From, To sizes and ElemCount must be pow of two
15788     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15789     // We are going to use the original vector elt for storing.
15790     // Accumulated smaller vector elements must be a multiple of the store size.
15791     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15792
15793     unsigned SizeRatio  = FromSz / ToSz;
15794
15795     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15796
15797     // Create a type on which we perform the shuffle
15798     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15799             StVT.getScalarType(), NumElems*SizeRatio);
15800
15801     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15802
15803     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15804     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15805     for (unsigned i = 0; i != NumElems; ++i)
15806       ShuffleVec[i] = i * SizeRatio;
15807
15808     // Can't shuffle using an illegal type.
15809     if (!TLI.isTypeLegal(WideVecVT))
15810       return SDValue();
15811
15812     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15813                                          DAG.getUNDEF(WideVecVT),
15814                                          &ShuffleVec[0]);
15815     // At this point all of the data is stored at the bottom of the
15816     // register. We now need to save it to mem.
15817
15818     // Find the largest store unit
15819     MVT StoreType = MVT::i8;
15820     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15821          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15822       MVT Tp = (MVT::SimpleValueType)tp;
15823       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15824         StoreType = Tp;
15825     }
15826
15827     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15828     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15829         (64 <= NumElems * ToSz))
15830       StoreType = MVT::f64;
15831
15832     // Bitcast the original vector into a vector of store-size units
15833     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15834             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15835     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15836     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15837     SmallVector<SDValue, 8> Chains;
15838     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15839                                         TLI.getPointerTy());
15840     SDValue Ptr = St->getBasePtr();
15841
15842     // Perform one or more big stores into memory.
15843     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15844       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15845                                    StoreType, ShuffWide,
15846                                    DAG.getIntPtrConstant(i));
15847       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15848                                 St->getPointerInfo(), St->isVolatile(),
15849                                 St->isNonTemporal(), St->getAlignment());
15850       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15851       Chains.push_back(Ch);
15852     }
15853
15854     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15855                                Chains.size());
15856   }
15857
15858
15859   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15860   // the FP state in cases where an emms may be missing.
15861   // A preferable solution to the general problem is to figure out the right
15862   // places to insert EMMS.  This qualifies as a quick hack.
15863
15864   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15865   if (VT.getSizeInBits() != 64)
15866     return SDValue();
15867
15868   const Function *F = DAG.getMachineFunction().getFunction();
15869   bool NoImplicitFloatOps = F->getFnAttributes().
15870     hasAttribute(Attributes::NoImplicitFloat);
15871   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15872                      && Subtarget->hasSSE2();
15873   if ((VT.isVector() ||
15874        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15875       isa<LoadSDNode>(St->getValue()) &&
15876       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15877       St->getChain().hasOneUse() && !St->isVolatile()) {
15878     SDNode* LdVal = St->getValue().getNode();
15879     LoadSDNode *Ld = 0;
15880     int TokenFactorIndex = -1;
15881     SmallVector<SDValue, 8> Ops;
15882     SDNode* ChainVal = St->getChain().getNode();
15883     // Must be a store of a load.  We currently handle two cases:  the load
15884     // is a direct child, and it's under an intervening TokenFactor.  It is
15885     // possible to dig deeper under nested TokenFactors.
15886     if (ChainVal == LdVal)
15887       Ld = cast<LoadSDNode>(St->getChain());
15888     else if (St->getValue().hasOneUse() &&
15889              ChainVal->getOpcode() == ISD::TokenFactor) {
15890       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15891         if (ChainVal->getOperand(i).getNode() == LdVal) {
15892           TokenFactorIndex = i;
15893           Ld = cast<LoadSDNode>(St->getValue());
15894         } else
15895           Ops.push_back(ChainVal->getOperand(i));
15896       }
15897     }
15898
15899     if (!Ld || !ISD::isNormalLoad(Ld))
15900       return SDValue();
15901
15902     // If this is not the MMX case, i.e. we are just turning i64 load/store
15903     // into f64 load/store, avoid the transformation if there are multiple
15904     // uses of the loaded value.
15905     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15906       return SDValue();
15907
15908     DebugLoc LdDL = Ld->getDebugLoc();
15909     DebugLoc StDL = N->getDebugLoc();
15910     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15911     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15912     // pair instead.
15913     if (Subtarget->is64Bit() || F64IsLegal) {
15914       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15915       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15916                                   Ld->getPointerInfo(), Ld->isVolatile(),
15917                                   Ld->isNonTemporal(), Ld->isInvariant(),
15918                                   Ld->getAlignment());
15919       SDValue NewChain = NewLd.getValue(1);
15920       if (TokenFactorIndex != -1) {
15921         Ops.push_back(NewChain);
15922         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15923                                Ops.size());
15924       }
15925       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15926                           St->getPointerInfo(),
15927                           St->isVolatile(), St->isNonTemporal(),
15928                           St->getAlignment());
15929     }
15930
15931     // Otherwise, lower to two pairs of 32-bit loads / stores.
15932     SDValue LoAddr = Ld->getBasePtr();
15933     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15934                                  DAG.getConstant(4, MVT::i32));
15935
15936     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15937                                Ld->getPointerInfo(),
15938                                Ld->isVolatile(), Ld->isNonTemporal(),
15939                                Ld->isInvariant(), Ld->getAlignment());
15940     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15941                                Ld->getPointerInfo().getWithOffset(4),
15942                                Ld->isVolatile(), Ld->isNonTemporal(),
15943                                Ld->isInvariant(),
15944                                MinAlign(Ld->getAlignment(), 4));
15945
15946     SDValue NewChain = LoLd.getValue(1);
15947     if (TokenFactorIndex != -1) {
15948       Ops.push_back(LoLd);
15949       Ops.push_back(HiLd);
15950       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15951                              Ops.size());
15952     }
15953
15954     LoAddr = St->getBasePtr();
15955     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15956                          DAG.getConstant(4, MVT::i32));
15957
15958     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15959                                 St->getPointerInfo(),
15960                                 St->isVolatile(), St->isNonTemporal(),
15961                                 St->getAlignment());
15962     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15963                                 St->getPointerInfo().getWithOffset(4),
15964                                 St->isVolatile(),
15965                                 St->isNonTemporal(),
15966                                 MinAlign(St->getAlignment(), 4));
15967     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15968   }
15969   return SDValue();
15970 }
15971
15972 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15973 /// and return the operands for the horizontal operation in LHS and RHS.  A
15974 /// horizontal operation performs the binary operation on successive elements
15975 /// of its first operand, then on successive elements of its second operand,
15976 /// returning the resulting values in a vector.  For example, if
15977 ///   A = < float a0, float a1, float a2, float a3 >
15978 /// and
15979 ///   B = < float b0, float b1, float b2, float b3 >
15980 /// then the result of doing a horizontal operation on A and B is
15981 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15982 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15983 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15984 /// set to A, RHS to B, and the routine returns 'true'.
15985 /// Note that the binary operation should have the property that if one of the
15986 /// operands is UNDEF then the result is UNDEF.
15987 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15988   // Look for the following pattern: if
15989   //   A = < float a0, float a1, float a2, float a3 >
15990   //   B = < float b0, float b1, float b2, float b3 >
15991   // and
15992   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15993   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15994   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15995   // which is A horizontal-op B.
15996
15997   // At least one of the operands should be a vector shuffle.
15998   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15999       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16000     return false;
16001
16002   EVT VT = LHS.getValueType();
16003
16004   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16005          "Unsupported vector type for horizontal add/sub");
16006
16007   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16008   // operate independently on 128-bit lanes.
16009   unsigned NumElts = VT.getVectorNumElements();
16010   unsigned NumLanes = VT.getSizeInBits()/128;
16011   unsigned NumLaneElts = NumElts / NumLanes;
16012   assert((NumLaneElts % 2 == 0) &&
16013          "Vector type should have an even number of elements in each lane");
16014   unsigned HalfLaneElts = NumLaneElts/2;
16015
16016   // View LHS in the form
16017   //   LHS = VECTOR_SHUFFLE A, B, LMask
16018   // If LHS is not a shuffle then pretend it is the shuffle
16019   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16020   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16021   // type VT.
16022   SDValue A, B;
16023   SmallVector<int, 16> LMask(NumElts);
16024   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16025     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16026       A = LHS.getOperand(0);
16027     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16028       B = LHS.getOperand(1);
16029     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16030     std::copy(Mask.begin(), Mask.end(), LMask.begin());
16031   } else {
16032     if (LHS.getOpcode() != ISD::UNDEF)
16033       A = LHS;
16034     for (unsigned i = 0; i != NumElts; ++i)
16035       LMask[i] = i;
16036   }
16037
16038   // Likewise, view RHS in the form
16039   //   RHS = VECTOR_SHUFFLE C, D, RMask
16040   SDValue C, D;
16041   SmallVector<int, 16> RMask(NumElts);
16042   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16043     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16044       C = RHS.getOperand(0);
16045     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16046       D = RHS.getOperand(1);
16047     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16048     std::copy(Mask.begin(), Mask.end(), RMask.begin());
16049   } else {
16050     if (RHS.getOpcode() != ISD::UNDEF)
16051       C = RHS;
16052     for (unsigned i = 0; i != NumElts; ++i)
16053       RMask[i] = i;
16054   }
16055
16056   // Check that the shuffles are both shuffling the same vectors.
16057   if (!(A == C && B == D) && !(A == D && B == C))
16058     return false;
16059
16060   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16061   if (!A.getNode() && !B.getNode())
16062     return false;
16063
16064   // If A and B occur in reverse order in RHS, then "swap" them (which means
16065   // rewriting the mask).
16066   if (A != C)
16067     CommuteVectorShuffleMask(RMask, NumElts);
16068
16069   // At this point LHS and RHS are equivalent to
16070   //   LHS = VECTOR_SHUFFLE A, B, LMask
16071   //   RHS = VECTOR_SHUFFLE A, B, RMask
16072   // Check that the masks correspond to performing a horizontal operation.
16073   for (unsigned i = 0; i != NumElts; ++i) {
16074     int LIdx = LMask[i], RIdx = RMask[i];
16075
16076     // Ignore any UNDEF components.
16077     if (LIdx < 0 || RIdx < 0 ||
16078         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16079         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16080       continue;
16081
16082     // Check that successive elements are being operated on.  If not, this is
16083     // not a horizontal operation.
16084     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16085     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16086     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16087     if (!(LIdx == Index && RIdx == Index + 1) &&
16088         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16089       return false;
16090   }
16091
16092   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16093   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16094   return true;
16095 }
16096
16097 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16098 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16099                                   const X86Subtarget *Subtarget) {
16100   EVT VT = N->getValueType(0);
16101   SDValue LHS = N->getOperand(0);
16102   SDValue RHS = N->getOperand(1);
16103
16104   // Try to synthesize horizontal adds from adds of shuffles.
16105   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16106        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16107       isHorizontalBinOp(LHS, RHS, true))
16108     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16109   return SDValue();
16110 }
16111
16112 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16113 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16114                                   const X86Subtarget *Subtarget) {
16115   EVT VT = N->getValueType(0);
16116   SDValue LHS = N->getOperand(0);
16117   SDValue RHS = N->getOperand(1);
16118
16119   // Try to synthesize horizontal subs from subs of shuffles.
16120   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16121        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16122       isHorizontalBinOp(LHS, RHS, false))
16123     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16124   return SDValue();
16125 }
16126
16127 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16128 /// X86ISD::FXOR nodes.
16129 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16130   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16131   // F[X]OR(0.0, x) -> x
16132   // F[X]OR(x, 0.0) -> x
16133   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16134     if (C->getValueAPF().isPosZero())
16135       return N->getOperand(1);
16136   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16137     if (C->getValueAPF().isPosZero())
16138       return N->getOperand(0);
16139   return SDValue();
16140 }
16141
16142 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16143 /// X86ISD::FMAX nodes.
16144 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16145   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16146
16147   // Only perform optimizations if UnsafeMath is used.
16148   if (!DAG.getTarget().Options.UnsafeFPMath)
16149     return SDValue();
16150
16151   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16152   // into FMINC and FMAXC, which are Commutative operations.
16153   unsigned NewOp = 0;
16154   switch (N->getOpcode()) {
16155     default: llvm_unreachable("unknown opcode");
16156     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
16157     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
16158   }
16159
16160   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16161                      N->getOperand(0), N->getOperand(1));
16162 }
16163
16164
16165 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16166 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16167   // FAND(0.0, x) -> 0.0
16168   // FAND(x, 0.0) -> 0.0
16169   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16170     if (C->getValueAPF().isPosZero())
16171       return N->getOperand(0);
16172   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16173     if (C->getValueAPF().isPosZero())
16174       return N->getOperand(1);
16175   return SDValue();
16176 }
16177
16178 static SDValue PerformBTCombine(SDNode *N,
16179                                 SelectionDAG &DAG,
16180                                 TargetLowering::DAGCombinerInfo &DCI) {
16181   // BT ignores high bits in the bit index operand.
16182   SDValue Op1 = N->getOperand(1);
16183   if (Op1.hasOneUse()) {
16184     unsigned BitWidth = Op1.getValueSizeInBits();
16185     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16186     APInt KnownZero, KnownOne;
16187     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16188                                           !DCI.isBeforeLegalizeOps());
16189     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16190     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16191         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16192       DCI.CommitTargetLoweringOpt(TLO);
16193   }
16194   return SDValue();
16195 }
16196
16197 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16198   SDValue Op = N->getOperand(0);
16199   if (Op.getOpcode() == ISD::BITCAST)
16200     Op = Op.getOperand(0);
16201   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16202   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16203       VT.getVectorElementType().getSizeInBits() ==
16204       OpVT.getVectorElementType().getSizeInBits()) {
16205     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16206   }
16207   return SDValue();
16208 }
16209
16210 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16211                                   TargetLowering::DAGCombinerInfo &DCI,
16212                                   const X86Subtarget *Subtarget) {
16213   if (!DCI.isBeforeLegalizeOps())
16214     return SDValue();
16215
16216   if (!Subtarget->hasAVX())
16217     return SDValue();
16218
16219   EVT VT = N->getValueType(0);
16220   SDValue Op = N->getOperand(0);
16221   EVT OpVT = Op.getValueType();
16222   DebugLoc dl = N->getDebugLoc();
16223
16224   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16225       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16226
16227     if (Subtarget->hasAVX2())
16228       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16229
16230     // Optimize vectors in AVX mode
16231     // Sign extend  v8i16 to v8i32 and
16232     //              v4i32 to v4i64
16233     //
16234     // Divide input vector into two parts
16235     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16236     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16237     // concat the vectors to original VT
16238
16239     unsigned NumElems = OpVT.getVectorNumElements();
16240     SDValue Undef = DAG.getUNDEF(OpVT);
16241
16242     SmallVector<int,8> ShufMask1(NumElems, -1);
16243     for (unsigned i = 0; i != NumElems/2; ++i)
16244       ShufMask1[i] = i;
16245
16246     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16247
16248     SmallVector<int,8> ShufMask2(NumElems, -1);
16249     for (unsigned i = 0; i != NumElems/2; ++i)
16250       ShufMask2[i] = i + NumElems/2;
16251
16252     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16253
16254     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16255                                   VT.getVectorNumElements()/2);
16256
16257     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16258     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16259
16260     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16261   }
16262   return SDValue();
16263 }
16264
16265 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16266                                  const X86Subtarget* Subtarget) {
16267   DebugLoc dl = N->getDebugLoc();
16268   EVT VT = N->getValueType(0);
16269
16270   // Let legalize expand this if it isn't a legal type yet.
16271   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16272     return SDValue();
16273
16274   EVT ScalarVT = VT.getScalarType();
16275   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16276       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16277     return SDValue();
16278
16279   SDValue A = N->getOperand(0);
16280   SDValue B = N->getOperand(1);
16281   SDValue C = N->getOperand(2);
16282
16283   bool NegA = (A.getOpcode() == ISD::FNEG);
16284   bool NegB = (B.getOpcode() == ISD::FNEG);
16285   bool NegC = (C.getOpcode() == ISD::FNEG);
16286
16287   // Negative multiplication when NegA xor NegB
16288   bool NegMul = (NegA != NegB);
16289   if (NegA)
16290     A = A.getOperand(0);
16291   if (NegB)
16292     B = B.getOperand(0);
16293   if (NegC)
16294     C = C.getOperand(0);
16295
16296   unsigned Opcode;
16297   if (!NegMul)
16298     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16299   else
16300     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16301
16302   return DAG.getNode(Opcode, dl, VT, A, B, C);
16303 }
16304
16305 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16306                                   TargetLowering::DAGCombinerInfo &DCI,
16307                                   const X86Subtarget *Subtarget) {
16308   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
16309   //           (and (i32 x86isd::setcc_carry), 1)
16310   // This eliminates the zext. This transformation is necessary because
16311   // ISD::SETCC is always legalized to i8.
16312   DebugLoc dl = N->getDebugLoc();
16313   SDValue N0 = N->getOperand(0);
16314   EVT VT = N->getValueType(0);
16315   EVT OpVT = N0.getValueType();
16316
16317   if (N0.getOpcode() == ISD::AND &&
16318       N0.hasOneUse() &&
16319       N0.getOperand(0).hasOneUse()) {
16320     SDValue N00 = N0.getOperand(0);
16321     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16322       return SDValue();
16323     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16324     if (!C || C->getZExtValue() != 1)
16325       return SDValue();
16326     return DAG.getNode(ISD::AND, dl, VT,
16327                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16328                                    N00.getOperand(0), N00.getOperand(1)),
16329                        DAG.getConstant(1, VT));
16330   }
16331
16332   // Optimize vectors in AVX mode:
16333   //
16334   //   v8i16 -> v8i32
16335   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
16336   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
16337   //   Concat upper and lower parts.
16338   //
16339   //   v4i32 -> v4i64
16340   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
16341   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
16342   //   Concat upper and lower parts.
16343   //
16344   if (!DCI.isBeforeLegalizeOps())
16345     return SDValue();
16346
16347   if (!Subtarget->hasAVX())
16348     return SDValue();
16349
16350   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16351       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
16352
16353     if (Subtarget->hasAVX2())
16354       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16355
16356     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16357     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16358     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16359
16360     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16361                                VT.getVectorNumElements()/2);
16362
16363     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16364     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16365
16366     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16367   }
16368
16369   return SDValue();
16370 }
16371
16372 // Optimize x == -y --> x+y == 0
16373 //          x != -y --> x+y != 0
16374 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16375   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16376   SDValue LHS = N->getOperand(0);
16377   SDValue RHS = N->getOperand(1);
16378
16379   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16380     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16381       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16382         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16383                                    LHS.getValueType(), RHS, LHS.getOperand(1));
16384         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16385                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16386       }
16387   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16388     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16389       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16390         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16391                                    RHS.getValueType(), LHS, RHS.getOperand(1));
16392         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16393                             addV, DAG.getConstant(0, addV.getValueType()), CC);
16394       }
16395   return SDValue();
16396 }
16397
16398 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16399 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16400                                    TargetLowering::DAGCombinerInfo &DCI,
16401                                    const X86Subtarget *Subtarget) {
16402   DebugLoc DL = N->getDebugLoc();
16403   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16404   SDValue EFLAGS = N->getOperand(1);
16405
16406   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16407   // a zext and produces an all-ones bit which is more useful than 0/1 in some
16408   // cases.
16409   if (CC == X86::COND_B)
16410     return DAG.getNode(ISD::AND, DL, MVT::i8,
16411                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16412                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
16413                        DAG.getConstant(1, MVT::i8));
16414
16415   SDValue Flags;
16416
16417   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16418   if (Flags.getNode()) {
16419     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16420     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16421   }
16422
16423   return SDValue();
16424 }
16425
16426 // Optimize branch condition evaluation.
16427 //
16428 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16429                                     TargetLowering::DAGCombinerInfo &DCI,
16430                                     const X86Subtarget *Subtarget) {
16431   DebugLoc DL = N->getDebugLoc();
16432   SDValue Chain = N->getOperand(0);
16433   SDValue Dest = N->getOperand(1);
16434   SDValue EFLAGS = N->getOperand(3);
16435   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16436
16437   SDValue Flags;
16438
16439   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16440   if (Flags.getNode()) {
16441     SDValue Cond = DAG.getConstant(CC, MVT::i8);
16442     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16443                        Flags);
16444   }
16445
16446   return SDValue();
16447 }
16448
16449 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16450   SDValue Op0 = N->getOperand(0);
16451   EVT InVT = Op0->getValueType(0);
16452
16453   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16454   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16455     DebugLoc dl = N->getDebugLoc();
16456     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16457     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16458     // Notice that we use SINT_TO_FP because we know that the high bits
16459     // are zero and SINT_TO_FP is better supported by the hardware.
16460     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16461   }
16462
16463   return SDValue();
16464 }
16465
16466 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16467                                         const X86TargetLowering *XTLI) {
16468   SDValue Op0 = N->getOperand(0);
16469   EVT InVT = Op0->getValueType(0);
16470
16471   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16472   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16473     DebugLoc dl = N->getDebugLoc();
16474     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16475     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16476     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16477   }
16478
16479   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16480   // a 32-bit target where SSE doesn't support i64->FP operations.
16481   if (Op0.getOpcode() == ISD::LOAD) {
16482     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16483     EVT VT = Ld->getValueType(0);
16484     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16485         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16486         !XTLI->getSubtarget()->is64Bit() &&
16487         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16488       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16489                                           Ld->getChain(), Op0, DAG);
16490       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16491       return FILDChain;
16492     }
16493   }
16494   return SDValue();
16495 }
16496
16497 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16498 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16499                                  X86TargetLowering::DAGCombinerInfo &DCI) {
16500   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16501   // the result is either zero or one (depending on the input carry bit).
16502   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16503   if (X86::isZeroNode(N->getOperand(0)) &&
16504       X86::isZeroNode(N->getOperand(1)) &&
16505       // We don't have a good way to replace an EFLAGS use, so only do this when
16506       // dead right now.
16507       SDValue(N, 1).use_empty()) {
16508     DebugLoc DL = N->getDebugLoc();
16509     EVT VT = N->getValueType(0);
16510     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16511     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16512                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16513                                            DAG.getConstant(X86::COND_B,MVT::i8),
16514                                            N->getOperand(2)),
16515                                DAG.getConstant(1, VT));
16516     return DCI.CombineTo(N, Res1, CarryOut);
16517   }
16518
16519   return SDValue();
16520 }
16521
16522 // fold (add Y, (sete  X, 0)) -> adc  0, Y
16523 //      (add Y, (setne X, 0)) -> sbb -1, Y
16524 //      (sub (sete  X, 0), Y) -> sbb  0, Y
16525 //      (sub (setne X, 0), Y) -> adc -1, Y
16526 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16527   DebugLoc DL = N->getDebugLoc();
16528
16529   // Look through ZExts.
16530   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16531   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16532     return SDValue();
16533
16534   SDValue SetCC = Ext.getOperand(0);
16535   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16536     return SDValue();
16537
16538   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16539   if (CC != X86::COND_E && CC != X86::COND_NE)
16540     return SDValue();
16541
16542   SDValue Cmp = SetCC.getOperand(1);
16543   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16544       !X86::isZeroNode(Cmp.getOperand(1)) ||
16545       !Cmp.getOperand(0).getValueType().isInteger())
16546     return SDValue();
16547
16548   SDValue CmpOp0 = Cmp.getOperand(0);
16549   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16550                                DAG.getConstant(1, CmpOp0.getValueType()));
16551
16552   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16553   if (CC == X86::COND_NE)
16554     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16555                        DL, OtherVal.getValueType(), OtherVal,
16556                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16557   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16558                      DL, OtherVal.getValueType(), OtherVal,
16559                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16560 }
16561
16562 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16563 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16564                                  const X86Subtarget *Subtarget) {
16565   EVT VT = N->getValueType(0);
16566   SDValue Op0 = N->getOperand(0);
16567   SDValue Op1 = N->getOperand(1);
16568
16569   // Try to synthesize horizontal adds from adds of shuffles.
16570   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16571        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16572       isHorizontalBinOp(Op0, Op1, true))
16573     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16574
16575   return OptimizeConditionalInDecrement(N, DAG);
16576 }
16577
16578 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16579                                  const X86Subtarget *Subtarget) {
16580   SDValue Op0 = N->getOperand(0);
16581   SDValue Op1 = N->getOperand(1);
16582
16583   // X86 can't encode an immediate LHS of a sub. See if we can push the
16584   // negation into a preceding instruction.
16585   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16586     // If the RHS of the sub is a XOR with one use and a constant, invert the
16587     // immediate. Then add one to the LHS of the sub so we can turn
16588     // X-Y -> X+~Y+1, saving one register.
16589     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16590         isa<ConstantSDNode>(Op1.getOperand(1))) {
16591       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16592       EVT VT = Op0.getValueType();
16593       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16594                                    Op1.getOperand(0),
16595                                    DAG.getConstant(~XorC, VT));
16596       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16597                          DAG.getConstant(C->getAPIntValue()+1, VT));
16598     }
16599   }
16600
16601   // Try to synthesize horizontal adds from adds of shuffles.
16602   EVT VT = N->getValueType(0);
16603   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16604        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16605       isHorizontalBinOp(Op0, Op1, true))
16606     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16607
16608   return OptimizeConditionalInDecrement(N, DAG);
16609 }
16610
16611 /// performVZEXTCombine - Performs build vector combines
16612 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16613                                         TargetLowering::DAGCombinerInfo &DCI,
16614                                         const X86Subtarget *Subtarget) {
16615   // (vzext (bitcast (vzext (x)) -> (vzext x)
16616   SDValue In = N->getOperand(0);
16617   while (In.getOpcode() == ISD::BITCAST)
16618     In = In.getOperand(0);
16619
16620   if (In.getOpcode() != X86ISD::VZEXT)
16621     return SDValue();
16622
16623   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16624 }
16625
16626 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16627                                              DAGCombinerInfo &DCI) const {
16628   SelectionDAG &DAG = DCI.DAG;
16629   switch (N->getOpcode()) {
16630   default: break;
16631   case ISD::EXTRACT_VECTOR_ELT:
16632     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16633   case ISD::VSELECT:
16634   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16635   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16636   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16637   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16638   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16639   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16640   case ISD::SHL:
16641   case ISD::SRA:
16642   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16643   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16644   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16645   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16646   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16647   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16648   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16649   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16650   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16651   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16652   case X86ISD::FXOR:
16653   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16654   case X86ISD::FMIN:
16655   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16656   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16657   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16658   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16659   case ISD::ANY_EXTEND:
16660   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16661   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16662   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16663   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16664   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16665   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16666   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
16667   case X86ISD::SHUFP:       // Handle all target specific shuffles
16668   case X86ISD::PALIGN:
16669   case X86ISD::UNPCKH:
16670   case X86ISD::UNPCKL:
16671   case X86ISD::MOVHLPS:
16672   case X86ISD::MOVLHPS:
16673   case X86ISD::PSHUFD:
16674   case X86ISD::PSHUFHW:
16675   case X86ISD::PSHUFLW:
16676   case X86ISD::MOVSS:
16677   case X86ISD::MOVSD:
16678   case X86ISD::VPERMILP:
16679   case X86ISD::VPERM2X128:
16680   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16681   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16682   }
16683
16684   return SDValue();
16685 }
16686
16687 /// isTypeDesirableForOp - Return true if the target has native support for
16688 /// the specified value type and it is 'desirable' to use the type for the
16689 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16690 /// instruction encodings are longer and some i16 instructions are slow.
16691 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16692   if (!isTypeLegal(VT))
16693     return false;
16694   if (VT != MVT::i16)
16695     return true;
16696
16697   switch (Opc) {
16698   default:
16699     return true;
16700   case ISD::LOAD:
16701   case ISD::SIGN_EXTEND:
16702   case ISD::ZERO_EXTEND:
16703   case ISD::ANY_EXTEND:
16704   case ISD::SHL:
16705   case ISD::SRL:
16706   case ISD::SUB:
16707   case ISD::ADD:
16708   case ISD::MUL:
16709   case ISD::AND:
16710   case ISD::OR:
16711   case ISD::XOR:
16712     return false;
16713   }
16714 }
16715
16716 /// IsDesirableToPromoteOp - This method query the target whether it is
16717 /// beneficial for dag combiner to promote the specified node. If true, it
16718 /// should return the desired promotion type by reference.
16719 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16720   EVT VT = Op.getValueType();
16721   if (VT != MVT::i16)
16722     return false;
16723
16724   bool Promote = false;
16725   bool Commute = false;
16726   switch (Op.getOpcode()) {
16727   default: break;
16728   case ISD::LOAD: {
16729     LoadSDNode *LD = cast<LoadSDNode>(Op);
16730     // If the non-extending load has a single use and it's not live out, then it
16731     // might be folded.
16732     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16733                                                      Op.hasOneUse()*/) {
16734       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16735              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16736         // The only case where we'd want to promote LOAD (rather then it being
16737         // promoted as an operand is when it's only use is liveout.
16738         if (UI->getOpcode() != ISD::CopyToReg)
16739           return false;
16740       }
16741     }
16742     Promote = true;
16743     break;
16744   }
16745   case ISD::SIGN_EXTEND:
16746   case ISD::ZERO_EXTEND:
16747   case ISD::ANY_EXTEND:
16748     Promote = true;
16749     break;
16750   case ISD::SHL:
16751   case ISD::SRL: {
16752     SDValue N0 = Op.getOperand(0);
16753     // Look out for (store (shl (load), x)).
16754     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16755       return false;
16756     Promote = true;
16757     break;
16758   }
16759   case ISD::ADD:
16760   case ISD::MUL:
16761   case ISD::AND:
16762   case ISD::OR:
16763   case ISD::XOR:
16764     Commute = true;
16765     // fallthrough
16766   case ISD::SUB: {
16767     SDValue N0 = Op.getOperand(0);
16768     SDValue N1 = Op.getOperand(1);
16769     if (!Commute && MayFoldLoad(N1))
16770       return false;
16771     // Avoid disabling potential load folding opportunities.
16772     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16773       return false;
16774     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16775       return false;
16776     Promote = true;
16777   }
16778   }
16779
16780   PVT = MVT::i32;
16781   return Promote;
16782 }
16783
16784 //===----------------------------------------------------------------------===//
16785 //                           X86 Inline Assembly Support
16786 //===----------------------------------------------------------------------===//
16787
16788 namespace {
16789   // Helper to match a string separated by whitespace.
16790   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16791     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16792
16793     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16794       StringRef piece(*args[i]);
16795       if (!s.startswith(piece)) // Check if the piece matches.
16796         return false;
16797
16798       s = s.substr(piece.size());
16799       StringRef::size_type pos = s.find_first_not_of(" \t");
16800       if (pos == 0) // We matched a prefix.
16801         return false;
16802
16803       s = s.substr(pos);
16804     }
16805
16806     return s.empty();
16807   }
16808   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16809 }
16810
16811 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16812   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16813
16814   std::string AsmStr = IA->getAsmString();
16815
16816   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16817   if (!Ty || Ty->getBitWidth() % 16 != 0)
16818     return false;
16819
16820   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16821   SmallVector<StringRef, 4> AsmPieces;
16822   SplitString(AsmStr, AsmPieces, ";\n");
16823
16824   switch (AsmPieces.size()) {
16825   default: return false;
16826   case 1:
16827     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16828     // we will turn this bswap into something that will be lowered to logical
16829     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16830     // lower so don't worry about this.
16831     // bswap $0
16832     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16833         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16834         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16835         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16836         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16837         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16838       // No need to check constraints, nothing other than the equivalent of
16839       // "=r,0" would be valid here.
16840       return IntrinsicLowering::LowerToByteSwap(CI);
16841     }
16842
16843     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16844     if (CI->getType()->isIntegerTy(16) &&
16845         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16846         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16847          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16848       AsmPieces.clear();
16849       const std::string &ConstraintsStr = IA->getConstraintString();
16850       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16851       std::sort(AsmPieces.begin(), AsmPieces.end());
16852       if (AsmPieces.size() == 4 &&
16853           AsmPieces[0] == "~{cc}" &&
16854           AsmPieces[1] == "~{dirflag}" &&
16855           AsmPieces[2] == "~{flags}" &&
16856           AsmPieces[3] == "~{fpsr}")
16857       return IntrinsicLowering::LowerToByteSwap(CI);
16858     }
16859     break;
16860   case 3:
16861     if (CI->getType()->isIntegerTy(32) &&
16862         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16863         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16864         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16865         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16866       AsmPieces.clear();
16867       const std::string &ConstraintsStr = IA->getConstraintString();
16868       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16869       std::sort(AsmPieces.begin(), AsmPieces.end());
16870       if (AsmPieces.size() == 4 &&
16871           AsmPieces[0] == "~{cc}" &&
16872           AsmPieces[1] == "~{dirflag}" &&
16873           AsmPieces[2] == "~{flags}" &&
16874           AsmPieces[3] == "~{fpsr}")
16875         return IntrinsicLowering::LowerToByteSwap(CI);
16876     }
16877
16878     if (CI->getType()->isIntegerTy(64)) {
16879       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16880       if (Constraints.size() >= 2 &&
16881           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16882           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16883         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16884         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16885             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16886             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16887           return IntrinsicLowering::LowerToByteSwap(CI);
16888       }
16889     }
16890     break;
16891   }
16892   return false;
16893 }
16894
16895
16896
16897 /// getConstraintType - Given a constraint letter, return the type of
16898 /// constraint it is for this target.
16899 X86TargetLowering::ConstraintType
16900 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16901   if (Constraint.size() == 1) {
16902     switch (Constraint[0]) {
16903     case 'R':
16904     case 'q':
16905     case 'Q':
16906     case 'f':
16907     case 't':
16908     case 'u':
16909     case 'y':
16910     case 'x':
16911     case 'Y':
16912     case 'l':
16913       return C_RegisterClass;
16914     case 'a':
16915     case 'b':
16916     case 'c':
16917     case 'd':
16918     case 'S':
16919     case 'D':
16920     case 'A':
16921       return C_Register;
16922     case 'I':
16923     case 'J':
16924     case 'K':
16925     case 'L':
16926     case 'M':
16927     case 'N':
16928     case 'G':
16929     case 'C':
16930     case 'e':
16931     case 'Z':
16932       return C_Other;
16933     default:
16934       break;
16935     }
16936   }
16937   return TargetLowering::getConstraintType(Constraint);
16938 }
16939
16940 /// Examine constraint type and operand type and determine a weight value.
16941 /// This object must already have been set up with the operand type
16942 /// and the current alternative constraint selected.
16943 TargetLowering::ConstraintWeight
16944   X86TargetLowering::getSingleConstraintMatchWeight(
16945     AsmOperandInfo &info, const char *constraint) const {
16946   ConstraintWeight weight = CW_Invalid;
16947   Value *CallOperandVal = info.CallOperandVal;
16948     // If we don't have a value, we can't do a match,
16949     // but allow it at the lowest weight.
16950   if (CallOperandVal == NULL)
16951     return CW_Default;
16952   Type *type = CallOperandVal->getType();
16953   // Look at the constraint type.
16954   switch (*constraint) {
16955   default:
16956     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16957   case 'R':
16958   case 'q':
16959   case 'Q':
16960   case 'a':
16961   case 'b':
16962   case 'c':
16963   case 'd':
16964   case 'S':
16965   case 'D':
16966   case 'A':
16967     if (CallOperandVal->getType()->isIntegerTy())
16968       weight = CW_SpecificReg;
16969     break;
16970   case 'f':
16971   case 't':
16972   case 'u':
16973       if (type->isFloatingPointTy())
16974         weight = CW_SpecificReg;
16975       break;
16976   case 'y':
16977       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16978         weight = CW_SpecificReg;
16979       break;
16980   case 'x':
16981   case 'Y':
16982     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16983         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16984       weight = CW_Register;
16985     break;
16986   case 'I':
16987     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16988       if (C->getZExtValue() <= 31)
16989         weight = CW_Constant;
16990     }
16991     break;
16992   case 'J':
16993     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16994       if (C->getZExtValue() <= 63)
16995         weight = CW_Constant;
16996     }
16997     break;
16998   case 'K':
16999     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17000       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17001         weight = CW_Constant;
17002     }
17003     break;
17004   case 'L':
17005     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17006       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17007         weight = CW_Constant;
17008     }
17009     break;
17010   case 'M':
17011     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17012       if (C->getZExtValue() <= 3)
17013         weight = CW_Constant;
17014     }
17015     break;
17016   case 'N':
17017     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17018       if (C->getZExtValue() <= 0xff)
17019         weight = CW_Constant;
17020     }
17021     break;
17022   case 'G':
17023   case 'C':
17024     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17025       weight = CW_Constant;
17026     }
17027     break;
17028   case 'e':
17029     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17030       if ((C->getSExtValue() >= -0x80000000LL) &&
17031           (C->getSExtValue() <= 0x7fffffffLL))
17032         weight = CW_Constant;
17033     }
17034     break;
17035   case 'Z':
17036     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17037       if (C->getZExtValue() <= 0xffffffff)
17038         weight = CW_Constant;
17039     }
17040     break;
17041   }
17042   return weight;
17043 }
17044
17045 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17046 /// with another that has more specific requirements based on the type of the
17047 /// corresponding operand.
17048 const char *X86TargetLowering::
17049 LowerXConstraint(EVT ConstraintVT) const {
17050   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17051   // 'f' like normal targets.
17052   if (ConstraintVT.isFloatingPoint()) {
17053     if (Subtarget->hasSSE2())
17054       return "Y";
17055     if (Subtarget->hasSSE1())
17056       return "x";
17057   }
17058
17059   return TargetLowering::LowerXConstraint(ConstraintVT);
17060 }
17061
17062 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17063 /// vector.  If it is invalid, don't add anything to Ops.
17064 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17065                                                      std::string &Constraint,
17066                                                      std::vector<SDValue>&Ops,
17067                                                      SelectionDAG &DAG) const {
17068   SDValue Result(0, 0);
17069
17070   // Only support length 1 constraints for now.
17071   if (Constraint.length() > 1) return;
17072
17073   char ConstraintLetter = Constraint[0];
17074   switch (ConstraintLetter) {
17075   default: break;
17076   case 'I':
17077     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17078       if (C->getZExtValue() <= 31) {
17079         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17080         break;
17081       }
17082     }
17083     return;
17084   case 'J':
17085     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17086       if (C->getZExtValue() <= 63) {
17087         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17088         break;
17089       }
17090     }
17091     return;
17092   case 'K':
17093     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17094       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17095         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17096         break;
17097       }
17098     }
17099     return;
17100   case 'N':
17101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17102       if (C->getZExtValue() <= 255) {
17103         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17104         break;
17105       }
17106     }
17107     return;
17108   case 'e': {
17109     // 32-bit signed value
17110     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17111       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17112                                            C->getSExtValue())) {
17113         // Widen to 64 bits here to get it sign extended.
17114         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17115         break;
17116       }
17117     // FIXME gcc accepts some relocatable values here too, but only in certain
17118     // memory models; it's complicated.
17119     }
17120     return;
17121   }
17122   case 'Z': {
17123     // 32-bit unsigned value
17124     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17125       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17126                                            C->getZExtValue())) {
17127         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17128         break;
17129       }
17130     }
17131     // FIXME gcc accepts some relocatable values here too, but only in certain
17132     // memory models; it's complicated.
17133     return;
17134   }
17135   case 'i': {
17136     // Literal immediates are always ok.
17137     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17138       // Widen to 64 bits here to get it sign extended.
17139       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17140       break;
17141     }
17142
17143     // In any sort of PIC mode addresses need to be computed at runtime by
17144     // adding in a register or some sort of table lookup.  These can't
17145     // be used as immediates.
17146     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17147       return;
17148
17149     // If we are in non-pic codegen mode, we allow the address of a global (with
17150     // an optional displacement) to be used with 'i'.
17151     GlobalAddressSDNode *GA = 0;
17152     int64_t Offset = 0;
17153
17154     // Match either (GA), (GA+C), (GA+C1+C2), etc.
17155     while (1) {
17156       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17157         Offset += GA->getOffset();
17158         break;
17159       } else if (Op.getOpcode() == ISD::ADD) {
17160         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17161           Offset += C->getZExtValue();
17162           Op = Op.getOperand(0);
17163           continue;
17164         }
17165       } else if (Op.getOpcode() == ISD::SUB) {
17166         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17167           Offset += -C->getZExtValue();
17168           Op = Op.getOperand(0);
17169           continue;
17170         }
17171       }
17172
17173       // Otherwise, this isn't something we can handle, reject it.
17174       return;
17175     }
17176
17177     const GlobalValue *GV = GA->getGlobal();
17178     // If we require an extra load to get this address, as in PIC mode, we
17179     // can't accept it.
17180     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17181                                                         getTargetMachine())))
17182       return;
17183
17184     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17185                                         GA->getValueType(0), Offset);
17186     break;
17187   }
17188   }
17189
17190   if (Result.getNode()) {
17191     Ops.push_back(Result);
17192     return;
17193   }
17194   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17195 }
17196
17197 std::pair<unsigned, const TargetRegisterClass*>
17198 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17199                                                 EVT VT) const {
17200   // First, see if this is a constraint that directly corresponds to an LLVM
17201   // register class.
17202   if (Constraint.size() == 1) {
17203     // GCC Constraint Letters
17204     switch (Constraint[0]) {
17205     default: break;
17206       // TODO: Slight differences here in allocation order and leaving
17207       // RIP in the class. Do they matter any more here than they do
17208       // in the normal allocation?
17209     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17210       if (Subtarget->is64Bit()) {
17211         if (VT == MVT::i32 || VT == MVT::f32)
17212           return std::make_pair(0U, &X86::GR32RegClass);
17213         if (VT == MVT::i16)
17214           return std::make_pair(0U, &X86::GR16RegClass);
17215         if (VT == MVT::i8 || VT == MVT::i1)
17216           return std::make_pair(0U, &X86::GR8RegClass);
17217         if (VT == MVT::i64 || VT == MVT::f64)
17218           return std::make_pair(0U, &X86::GR64RegClass);
17219         break;
17220       }
17221       // 32-bit fallthrough
17222     case 'Q':   // Q_REGS
17223       if (VT == MVT::i32 || VT == MVT::f32)
17224         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17225       if (VT == MVT::i16)
17226         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17227       if (VT == MVT::i8 || VT == MVT::i1)
17228         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17229       if (VT == MVT::i64)
17230         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17231       break;
17232     case 'r':   // GENERAL_REGS
17233     case 'l':   // INDEX_REGS
17234       if (VT == MVT::i8 || VT == MVT::i1)
17235         return std::make_pair(0U, &X86::GR8RegClass);
17236       if (VT == MVT::i16)
17237         return std::make_pair(0U, &X86::GR16RegClass);
17238       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17239         return std::make_pair(0U, &X86::GR32RegClass);
17240       return std::make_pair(0U, &X86::GR64RegClass);
17241     case 'R':   // LEGACY_REGS
17242       if (VT == MVT::i8 || VT == MVT::i1)
17243         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17244       if (VT == MVT::i16)
17245         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17246       if (VT == MVT::i32 || !Subtarget->is64Bit())
17247         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17248       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17249     case 'f':  // FP Stack registers.
17250       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17251       // value to the correct fpstack register class.
17252       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17253         return std::make_pair(0U, &X86::RFP32RegClass);
17254       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17255         return std::make_pair(0U, &X86::RFP64RegClass);
17256       return std::make_pair(0U, &X86::RFP80RegClass);
17257     case 'y':   // MMX_REGS if MMX allowed.
17258       if (!Subtarget->hasMMX()) break;
17259       return std::make_pair(0U, &X86::VR64RegClass);
17260     case 'Y':   // SSE_REGS if SSE2 allowed
17261       if (!Subtarget->hasSSE2()) break;
17262       // FALL THROUGH.
17263     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17264       if (!Subtarget->hasSSE1()) break;
17265
17266       switch (VT.getSimpleVT().SimpleTy) {
17267       default: break;
17268       // Scalar SSE types.
17269       case MVT::f32:
17270       case MVT::i32:
17271         return std::make_pair(0U, &X86::FR32RegClass);
17272       case MVT::f64:
17273       case MVT::i64:
17274         return std::make_pair(0U, &X86::FR64RegClass);
17275       // Vector types.
17276       case MVT::v16i8:
17277       case MVT::v8i16:
17278       case MVT::v4i32:
17279       case MVT::v2i64:
17280       case MVT::v4f32:
17281       case MVT::v2f64:
17282         return std::make_pair(0U, &X86::VR128RegClass);
17283       // AVX types.
17284       case MVT::v32i8:
17285       case MVT::v16i16:
17286       case MVT::v8i32:
17287       case MVT::v4i64:
17288       case MVT::v8f32:
17289       case MVT::v4f64:
17290         return std::make_pair(0U, &X86::VR256RegClass);
17291       }
17292       break;
17293     }
17294   }
17295
17296   // Use the default implementation in TargetLowering to convert the register
17297   // constraint into a member of a register class.
17298   std::pair<unsigned, const TargetRegisterClass*> Res;
17299   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17300
17301   // Not found as a standard register?
17302   if (Res.second == 0) {
17303     // Map st(0) -> st(7) -> ST0
17304     if (Constraint.size() == 7 && Constraint[0] == '{' &&
17305         tolower(Constraint[1]) == 's' &&
17306         tolower(Constraint[2]) == 't' &&
17307         Constraint[3] == '(' &&
17308         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17309         Constraint[5] == ')' &&
17310         Constraint[6] == '}') {
17311
17312       Res.first = X86::ST0+Constraint[4]-'0';
17313       Res.second = &X86::RFP80RegClass;
17314       return Res;
17315     }
17316
17317     // GCC allows "st(0)" to be called just plain "st".
17318     if (StringRef("{st}").equals_lower(Constraint)) {
17319       Res.first = X86::ST0;
17320       Res.second = &X86::RFP80RegClass;
17321       return Res;
17322     }
17323
17324     // flags -> EFLAGS
17325     if (StringRef("{flags}").equals_lower(Constraint)) {
17326       Res.first = X86::EFLAGS;
17327       Res.second = &X86::CCRRegClass;
17328       return Res;
17329     }
17330
17331     // 'A' means EAX + EDX.
17332     if (Constraint == "A") {
17333       Res.first = X86::EAX;
17334       Res.second = &X86::GR32_ADRegClass;
17335       return Res;
17336     }
17337     return Res;
17338   }
17339
17340   // Otherwise, check to see if this is a register class of the wrong value
17341   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17342   // turn into {ax},{dx}.
17343   if (Res.second->hasType(VT))
17344     return Res;   // Correct type already, nothing to do.
17345
17346   // All of the single-register GCC register classes map their values onto
17347   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
17348   // really want an 8-bit or 32-bit register, map to the appropriate register
17349   // class and return the appropriate register.
17350   if (Res.second == &X86::GR16RegClass) {
17351     if (VT == MVT::i8) {
17352       unsigned DestReg = 0;
17353       switch (Res.first) {
17354       default: break;
17355       case X86::AX: DestReg = X86::AL; break;
17356       case X86::DX: DestReg = X86::DL; break;
17357       case X86::CX: DestReg = X86::CL; break;
17358       case X86::BX: DestReg = X86::BL; break;
17359       }
17360       if (DestReg) {
17361         Res.first = DestReg;
17362         Res.second = &X86::GR8RegClass;
17363       }
17364     } else if (VT == MVT::i32) {
17365       unsigned DestReg = 0;
17366       switch (Res.first) {
17367       default: break;
17368       case X86::AX: DestReg = X86::EAX; break;
17369       case X86::DX: DestReg = X86::EDX; break;
17370       case X86::CX: DestReg = X86::ECX; break;
17371       case X86::BX: DestReg = X86::EBX; break;
17372       case X86::SI: DestReg = X86::ESI; break;
17373       case X86::DI: DestReg = X86::EDI; break;
17374       case X86::BP: DestReg = X86::EBP; break;
17375       case X86::SP: DestReg = X86::ESP; break;
17376       }
17377       if (DestReg) {
17378         Res.first = DestReg;
17379         Res.second = &X86::GR32RegClass;
17380       }
17381     } else if (VT == MVT::i64) {
17382       unsigned DestReg = 0;
17383       switch (Res.first) {
17384       default: break;
17385       case X86::AX: DestReg = X86::RAX; break;
17386       case X86::DX: DestReg = X86::RDX; break;
17387       case X86::CX: DestReg = X86::RCX; break;
17388       case X86::BX: DestReg = X86::RBX; break;
17389       case X86::SI: DestReg = X86::RSI; break;
17390       case X86::DI: DestReg = X86::RDI; break;
17391       case X86::BP: DestReg = X86::RBP; break;
17392       case X86::SP: DestReg = X86::RSP; break;
17393       }
17394       if (DestReg) {
17395         Res.first = DestReg;
17396         Res.second = &X86::GR64RegClass;
17397       }
17398     }
17399   } else if (Res.second == &X86::FR32RegClass ||
17400              Res.second == &X86::FR64RegClass ||
17401              Res.second == &X86::VR128RegClass) {
17402     // Handle references to XMM physical registers that got mapped into the
17403     // wrong class.  This can happen with constraints like {xmm0} where the
17404     // target independent register mapper will just pick the first match it can
17405     // find, ignoring the required type.
17406
17407     if (VT == MVT::f32 || VT == MVT::i32)
17408       Res.second = &X86::FR32RegClass;
17409     else if (VT == MVT::f64 || VT == MVT::i64)
17410       Res.second = &X86::FR64RegClass;
17411     else if (X86::VR128RegClass.hasType(VT))
17412       Res.second = &X86::VR128RegClass;
17413     else if (X86::VR256RegClass.hasType(VT))
17414       Res.second = &X86::VR256RegClass;
17415   }
17416
17417   return Res;
17418 }